我需要此錯誤的幫助:給定最終塊未正確填充。從標題中可以看出,我正在與AES合作。AES錯誤:鑑於最終塊未正確填充
這裏是行的代碼,其中的錯誤:
byte[] decrypted = cipher.doFinal(bytes);
下面是完整的代碼:
public class AESCrypt {
private final Cipher cipher;
private final SecretKeySpec key;
private String encryptedText, decryptedText;
public AESCrypt(String password) throws Exception {
// hash password with SHA-256 and crop the output to 128-bit for key
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(password.getBytes("UTF-8"));
byte[] keyBytes = new byte[16];
System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
key = new SecretKeySpec(keyBytes, "AES");
}
public String encrypt(String plainText) throws Exception {
byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
AlgorithmParameterSpec spec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
encryptedText = asHex(encrypted);
return encryptedText;
}
public String decrypt(String cryptedText) throws Exception {
byte[] iv = new byte[cipher.getBlockSize()];
AlgorithmParameterSpec spec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
// decrypt the message
byte[] bytes = cryptedText.getBytes("UTF-8");
byte[] decrypted = cipher.doFinal(bytes);
decryptedText = asHex(decrypted);
System.out.println("Desifrovani tekst: " + decryptedText + "\n");
return decryptedText;
}
public static String asHex(byte buf[]) {
StringBuilder strbuf = new StringBuilder(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append("0");
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception {
System.out.print("....AES....\n");
String message = "MESSAGE";
String password = "PASSWORD";
System.out.println("MSG:" + message);
AESCrypt aes = new AESCrypt(password);
String encryptedText = aes.encrypt(message).toString();
System.out.println("SIFROVANA PORUKA: " + encryptedText);
String decryptedText = aes.decrypt(encryptedText).toString();
System.out.print("DESIFROVANA PORUKA: " + decryptedText);
}
}
我會建議你使用Apache Commons編解碼器[十六進制](http://commons.apache.org/proper/commons- codec/apidocs/org/apache/commons/codec/binary/Hex.html)而不是滾動自己的十六進制編碼器和解碼器 – 2013-03-25 21:25:42
我在互聯網上看過很多例子,其中人們使用BASE64Decoder和BASE64Encoder?但似乎我不能使用它。 – Zookey 2013-03-25 21:51:07
因爲它們位於sun名稱空間中,所以使用它們並不是一個最佳實踐,並且可能不一定在JDK的所有實現中都有。如果你想在沒有庫的情況下進行Base64編碼和解碼,並且你正在支持Java 6+,請使用[本答案](http://stackoverflow.com/a/2054226/1904979)中概述的JAXB – 2013-03-25 21:54:00