Case study of AES encryption method in JAVA

  • 2020-04-01 04:00:29
  • OfStack

This article illustrates the method of AES encryption in JAVA. Share with you for your reference. The details are as follows:

Java code:


KeyGenerator kg = KeyGenerator.getInstance("AES"); //Get the key generator
kg.init(256); //Initialize the
//The DES algorithm must be 56 bits
//The DESede algorithm can be 112 or 168 bits
//The AES algorithm can be 128, 192, 256 bits
SecretKey key = kg.generateKey(); //Generate keys. You can save keys in a variety of ways

Encryption:


Cipher cp = Cipher.getInstance("AES"); //Create password
cp.init(Cipher.ENCRYPT_MODE, key); //Initialize the
String str = " I need to be encryption The clear ";
byte [] ptext = str.getBytes("UTF8");
byte [] ctext = cp.doFinal(ptext); //encryption

Decryption:


Cipher cp = Cipher.getInstance("AES"); //Create password
cp.init(Cipher.DECRYPT_MODE, key); //Initialize the
byte [] ptext = cp.doFinal(ctext); //decryption
String str = new String(ptext, "UTF8"); //Redisplay plaintext

I hope this article has been helpful to your Java programming.


Related articles: