我得到这个警告:
javax.crypto.badpaddingexception:给定的最后一个块没有正确填充。如果在解密过程中使用了坏密钥,则会出现此类问题。
知道是什么原因吗?这是我的加密和解密代码。我已经查看了关于stackoverflow的各种不同的答案,但是我找不到一个真正有效的答案。
private static Cipher ecipher;
private static Cipher dcipher;
private static SecretKey key;
public static void Menu() {
try {
// generate secret key using DES algorithm
key = KeyGenerator.getInstance("DES").generateKey();
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
// initialize the ciphers with the given key
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
} catch (NoSuchAlgorithmException e) {
System.out.println("No Such Algorithm:" + e.getMessage());
return;
} catch (NoSuchPaddingException e) {
System.out.println("No Such Padding:" + e.getMessage());
return;
} catch (InvalidKeyException e) {
System.out.println("Invalid Key:" + e.getMessage());
return;
}
}
public static String encrypt(String WordToEncrypt) {
Menu();
try {
// encode the string into a sequence of bytes using the named charset
// storing the result into a new byte array.
byte[] utf8 = WordToEncrypt.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
// encode to base64
enc = BASE64EncoderStream.encode(enc);
System.out.println(new String(enc));
return new String(enc);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String WordToDecrypt) {
Menu();
try {
// decode with base64 to get bytes
byte[] dec = BASE64DecoderStream.decode(WordToDecrypt.getBytes());
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
1条答案
按热度按时间qxgroojn1#
你打电话来
Menu
一次在加密代码中,一次在解密代码中。由于您为加密和解密随机生成密钥,因此密钥将不同,代码将失败。别老盯着我
Cipher
示例,最好不在字段中,但肯定不在类字段中。des很老了;太老了。使用aes-使用des并不比aes简单。