用Java加密和解密字符串

我是密码学的新手。我希望学习如何在文件中加密和解密文本……当我在net中引用相关文章时。我怀疑对同一文本进行多次加密后,单个文本的加密文本是否会相同?谁能解决我的疑问?

回答:

    public String encrypt(String str) {

try {

// Encode the string into bytes using utf-8

byte[] utf8 = str.getBytes("UTF8");

// Encrypt

byte[] enc = ecipher.doFinal(utf8);

// Encode bytes to base64 to get a string

return new sun.misc.BASE64Encoder().encode(enc);

} catch (javax.crypto.BadPaddingException e) {

} catch (IllegalBlockSizeException e) {

} catch (UnsupportedEncodingException e) {

} catch (java.io.IOException e) {

}

return null;

}

public String decrypt(String str) {

try {

// Decode base64 to get bytes

byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

// Decrypt

byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8

return new String(utf8, "UTF8");

} catch (javax.crypto.BadPaddingException e) {

} catch (IllegalBlockSizeException e) {

} catch (UnsupportedEncodingException e) {

} catch (java.io.IOException e) {

}

return null;

}

}

这是使用该类的示例:

try {

// Generate a temporary key. In practice, you would save this key.

// See also Encrypting with DES Using a Pass Phrase.

SecretKey key = KeyGenerator.getInstance("DES").generateKey();

// Create encrypter/decrypter class

DesEncrypter encrypter = new DesEncrypter(key);

// Encrypt

String encrypted = encrypter.encrypt("Don't tell anybody!");

// Decrypt

String decrypted = encrypter.decrypt(encrypted);

} catch (Exception e) {

}

以上是 用Java加密和解密字符串 的全部内容, 来源链接: utcz.com/qa/434967.html

回到顶部