Java加密/解密错误。偶尔会出现解密错误

时间:2016-01-19 19:18:10

标签: java encryption cryptography

我有以下简单的加密/解密代码:

import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.RandomStringUtils;
          :

public class MyUtility {

    private static Cipher instance = Cipher.getInstance("AES/CBC/PKCS5Padding");
    private static Cipher instance2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
    private static byte[] iv = { 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };

    private static String encrypt(String data, DataParameters params) throws Exception {

        IvParameterSpec ivspec = new IvParameterSpec(iv);
        String privateKey = MyUtility.getKey(params);

        SecretKey key = new SecretKeySpec(privateKey.getBytes(), "AES");
        instance.init(Cipher.ENCRYPT_MODE, key, ivspec);

        String paddedData = addPaddDate(data); 
        byte[] encryptedBytes = instance.doFinal(paddedData.getBytes());
        byte[] encodeBase64 = Base64.encodeBase64(encryptedBytes); 
        String encryptedStr = new String(encodeBase64);

然后很快执行解密:

    byte[] decodeBytes = Base64.decodeBase64(encryptedStr.getBytes()); // Decode
    String padDecryptedStr = new String(instance2.doFinal(decodeBytes)); 

然后95%的时间,解密的值是正确的。但是,偶尔会出现以下错误:

javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:420)
    at javax.crypto.Cipher.doFinal(Cipher.java:1966)
    at myCode.decrypt(MyEncryptDecryptUtility.java:97)

第97行是String padDecryptedStr = new String(instance2.doFinal(decodeBytes));

解密的值看起来像奇怪的字符串,例如:\u001d tq@s 2 a或 w $ X\ u0005

这是我使用的填充函数:

private static String addPaddDate(String data) {
    return data + RandomStringUtils.randomAlphanumeric(10);
}

知道上面代码中缺少什么吗?

谢谢!

只想更新我发现的更多信息:

当解密的值是一个奇怪的字符串时,我再次解密,然后第二次得到正确的值。谁知道为什么会这样?谢谢!

1 个答案:

答案 0 :(得分:0)

作业有多个cpu内核,因此多任务访问同一个Cipher并破坏了编码。我同步了encrypt()和decrypt()函数,现在情况正常。