web123456

JAVA implements AES encryption

JAVA implements AES encryption

1. Factor

Last time I introduced itJAVA implements AES encryption》, mentioned that DES is less and less used in recent years, because it uses 56-bit keys, which are easier to crack. In recent years, it has gradually been replaced by AES, and AES has become one of the most popular algorithms in symmetric encryption at present; AES can use 128, 192, and 256-bit keys, and encrypt and decrypt data with 128-bit packets. This article briefly introduces how to implement AES encryption through JAVA.

2. JAVA implementation

A little gossip, skimming the principles and algorithms of AES encryption, search for professional websites directly, let’s take a look at the specific implementation of JAVA.

2.1 Encryption

The code has a detailed explanation, no nonsense.

2.2 Decryption

The code has detailed comments, no nonsense
Note: When decrypting, you must pass in the byte array

2.3 Test code

The output result is as follows:
Before encryption: test
After decryption: test

2.4 Prone to errors

But if we modify the test code, as follows:
Then, the system will report the following exception:
: Input length must be multiple of 16 when decrypting with padded cipher
        at .SunJCE_f.b(DashoA13*..)
        at .SunJCE_f.b(DashoA13*..)
        at (DashoA13*..)
        at (DashoA13*..)
This is mainly because the encrypted byte array cannot be cast into a string. In other words, strings and byte arrays are not inverse in this case; to avoid this case, we need to make some revisions, and we can consider converting binary data into hexadecimal representations. There are two main methods:
2.4.1 Convert binary to hexadecimal
2.4.2 Convert hexadecimal to binary
Then, we revise the above test code, as follows:
The test results are as follows:
Before encryption: test
After encryption: 73C58BAFE578C59366D8C995CD0B9D6D
After decryption: test
 

2.5 Another encryption method

There is also an encryption method, which you can refer to as follows:
There are two limitations to this encryption method
  • The key must be 16-bit
  • The length of the content to be encrypted must be a multiple of 16. If it is not a multiple of 16, the following exception will occur:
: Input length not multiple of 16 bytes
        at .SunJCE_f.a(DashoA13*..)
        at .SunJCE_f.b(DashoA13*..)
        at .SunJCE_f.b(DashoA13*..)
        at (DashoA13*..)
        at (DashoA13*..)
To solve the above exception, you can avoid it by completing the encrypted content.