简体   繁体   English

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

[英]How to decrypt encrypted string using AES Algorithm in Java?

I can't decrypt the AES encrypted text in Java. 我无法用Java解密AES加密的文本。 Here's my code: 这是我的代码:

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);
    }

}

When I run this, I'm getting error in the following output: 运行此命令时,在以下输出中出现错误:

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)

I've already searched Stack Overflow and search engines but I can't actually find the solution. 我已经搜索了Stack Overflow和搜索引擎,但实际上找不到解决方案。

PROBLEM SOLVED 问题解决了

UPDATE : Problem Solved, thanks to JB Nizet for the solution! 更新 :已解决问题,感谢JB Nizet提供了解决方案!

Revised Code : 修改后的代码:

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);
    }

}

Here's the output: 这是输出:

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

Look at what you're doing: 看你在做什么:

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

Here you transform the plain text into bytes (using the lossy, platform-dependant getBytes() , BTW. You should use UTF8). 在这里,您将纯文本转换为字节(使用有损,与平台有关的getBytes() ,顺便说一句。您应该使用UTF8)。

Then you encrypt those bytes and get a byte array as a result. 然后,您将这些字节加密并得到一个字节数组。 Then you encode this byte array to hexadecimal. 然后,您将此字节数组编码为十六进制。

So, the reverse operation would be: decode from hexadecimal to bytes, then decrypt those bytes, then construct a String from the descrypted bytes. 因此,相反的操作将是:从十六进制解码为字节,然后解密那些字节,然后从解密后的字节构造一个字符串。

But here's what you're doing: 但是,这是您正在做的事情:

String decryptedText = decryptText(encryptedText, secKey);

where decryptText() does: 其中deleteText()的作用是:

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

So, you're never using the hexadecimal decoding. 因此,您永远不会使用十六进制解码。 If you use bytesToHex() on one side, you need to use hexToBytes() on the other side. 如果你使用bytesToHex()在一边,你需要使用hexToBytes()的另一边。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM