javax.crypto.BadPaddingException: Given final block not properly padded

/ Markbug / 没有评论 / 440浏览
javax.crypto.BadPaddingException: Given final block not properly padded

昨天在使用spring给数据库配置文件做解密时,遇到了上述的异常。问题的原因是我先是在Windwos上写了一个DES的加解密工具类,并在该系统上做了测试没有任何问题,但将源代码拷贝到Mac系统上运行时,遇到了上述问题。源代码如下:

public class DESUtils {
private static Key key;
private static String SECRET_KEY = "jilinwula";

static {
try {
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom(SECRET_KEY.getBytes()));
key = generator.generateKey();
generator = null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}

public static String getEncryptString(String value) {
BASE64Encoder base64Encoder = new BASE64Encoder();
try {
byte[] valueBytes = value.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptValueBytes = cipher.doFinal(valueBytes);
return base64Encoder.encode(encryptValueBytes);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
return null;
}

public static String getDecryptString(String value) {
BASE64Decoder base64Decoder = new BASE64Decoder();
try {
byte[] valueBytes = base64Decoder.decodeBuffer(value);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptValueBytes = cipher.doFinal(valueBytes);
return new String(decryptValueBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
return null;
}
}

后来在网上查询资料时发现,问题的原因就是SecureRandom导致的,SecureRandom每次都会随着操作系统本身的内部状态发生变化(Linux或Mac),所以会导致,加密时生成的加密内容每次都是不同的,并报上述异常。解决的办法如下。只要调用SecureRandom类的setSeed方法即可。具体修改如下:

static {
try {
KeyGenerator generator = KeyGenerator.getInstance("DES");
// 解决Linux Mac异常问题
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(SECRET_KEY.getBytes());
generator.init(secureRandom);
key = generator.generateKey();
generator = null;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}

相关资料:http://www.jb51.net/article/40941.htm