【发布时间】:2015-07-07 14:59:36
【问题描述】:
当我在搜索 AES 加密/解密实现时,我在 SO 中发现了一些问题的链接,例如:
- AES Encryption Java -> PHP -> Java
- AES encryption in java
- AES encryption & security flaw
- Is it safe to use PBKDF2 with SHA256 to generate 128-bit AES keys?
我还发现了以下网页,它提供了易于使用的 PHP 和 Java 中的 AES 加密/解密算法实现,library。
问题:直接在我们的实时开发项目中使用该 AES 实现库是否安全?
这可能需要您执行源代码。因此,由于 PHP 实现可能看起来更长,因此我已经放置了该库的 Java 源代码的基本部分。
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
Aes encryption
*/
public class AES
{
private static SecretKeySpec secretKey ;
private static byte[] key ;
private static String decryptedString;
private static String encryptedString;
public static void setKey(String myKey){
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
System.out.println(key.length);
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // use only first 128 bit
System.out.println(key.length);
System.out.println(new String(key,"UTF-8"));
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getDecryptedString() {
return decryptedString;
}
public static void setDecryptedString(String decryptedString) {
AES.decryptedString = decryptedString;
}
public static String getEncryptedString() {
return encryptedString;
}
public static void setEncryptedString(String encryptedString) {
AES.encryptedString = encryptedString;
}
public static String encrypt(String strToEncrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
setEncryptedString(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
}
catch (Exception e)
{
System.out.println("Error while encrypting: "+e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt)
{
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
setDecryptedString(new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));
}
catch (Exception e)
{
System.out.println("Error while decrypting: "+e.toString());
}
return null;
}
}
注意:请不要将此标记为过于宽泛的问题并忽略它,我之所以这样问是因为我需要在将其用于下一个项目之前确定。
提前感谢您宝贵的时间!
【问题讨论】:
-
Cipher.getInstance("AES/ECB/PKCS5Padding");不要使用 ECB,使用 CBC。另外,你应该authenticate your ciphertexts。
标签: java php security cryptography aes