Example of AES Encryption

Source: Internet
Author: User

Recently I used to encrypt text content, so I checked the common encryption algorithms:

Des (Data Encryption Standard): symmetric algorithm, Data Encryption Standard, fast, suitable for encrypting a large amount of data;
3DES (Triple DES): It is a symmetric algorithm based on Des. it encrypts a piece of data three times with three different keys, with higher strength;
RC2 and RC4: symmetric algorithms that use variable-length keys to encrypt a large amount of data, faster than DES;
Idea (International Data Encryption Algorithm) International Data Encryption Algorithm, uses a 128-bit key to provide very strong security;
RSA: A Public Key algorithm that supports variable-length keys. The length of the file block to be encrypted is also variable. asymmetric algorithms;
DSA (Digital Signature Algorithm): digital signature algorithm, which is a standard DSS (Digital Signature Standard). It is not an encryption algorithm strictly;
AES (Advanced Encryption Standard): Advanced Encryption Standard, symmetric algorithm, is the next generation of encryption algorithm standard, fast, high security level, currently an implementation of the AES standard is Rijndael algorithm;
Blowfish uses a variable-length key, which can contain up to 448 bits and runs fast;
MD5: it is not an encryption algorithm, but a digest algorithm.

The following example shows how to implement AES encryption and decryption in Java:

Encryption:

/* * encrypt * @param content:  * @param password: */private static byte[] encrypt(String content, String password) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128, new SecureRandom(password.getBytes()));SecretKey secretKey = kgen.generateKey();byte[] encodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(encodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");byte[] byteContent = content.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE, key);byte[] result = cipher.doFinal(byteContent);return result;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (NoSuchPaddingException e) {e.printStackTrace();} catch (InvalidKeyException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IllegalBlockSizeException e) {e.printStackTrace();} catch (BadPaddingException e) {e.printStackTrace();}return null;}

Decryption:

/* * decrypt * @param content:  * @param password: */private static byte[] decrypt(byte[] content, String password) {try {KeyGenerator kgen = KeyGenerator.getInstance("AES");kgen.init(128, new SecureRandom(password.getBytes()));SecretKey secretKey = kgen.generateKey();byte[] encodeFormat = secretKey.getEncoded();SecretKeySpec key = new SecretKeySpec(encodeFormat, "AES");Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE, key);byte[] result = cipher.doFinal(content);return result;} 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();}return null;}

Example:

String content = "test"; string Password = "12345678"; // encrypt the system. out. println ("before encryption:" + content); byte [] encryptresult = encrypt (content, password); // decrypt byte [] decryptresult = decrypt (encryptresult, password); system. out. println ("decrypted:" + new string (decryptresult ));

Output:

Before encryption: test after decryption: Test

If you want to display the data in hexadecimal format after encryption, you can add two functions for binary and hexadecimal conversion.

Convert binary to hexadecimal:

private static String parseByte2HexStr(byte buf[]) {StringBuffer sb = new StringBuffer();for (int i = 0; i < buf.length; i++) {String hex = Integer.toHexString(buf[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}return sb.toString();}

Hexadecimal conversion to binary:

private static byte[] parseHexStr2Byte(String hexStr) {if (hexStr.length() < 1) {return null;}byte[] result = new byte[hexStr.length() / 2];for (int i = 0; i < hexStr.length() / 2; i++) {int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);result[i] = (byte)(high * 16 + low);}return result;}

Example:

String content = "test"; string Password = "12345678"; // encrypt the system. out. println ("before encryption:" + content); byte [] encryptresult = encrypt (content, password); string encryptresultstr = parsebyte2hexstr (encryptresult); system. out. println ("encrypted:" + encryptresultstr); // decrypt byte [] decryptfrom = parsehexstr2byte (encryptresultstr); byte [] decryptresult = decrypt (decryptfrom, password); system. out. println ("decrypted:" + new string (decryptresult ));

Output:

Before encryption: test after encryption: 73c58bafe578c591_d8c995cd0b9d6d after decryption: Test

Note: the code can be found in networks.

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.