【问题标题】:Java - SHA-256 hashing : Invalid AES key length : 64 bytesJava - SHA-256 散列:无效的 AES 密钥长度:64 字节
【发布时间】:2013-02-22 16:14:32
【问题描述】:
public static String doGenerate() {
    int val = 10000000;
    Random r = new Random();
    int gen = r.nextInt(89999999);
    int gen1 = r.nextInt(89999999);
    gen = val + gen;
    gen1 = val + gen1;
    String reply = gen + "" + gen1;
    return reply;
}

这是我用来生成下面给出的 AES 算法所需的密钥的方法。

public static void decryptFile(String keyString, String fileName){
    try {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        SecretKey key = (SecretKey) new SecretKeySpec(
            keyString.getBytes(), "AES");// kgen.generateKey();

        AESEncrypter encrypter = new AESEncrypter(key);

        encrypter.decrypt(new FileInputStream(
            new java.io.File("").getCanonicalFile() +
            File.separator + "Received"+
            File.separator + fileName),
            new FileOutputStream(new java.io.File("").getCanonicalFile() +
            File.separator + "Decrypted" + 
            File.separator + fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这是 AESEncrypter 方法。

  public AESEncrypter(SecretKey key) {
    // Create an 8-byte initialization vector
    byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
            0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

    AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
    try {
        ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // CBC requires an initialization vector
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

解密后我得到一个无效的密钥异常:java.security.InvalidKeyException: Invalid AES key length: 64 bytes。为什么会这样?有解决办法吗?

【问题讨论】:

    标签: java aes sha256


    【解决方案1】:

    您的密钥生成功能存在缺陷 - 它仅生成整数并将其转换为字符串,从而大量减少可用密钥空间并显着削弱您的密钥。

    但是,它确实会产生适合 AES 密钥的 16 字节值。我只能假设您在上次收到错误消息后更改了代码?

    我强烈建议您恢复为仅使用 KeyGenerator 来生成 AES 密钥。这将以一种安全的方式进行。

    【讨论】:

    • 其实返回16个字符。这可能不会编码为 16 个字节,尽管它通常会这样做。 UTF-16 应将此编码为 32 个字节。但这仍然不能解释 64 字节。
    • 谢谢你..我现在才明白.. :)
    猜你喜欢
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 2021-01-07
    • 2019-02-24
    • 2017-02-13
    • 2012-06-05
    相关资源
    最近更新 更多