我已经尝试添加 getbytes("UTF") 或 getbytes("UTF-8"),因为它在类似的问题中被建议。 它说我们需要在将字节转换为字符串时尝试使用 UTF,反之亦然。 但它仍然不适用于我的代码...请帮忙
public class Password1 {
private static final String ALGO = "AES";
private static byte[] keyValue = new byte[]{'t','h','y','u','e','f','z','s','y','k','f','l','d','a','b','m'};
public static void main(String[] args) {
//Password1 p = new Password1();
Scanner sc = new Scanner(System.in);
String i = sc.nextLine();
System.out.println("Password = "+i);
try {
String en = encrypt(i);
System.out.println(en);
String dec = decrypt(en);
System.out.println("Encrypted = " + en);
System.out.println("Decrypted = " + dec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
String encrypted = new BASE64Encoder().encode(encVal);
return encrypted;
}
public static String decrypt(String encrypted) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
//Byte bencrypted = Byte.valueOf(encrypted);
byte[] decoded = new BASE64Decoder().decodeBuffer(encrypted);
byte[] decValue = c.doFinal(decoded);
String decrypted = new String(decValue);
return decrypted;
}
private static Key generateKey() throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
keyValue = sha.digest(keyValue);
keyValue = Arrays.copyOf(keyValue, 16);
SecretKeySpec key = new SecretKeySpec(keyValue, ALGO);
return key;
}
}
最佳答案
当您调用 encrypt()
时,您用它的散列替换密码,然后使用散列作为 key 。
然后调用decrypt()
,重新散列哈希值,并使用散列后的散列值作为 key 。所以你没有使用相同的 key 进行加密和解密。
在 main()
中生成 key 一次,并将其作为参数传递给 encrypt()
和 decrypt()
。使 keyValue
最终化。或者更好的是,将其设为 main
的局部变量。
关于javax.crypto.BadPaddingException : Given final block not properly padded. ..尝试使用 getbytes ("UTF"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853757/