如何使用自定义秘密密钥而不是在AES 256加密中生成新的秘密密钥

发布于 2025-01-24 07:31:07 字数 1302 浏览 2 评论 0原文

我现在正在尝试在Java开发AES 256 CFB加密程序。

我想使用自己的秘密钥匙(十六进制)。但是,它回报了关键长度有问题。

代码

class encryption_different {
private static String SECRET_KEY = "afd7a42b34f4875e05d210ea1252e02d5305becdb752f3553d657bab1236f733";

public static String encrypt(String strToEncrypt) {
    try {

        //IV handling
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        //convert custom key string to Secret key format
        byte[] decodedKey = Base64.getDecoder().decode(SECRET_KEY);
        SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, originalKey, 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;
}
public static void main(String[] args){
    encrypt("password1");
}
}

这是我收到的错误消息的

Error while encrypting: java.security.InvalidKeyException: Invalid AES key length: 48 bytes

:因此,我想知道为什么我会收到此错误消息以及如何修复它。

I am now trying to develop a AES 256 CFB encryption program in Java.

I wish to use my own secret key (Hex). However, it returned that there is something wrong with the key length.

Here is the code

class encryption_different {
private static String SECRET_KEY = "afd7a42b34f4875e05d210ea1252e02d5305becdb752f3553d657bab1236f733";

public static String encrypt(String strToEncrypt) {
    try {

        //IV handling
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        //convert custom key string to Secret key format
        byte[] decodedKey = Base64.getDecoder().decode(SECRET_KEY);
        SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, originalKey, 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;
}
public static void main(String[] args){
    encrypt("password1");
}
}

The error message I got:

Error while encrypting: java.security.InvalidKeyException: Invalid AES key length: 48 bytes

And therefore, I would like to know why I am getting this error message and how to fix it.

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

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

发布评论

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