我正在尝试实现AES CBC 256算法。在网上学习并检查了很少的代码样本后,我意识到有两种不同的方法来检索SecretKeySpec
,并且两种方法都会产生不同的加密消息。
private static SecretKeySpec getSecretKeySpec(String secretKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
String salt = "a";
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), salt.getBytes(), 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
return new SecretKeySpec(tmp.getEncoded(), "AES");
}
// private static SecretKeySpec getSecretKeySpec(String secretKey) throws NoSuchAlgorithmException {
//
// MessageDigest digest = MessageDigest.getInstance("SHA-256");
// digest.update(secretKey.getBytes(StandardCharsets.UTF_8));
// byte[] keyBytes = new byte[32];
// System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
// return new SecretKeySpec(keyBytes, "AES");
// }
public static String encrypt(String strToEncrypt, String secret)
{
try
{
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeySpec secretKeySpec = getSecretKeySpec(secret);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
[请让我知道AES CBC 256位加密的正确实现是哪一个?
AES&CBC没有指定任何有关如何导出密钥的内容。任何128、192和256位密钥均有效。使用PBKDF2WithHmacSHA256之类的实际密钥派生功能比单次传递SHA-256来降低暴力攻击的速度要好,但是,否则它们都会生成有效的密钥。