【问题标题】:How to do AES Decryption in java如何在java中进行AES解密
【发布时间】:2019-05-09 13:42:35
【问题描述】:

我在 javaScript 中尝试了 AES 加密,并尝试在 java 中使用相同的算法和 secretKey 解密,请任何人建议

javaScript 加密

const cipher = crypto.createCipher('aes192','67f969129e2f78f2ee286d16efec0dad'); 
var encrypted = cipher.update('Hello JavaTpoint', 'utf8', 'base64'); 
encrypted += cipher.final('base64'); 
console.log(encrypted); // VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=

加密的 base64 密钥:VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=

java解密

public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException, Exception {
    byte[] array = Base64.getDecoder().decode("VABI2hVl2Ydqednr3K5tJv0VFKKiiFK3Jn3kinGxL7U=");  
    byte[] dec = decrypt(array, "67f969129e2f78f2ee286d16efec0dad");
    System.out.println("content is :: dec " + new String(dec));
}

public static byte[] decrypt(byte[] input, String key) {
    byte[] decrypted = null;
    try {
        System.out.println(new String(decodeHexString(key)));
        SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");    
        cipher.init(Cipher.DECRYPT_MODE, skey);
        decrypted = cipher.doFinal(input);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return decrypted;
}

在 java 中出现错误:

javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:991)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
    at javax.crypto.Cipher.doFinal(Cipher.java:2164)
    at com.sd.lambda.Decryption.decrypt(Decryption.java:84)
    at com.sd.lambda.Decryption.main(Decryption.java:47)
Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.<init>(String.java:566)
    at com.sd.lambda.Decryption.main(Decryption.java:50)

它应该像这样在Java控制台中解密并打印“Hello JavaTpoint”:

content is :: dec Hello JavaTpoint

【问题讨论】:

    标签: java


    【解决方案1】:

    当您在decrypt 方法中调用cipher.init() 时,IV 是必要的第三个参数。取决于原始字符串的加密方式将决定您如何获取此值。

    这是您在设置解密密码时要使用的 init() 方法的链接: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/javax/crypto/Cipher.html#init(int,java.security.Key,java.security.SecureRandom)

    【讨论】:

    • 我不确定正在使用哪种模式。但在我的 java 代码中,我使用的是 ECB 模式,所以不需要 IV
    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 2021-04-27
    • 1970-01-01
    • 2019-01-30
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多