如何在Java中使用AES算法解密加密字符串?

时间:2018-01-19 15:42:24

标签: java string encryption aes

我无法用Java解密AES加密文本。这是我的代码:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;

public class aesencrypt {

    public static void main(String[] args) throws Exception {
        String plainText = "Hello World";
        System.out.println("Original Text:" + plainText);
        SecretKey secKey = getSecretEncryptionKey();
        System.out.println("AES Key (Hex Form):"+bytesToHex(secKey.getEncoded()));
        String encryptedText = bytesToHex(encryptText(plainText, secKey));
        System.out.println("Encrypted Text (Hex Form):"+encryptedText);
        String decryptedText = decryptText(encryptedText, secKey);
        System.out.println("Descrypted Text:"+decryptedText);
    }

    public static SecretKey getSecretEncryptionKey() throws Exception{
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128); // The AES key size in number of bits
        SecretKey secKey = generator.generateKey();
        return secKey;
    }

    public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
        // AES defaults to AES/ECB/PKCS5Padding in Java 7
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
        byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
        return byteCipherText;
    }

    public static String decryptText(String encrypted, SecretKey secKey) throws Exception {
        // AES defaults to AES/ECB/PKCS5Padding in Java 7
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secKey);
        byte[] bytePlainText = aesCipher.doFinal(encrypted.getBytes());
        return new String(bytePlainText);
    }

    private static String bytesToHex(byte[] hash) {
        return DatatypeConverter.printHexBinary(hash);
    }

}

当我运行此操作时,我在以下输出中收到错误:

Original Text:Hello World
AES Key (Hex Form):4690FFCDC7B5E8B128F5BF45F0920527
Encrypted Text (Hex Form):7C092F40D592F9DF83F3D4E976612928
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:989)
    at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:845)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at aesencrypt.decryptText(aesencrypt.java:38)
    at aesencrypt.main(aesencrypt.java:15)

我已经搜索了Stack Overflow和搜索引擎,但我实际上找不到解决方案。

问题已解决

更新 :问题解决了,感谢JB Nizet解决方案!

修订代码:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;

public class aesencrypt {

    public static void main(String[] args) throws Exception {
        String plainText = "Hello World";
        System.out.println("Original Text:" + plainText);
        SecretKey secKey = getSecretEncryptionKey();
        System.out.println("AES Key (Hex Form):"+bytesToHex(secKey.getEncoded()));
        String encryptedText = bytesToHex(encryptText(plainText, secKey));
        System.out.println("Encrypted Text (Hex Form):"+encryptedText);
        String decryptedText = decryptText(encryptedText, secKey);
        System.out.println("Decrypted Text:"+decryptedText);
    }

    public static SecretKey getSecretEncryptionKey() throws Exception{
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey secKey = generator.generateKey();
        return secKey;
    }

    public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
        byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
        return byteCipherText;
    }

    public static String decryptText(String encrypted, SecretKey secKey) throws Exception {
        Cipher aesCipher = Cipher.getInstance("AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secKey);
        byte[] bytePlainText = aesCipher.doFinal(hexToByte(encrypted));
        return new String(bytePlainText);
    }

    private static String bytesToHex(byte[] hash) {
        return DatatypeConverter.printHexBinary(hash);
    }

    private static byte[] hexToByte(String txt) {
        return DatatypeConverter.parseHexBinary(txt);
    }

}

这是输出:

Original Text:Hello World
AES Key (Hex Form):84526F32BEDDBEA5BFBCDE241AD9BBA2
Encrypted Text (Hex Form):25378032E5F52575B7CEF311D45F00BD
Decrypted Text:Hello World

1 个答案:

答案 0 :(得分:3)

看看你在做什么:

String encryptedText = bytesToHex(encryptText(plainText, secKey));

在这里,您可以将纯文本转换为字节(使用有损,平台相关的getBytes(),BTW。您应该使用UTF8。)

然后加密这些字节并获得一个字节数组。然后将此字节数组编码为十六进制。

因此,反向操作将是:从十六进制解码为字节,然后解密这些字节,然后从解密的字节构造一个字符串。

但这就是你正在做的事情:

String decryptedText = decryptText(encryptedText, secKey);

其中decryptText()执行:

byte[] bytePlainText = aesCipher.doFinal(encrypted.getBytes());

所以,你永远不会使用十六进制解码。如果您在一侧使用bytesToHex(),则需要在另一侧使用hexToBytes()