aes解密错误

vhmi4jdf  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(193)

我正试图重写我在网上找到的aes代码。试图从欧洲央行转变为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};

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

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题