Java AES Encryption Algorithm __ Code

Source: Internet
Author: User
Tags decrypt rounds stringbuffer

Reprint Address: Java version AES encryption algorithm

The Advanced Encryption Standard in cryptography (Advanced encryption Standard,aes), also known as Rijndael encryption, is a block encryption standard used by the U.S. federal government. This standard, which replaces the original DES, has been analyzed and widely used worldwide. After five years of selection process, the Advanced Encryption Standard was issued by the National Institute of Standards and Technology (NIST) on November 26, 2001 in FIPS PUB 197 and became an effective standard on May 26, 2002. In the 2006, the Advanced Encryption Standard has become one of the most popular algorithms in symmetric key cryptography.
  
The algorithm is designed by the Belgian cipher scientists Joan Daemen and Vincent Rijmen, combining the names of the two authors with the name of Rijndael, to submit the selection process of the Advanced Encryption Standard. (Rijdael pronunciation is close to "Rhinedoll")

AES is a new encryption algorithm that can be used to protect electronic data. Specifically, AES is an iterative, symmetric key-grouping cipher that uses 128, 192, and 256-bit keys and encrypts and decrypts data in 128-bit (16-byte) groupings. The symmetric key password uses the same key to encrypt and decrypt the data, unlike the public key password using the key pair. The number of bits of encrypted data returned by a block cipher is the same as the input data. Iterative cryptography uses a looping structure in which repeated permutations (permutations) and substitution (substitutions) input data. Figure 1 shows the case where AES encrypts and decrypts a 16-bit byte block of data using a 192-bit key.

The development trend of symmetric cipher system will focus on the block cipher. Block cipher algorithm is usually composed of key expansion algorithm and encryption (decryption) algorithm. The key extension algorithm expands the B-byte user master key into the R child key. The cryptographic algorithm consists of a weak function f with a cipher and an iterative R of R Sub key. Chaos and key diffusion are the basic principles of block cipher algorithm design. Variable-length keys and groupings are key points in the design of the system to protect against differential and linear attacks in known plaintext.
  
AES is the United States Institute of Standards and Technology NIST's 21st century encryption standard designed to replace DES.

The basic requirements of the

Aes are that the symmetric packet cipher system is used, the minimum number of key lengths is 128, 192, 256, and the packet length is 128 bits, and the algorithm should be easy to implement with various hardware and software. 1998 NIST began the first round of AES analysis, testing and solicitation, resulting in a total of 15 candidate algorithms. March 1999 completed the second round of AES2 analysis, testing. October 2, 2000 the United States Government formally announced the selection of Belgian cryptography, Joan Daemen and Vincent Rijmen proposed a cryptographic algorithm Rijndael as AES. The

AES encrypted block size is maximum 256bit, but the key size is theoretically not capped. AES encryption has many rounds of duplication and transformation. The approximate steps are as follows:

1. Key extension (keyexpansion)
2. Initial wheel (Initial Round)
3. Repeat round (Rounds), each round also includes: Subbytes, Shiftrows, Mixco Lumns, AddRoundKey
4. Final Round, final round without mixcolumns.

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 java.io.UnsupportedEncodingException;
Import java.security.InvalidKeyException;
Import java.security.NoSuchAlgorithmException;

Import Java.security.SecureRandom;
     Public abstract class Aeshelper {/** * encryption * @param content needs to be encrypted @param salt encrypted password * @return */public static byte[] Encrypt (string content, string salt) {try {securerandom R
            Andom = Securerandom.getinstance ("sha1prng");
            Random.setseed (Salt.getbytes ());
            Keygenerator KGen = keygenerator.getinstance ("AES");
            Kgen.init (128, random);
            Secretkey Secretkey = Kgen.generatekey ();
            byte[] Encodeformat = secretkey.getencoded (); SecreTkeyspec key = new Secretkeyspec (Encodeformat, "AES");
            Cipher Cipher = cipher.getinstance ("AES");//Create cipher byte[] bytecontent = content.getbytes ("Utf-8");
            Cipher.init (Cipher.encrypt_mode, key);//Initialize byte[] result = cipher.dofinal (bytecontent); return result;
        Encryption} 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 * @param content to be decrypted * @param salt decryption key * @return/public Stati C byte[] Decrypt (byte[] content, String salt) {try {keygenerator KGen = keygenerator.getinstance ("AES");
            SecureRandom securerandom = securerandom.getinstance ("sha1prng");
            Securerandom.setseed (Salt.getbytes ());
            Kgen.init (128, SecureRandom);
            Secretkey Secretkey = Kgen.generatekey ();
            byte[] Encodeformat = secretkey.getencoded ();
            Secretkeyspec key = new Secretkeyspec (Encodeformat, "AES"); Cipher Cipher = cipher.getinstance ("AES");//Create cipher Cipher.init (Cipher.decrypt_mode, key);//Initialize by
            Te[] result = cipher.dofinal (content); return result;
        Encryption} 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;
        public static String bytestohexstring (byte[] src) {stringbuffer sb = new StringBuffer ();
            for (int i = 0; i < src.length i++) {String hex = integer.tohexstring (Src[i] & 0xFF);
            if (hex.length () = = 1) {hex = ' 0 ' + hex;
        } sb.append (Hex.touppercase ());
    return sb.tostring (); public static string Encrypttostr (string content, string password) {return bytestohexstring Encrypt (content
    , password)); public static byte[] Decrypt (string content, String KeyWord) {return decrypt hexstringtobytes (content), ke
    Yword);  public static byte[] Hexstringtobytes (String hexstring) {if (Hexstring.length () < 1) return
        Null
        Byte[] result = new Byte[hexstring.length ()/2]; for (int i = 0; i < hexstring.length ()/2; i++) {int high= Integer.parseint (Hexstring.substring (i * 2, I * 2 + 1), 16);
            int low = Integer.parseint (Hexstring.substring (i * 2 + 1, I * 2 + 2), 16);
        Result[i] = (byte) (high * + low);
    return result; }
}

Here is testcase:

public class Aestest {

    @Test public
    void Testaes () {
        String content = "Carl.zhao";
        String Key = "Http://www.csdn.net";

        Encrypted
        String Encryptresult = aeshelper.encrypttostr (content, Key);

        Decryption
        byte[] Decryptresult = Aeshelper.decrypt (Encryptresult,key);
        Assert.assertequals (content, new String (Decryptresult));
    }

The code above is correct, and I encountered the following problem when I used other code before: running on Windows is fine, but running on Linux prompts the following error:

Javax.crypto.BadPaddingException:Given final block not properly padded

This is because: the SecureRandom implementation completely follows the internal state of the operating system itself. The implementation is the same for each generated key on Windows. But it's different on Solaris or some Linux systems. you can confirm this by printing the log.

my previous code is as follows:

SecureRandom = new SecureRandom (Seed.getbytes ());

the correct code after the modification is as follows:

SecureRandom securerandom = securerandom.getinstance ("sha1prng");
 Securerandom.setseed (Seed.getbytes ());

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.