gpt4 book ai didi

Java - AES CBC 算法生成 SecretKeySpec 的不同方式

转载 作者:行者123 更新时间:2023-12-02 08:46:13 24 4
gpt4 key购买 nike

我正在尝试实现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 没有指定任何有关如何派生 key 的信息。任何 128、192 和 256 位 key 均有效。使用 PBKDF2WithHmacSHA256 等实际 key 派生函数比单次传递 SHA-256 更适合减缓暴力攻击,但除​​此之外,它们都会生成有效 key 。

关于Java - AES CBC 算法生成 SecretKeySpec 的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61068044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com