AES symmetric encryption and decryption process in Java _java

Source: Internet
Author: User
Tags decrypt generator string back

AES symmetric encryption and decryption code detailed introduction, for your reference, the specific content as follows  

Package demo.security;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;
Import java.security.InvalidKeyException;
Import java.security.NoSuchAlgorithmException;
Import Java.security.SecureRandom;
Import java.util.Base64;

Import Java.util.Scanner;
Import javax.crypto.BadPaddingException;
Import Javax.crypto.Cipher;
Import javax.crypto.IllegalBlockSizeException;
Import Javax.crypto.KeyGenerator;
Import javax.crypto.NoSuchPaddingException;
Import Javax.crypto.SecretKey;

Import Javax.crypto.spec.SecretKeySpec;
Import Sun.misc.BASE64Decoder;

Import Sun.misc.BASE64Encoder;  /* AES symmetric encryption and decryption/public class Symmetricencoder {/* * encryption * 1. Construct the key generator * 2. Initialize the key generator * 3 According to the Ecnoderules rule. Generate key *
      4. Create and initialize the cipher * 5. Content encryption * 6. Return string/public static string Aesencode (string encoderules,string content) {try {
      1. Construct the key generator, designated as AES algorithm, case-insensitive Keygenerator keygen=keygenerator.getinstance ("AES"); 2. Generate a 128-bit random source based on the Ecnoderules rule initialization key generator/, based on the bytes passed inArray Keygen.init (128, New SecureRandom (Encoderules.getbytes ()));
       3. Generate the original symmetric key Secretkey Original_key=keygen.generatekey ();
      4. Bytes array byte [] raw=original_key.getencoded () to obtain the original symmetric key;
       5. Generate AES Key Secretkey key=new Secretkeyspec (Raw, "AES") according to the byte array;
       6. According to the specified algorithm AES self-cipher Cipher cipher=cipher.getinstance ("AES");
      7. Initialize the cipher, the first parameter is encrypt (Encrypt_mode) or decrypt decrypt (decrypt_mode) operation, the second parameter is to use key Cipher.init (Cipher.encrypt_mode, key);
      8. Get the encrypted content of the byte array (here to set to Utf-8) otherwise the content if there are Chinese and English mixed in Chinese will be decrypted as garbled byte [] byte_encode=content.getbytes ("Utf-8");
     9. According to the initialization of the cipher-encryption: The Data encryption byte [] byte_aes=cipher.dofinal (Byte_encode); 10. Convert the encrypted data to a string//the package//workaround is not found in Base64encoder://The JRE System Library is first removed from the project's build path and the library JRE is added syste
      M Library, after recompiling everything is OK.
     String Aes_encode=new string (new Base64encoder (). Encode (Byte_aes));
    11. Return the string back to Aes_encode; catch (NoSuchAlgorithmException e) {E.printstaCktrace ();
    catch (Nosuchpaddingexception e) {e.printstacktrace ();
    catch (InvalidKeyException e) {e.printstacktrace ();
    catch (Illegalblocksizeexception e) {e.printstacktrace ();
    catch (Badpaddingexception e) {e.printstacktrace ();
    catch (Unsupportedencodingexception e) {e.printstacktrace ();     
  ////If there is a mistake, return nulll returns null; * * * Decryption process: * 1. With encryption 1-4 steps * 2. byte[the encrypted string into an array * 3. Decrypt the encrypted content/public static string Aesdncode ( String encoderules,string content) {try {//1. Construct key builder, specified as AES algorithm, case-insensitive Keygenerator keygen=keygenerator.get
      Instance ("AES"); 2. Generate a 128-bit random source based on the Ecnoderules rule initialization key generator/, according to the passed-in byte array keygen.init (128, New SecureRandom (Encoderules.getbytes ())
       );
       3. Generate the original symmetric key Secretkey Original_key=keygen.generatekey ();
      4. Bytes array byte [] raw=original_key.getencoded () to obtain the original symmetric key; 5. Generate AES Key Secretkey Key=new SECRETKEYSP based on byte arrayEC (Raw, "AES");
       6. According to the specified algorithm AES self-cipher Cipher cipher=cipher.getinstance ("AES");
      7. Initialize the cipher, the first parameter is encryption (Encrypt_mode) or decryption (Decrypt_mode) operation, the second parameter is the key Cipher.init (Cipher.decrypt_mode, key);
      8. Decode the encrypted and encoded content into a byte array byte [] byte_content= new Base64decoder (). Decodebuffer (content);
      * * Decryption/Byte [] byte_decode=cipher.dofinal (byte_content);
      String Aes_decode=new string (Byte_decode, "utf-8");
    return aes_decode;
    catch (NoSuchAlgorithmException e) {e.printstacktrace ();
    catch (Nosuchpaddingexception e) {e.printstacktrace ();
    catch (InvalidKeyException e) {e.printstacktrace ();
    catch (IOException e) {e.printstacktrace ();
    catch (Illegalblocksizeexception e) {e.printstacktrace ();
    catch (Badpaddingexception e) {e.printstacktrace ();     
  ////If there is a mistake, return nulll returns null; public static void Main (string[] args) {Symmetricencoder Se=neW Symmetricencoder ();
    Scanner scanner=new Scanner (system.in);
    * * * Encryption/SYSTEM.OUT.PRINTLN ("Use AES symmetric encryption, please enter the rules of Encryption");
    String Encoderules=scanner.next ();
    System.out.println ("Please enter the content to be encrypted:");
    String content = Scanner.next (); System.out.println ("+encoderules+" according to the input rule "encrypted cipher" is: "+se.
    
    Aesencode (encoderules, content));
     * * Decryption/SYSTEM.OUT.PRINTLN ("Using AES symmetric decryption, please enter the rules of encryption: (must be the same as encryption)");
    Encoderules=scanner.next ();
     System.out.println ("Please enter the content to decrypt (ciphertext):");
    Content = Scanner.next (); System.out.println ("+encoderules+" based on the rules entered) is decrypted with the following text: "+se."
  Aesdncode (encoderules, content));

 }

}

Test results:

Using AES symmetric encryption, enter the rules for encryption
Using AES symmetric encryption
Please enter the content to be encrypted:
Using AES symmetric encryption
The ciphertext that is encrypted using AES symmetric encryption according to the rules entered is: z0nwrnphghgxhn0cqjls58ycjhmcbfer33rws7lw+ay=
Using AES symmetric decryption, enter the rules for encryption: (must be the same as encryption)
Using AES symmetric encryption
Please enter the content to decrypt (ciphertext):
z0nwrnphghgxhn0cqjls58ycjhmcbfer33rws7lw+ay=
The plaintext that is decrypted using AES symmetric encryption based on the rules entered is: using AES symmetric encryption

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.