首页 > 解决方案 > AES 解密不正确

问题描述

我正在尝试重写我在互联网上找到的 AES 代码。试图将模式从 ECB 更改为 CBC。代码在加密或解密时没有给我任何错误,但它返回不正确的解密明文。你可以在这里看到输出。

public static String encrypt(String strToEncrypt, SecretKey secret) throws InvalidKeyException{
    
    try{
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret); //without this line, iv = null
        byte[] iv = cipher.getIV();
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(iv));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        
        byteArrayOutputStream.write(iv, 0, iv.length);
        byte[] cipherT = cipher.doFinal(strToEncrypt.getBytes());
        byteArrayOutputStream.write(cipherT, 0, cipherT.length);
        cipherT = byteArrayOutputStream.toByteArray();
        
        return Base64.getEncoder().encodeToString(cipher.doFinal(cipherT));
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
} 
     
public static String decrypt(String strToDecrypt, SecretKey secret) throws NoSuchAlgorithmException, NoSuchPaddingException{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] iv = new byte[16];
    byte[] CipherByte = Base64.getDecoder().decode(strToDecrypt);
    iv = Arrays.copyOfRange(CipherByte, 0, iv.length);

    CipherByte = Arrays.copyOfRange(CipherByte, 16, CipherByte.length);
    try{
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        return new String(cipher.doFinal(CipherByte));
    
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}

我尝试让 iv 全部为零,所以我不需要将它添加到密文中

byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

并在解密时读取它,但输出是相同的。我想不通,我不明白,是加密问题还是解密问题。

标签: javaencryptionaes

解决方案


推荐阅读