例外:在Linux中"给定最终块未正确填充",但它适用于Windows

use*_*364 10 java encryption

我的应用程序在Windows中运行,但在Linux中失败,Given final block not properly padded例外.

组态:

  • JDK版本:1.6
  • Windows:版本7
  • Linux:CentOS 5.8 64位

我的代码如下:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SecurityKey {
    private static Key key = null;
    private static String encode = "UTF-8";
    private static String cipherKey = "DES/ECB/PKCS5Padding";

    static  {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            String seedStr = "test";
            generator.init(new SecureRandom(seedStr.getBytes()));
            key = generator.generateKey();
        } catch(Exception e) {
        }
    }

    // SecurityKey.decodeKey("password")
    public static String decodeKey(String str) throws Exception  {
        if(str == null)
            return str;

        Cipher cipher = null;
        byte[] raw = null;
        BASE64Decoder decoder = new BASE64Decoder();
        String result = null;
        cipher = Cipher.getInstance(cipherKey);
        cipher.init(Cipher.DECRYPT_MODE, key);
        raw = decoder.decodeBuffer(str);
        byte[] stringBytes = null;
        stringBytes = cipher.doFinal(raw); // Exception!!!!
        result = new String(stringBytes, encode);

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

在线:

   ciper.doFilnal(raw);
Run Code Online (Sandbox Code Playgroud)

抛出以下异常:

   javax.crypto.BadPaddingException: Given final block not properly padded
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Maa*_*wes 2

答案在于,SecureRandom特定运行时间的播种可能会有所不同。大多数时候你会得到"SHA1PRNG",但不会立即获得种子。相反,您可以setSeed()在请求任何随机之前调用,在这种情况下,种子将用作唯一的熵源。在这种情况下,您的密钥将始终相同。

问题是没有定义SecureRandom返回哪个。您可能会得到一个完全不同的、特定于平台的实现,但上述情况并不成立。如果 Sun 提供程序的优先级较高,您可能无法获得其中一个提供程序。

然后是种子的问题。种子seedStr在调用期间使用变量的平台默认编码getBytes()。由于编码可能不同,种子也可能不同,因此结果也会不同。

尝试使用PBKDF2等函数来代替密钥导出;stackoverflow 上有足够的关于如何进行的信息。