Symmetric encryption and decryption in Aes--java

Source: Internet
Author: User
Tags decrypt string back

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 classSymmetricencoder {/** Encryption * 1. Construct key Generator * 2. Initialize the key generator according to the Ecnoderules rule * 3. Generate the key * 4. Create and initialize the cipher * 5. Content encryption * 6. Return string*/     Public Staticstring Aesencode (string encoderules,string content) {Try {            //1. Construct key generator, specified as AES algorithm, case insensitiveKeygenerator Keygen=keygenerator.getinstance ("AES"); //2. Initialize the key generator according to the ecnoderules rule//generates a 128-bit random source, based on the array of bytes passed inKeygen.init ( -,NewSecureRandom (Encoderules.getbytes ())); //3. Generating the original symmetric keySecretkey original_key=Keygen.generatekey (); //4. Byte array to obtain the original symmetric key            byte[] raw=original_key.getencoded (); //5. Generating an AES key based on a byte arraySecretkey key=NewSecretkeyspec (Raw,"AES"); //6. AES Self-forming cipher according to the specified algorithmCipher Cipher=cipher.getinstance ("AES"); //7. Initialize the cipher, the first parameter is an encryption (Encrypt_mode) or decryption/decryption (Decrypt_mode) operation, the second parameter is the key usedCipher.init (Cipher.encrypt_mode, key); //8. Get a byte array of encrypted content (set to utf-8 here) otherwise the content will be decrypted as garbled if Chinese and English are mixed.            byte[] Byte_encode=content.getbytes ("Utf-8"); //9. Depending on how the cipher is initialized-encryption: Encrypt the data            byte[] byte_aes=cipher.dofinal (Byte_encode); //10. Convert the encrypted data to a string//It's not going to find a package in Base64encoder.//Workaround://in the project's build path, remove the JRE system library, add the Library JRE system Library, and then all is fine after recompiling. String aes_encode=NewString (NewBase64encoder (). Encode (Byte_aes)); //11. Return a string            returnAes_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 wrong, add nulll .        return NULL; }    /** Decryption * decryption Process: * 1. Encrypt with 1-4 step * 2. Convert the encrypted string back to byte[] array * 3. Decrypt encrypted content*/     Public Staticstring Aesdncode (string encoderules,string content) {Try {            //1. Construct key generator, specified as AES algorithm, case insensitiveKeygenerator Keygen=keygenerator.getinstance ("AES"); //2. Initialize the key generator according to the ecnoderules rule//generates a 128-bit random source, based on the array of bytes passed inKeygen.init ( -,NewSecureRandom (Encoderules.getbytes ())); //3. Generating the original symmetric keySecretkey original_key=Keygen.generatekey (); //4. Byte array to obtain the original symmetric key            byte[] raw=original_key.getencoded (); //5. Generating an AES key based on a byte arraySecretkey key=NewSecretkeyspec (Raw,"AES"); //6. AES Self-forming cipher according to the specified algorithmCipher Cipher=cipher.getinstance ("AES"); //7. Initialize the cipher, the first parameter is an encryption (Encrypt_mode) or decryption (Decrypt_mode) operation, the second parameter is the key usedCipher.init (Cipher.decrypt_mode, key); //8. Decode the encrypted and encoded content into a byte array            byte[] byte_content=NewBase64decoder (). Decodebuffer (content); /** Decryption*/            byte[] Byte_decode=cipher.dofinal (byte_content); String Aes_decode=NewString (Byte_decode,"Utf-8"); returnAes_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 wrong, add nulll .        return NULL; }         Public Static voidMain (string[] args) {symmetricencoder se=NewSymmetricencoder (); Scanner Scanner=NewScanner (System.inch); /** Encryption*/System. out. println ("using AES symmetric encryption, enter the rules for encryption"); String Encoderules=Scanner.next (); System. out. println ("Please enter what you want to encrypt:"); String content=Scanner.next (); System. out. println ("according to the rules entered"+encoderules+"the ciphertext after encryption is:"+SE.               Aesencode (encoderules, content)); /** Decryption*/System. out. println ("to use AES symmetric decryption, enter the encryption rule: (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 ("according to the rules entered"+encoderules+"The decrypted plaintext is:"+SE.    Aesdncode (encoderules, content)); }}

"Source Download" Test results:

Using AES symmetric encryption, enter an encrypted rule using AES symmetric encryption Please enter what you want to encrypt: using AES symmetric encryption using AES symmetric encryption encryption based on the rules entered is: Z0NWRNPHGHGXHN0CQJLS58YCJHMCBFER33RWS7LW +ay= using AES symmetric decryption, enter the encryption rule: (must be the same as encryption) use AES symmetric encryption Please enter the content to decrypt (ciphertext): z0nwrnphghgxhn0cqjls58ycjhmcbfer33rws7lw+ay=  Decrypted plaintext using AES symmetric encryption according to the rules entered is: Symmetric encryption using AES 

Symmetric encryption and decryption in Aes--java

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.