【发布时间】:2016-03-11 19:41:36
【问题描述】:
我正在使用 AES 加密字符串,但它没有将“1234567812345678”字符从加密字符串解密回纯文本。对于其他文本(如“Hello World”),它工作正常。还希望保持加密代码只接受 UTF-8 字符。我正在使用以下代码
import java.security.*;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{
public static void main(String[] args)
{
//listing all available cryptographic algorithms
/* for (Provider provider: Security.getProviders()) {
System.out.println(provider.getName());
for (String key: provider.stringPropertyNames())
System.out.println("\t" + key + "\t" + provider.getProperty(key));
}*/
StrongAES saes = new StrongAES();
String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("1234567812345678"));
//String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("Hello world"));
System.out.println(encrypt);
String decrypt = saes.decrypt(new String("Bar12346Bar12346"), new String(encrypt));
System.out.println(decrypt);
}
String encrypt(String key, String text)
{
String encryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
encryptedText = new String(encrypted);
// System.out.println(encryptedText);
}
catch(Exception e)
{
e.printStackTrace();
}
return encryptedText;
}
String decrypt(String key, String encryptedText)
{
String decryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decryptedText = new String(cipher.doFinal(encryptedText.getBytes()));
// System.out.println("Decrypted "+decryptedText);
}
catch(Exception e)
{
e.printStackTrace();
}
return decryptedText;
}
}
【问题讨论】:
-
(1) 您可能正在使用不是很安全的 ECB 模式。 (2) 始终使用像
Cipher.getInstance("AES/CBC/PKCS5Padding")这样的完全限定密码字符串并生成随机IV。 (3) 您应该使用 HMAC 或使用 GCM 或 EAX 等身份验证模式为您的密文添加身份验证。