如何在java中将长度为32位的AES密钥转换为256位密钥?盐是唯一的方法吗?

发布于 2025-01-10 08:12:41 字数 911 浏览 3 评论 0原文

我想在java中将长度为32的字符串转换为AES/CBC/PKCS5Padding的256位密钥。 我找到了两个答案:

  1. 通过编码和解码 -

    字符串密码 = "12345678910111211234567891011121"; // 长度-32
    byte[]解码密钥 = Base64.getDecoder().decode(密码); // 给出大小为 24 的 byte[]
    SecretKey key = new SecretKeySpec(decodedKey, 0,decodedKey.length, "AES");
    

    但是大小为 24 的 byte[] 为我提供了 192 位密钥。我想要该字符串的 256 位密钥。

  2. 通过使用盐 -

    public static SecretKey getKey(字符串密码,字符串盐)抛出NoSuchAlgorithmException,InvalidKeySpecException {
        SecretKeyFactory 工厂 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec 规范 = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
        返回键;
    }
    

    但我不想使用盐,因为我需要再次生成它。

有没有其他方法可以将长度为 32 位的密钥转换为 256 位密钥?无论如何我都会使用IV。我可以用它作为盐吗?如果没有,我可以给出什么盐值以及产生盐的标准方法是什么?

I want to convert a string of length 32 to 256-bit secret key of AES/CBC/PKCS5Padding in java.
I found two answers:

  1. By encoding and decoding -

    String password = "12345678910111211234567891011121"; // length-32
    byte[] decodedKey = Base64.getDecoder().decode(password); // gives byte[] of size 24
    SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    

    But byte[] of size 24 gives me for 192-bit key. I want 256-bit key for that exact string.

  2. By using salt -

    public static SecretKey getKey(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
        return key;
    }
    

    But I don't want to use salt as I need to generate it again.

Is there any other way to convert string of length 32 to 256-bit secret key? I will be using IV anyway. Can I use it as a salt? If not, what can I give for salt value and what is the standard way to generate salt?.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文