Java symmetric encryption Algorithm aes--encryption and decryption __aes

Source: Internet
Author: User
Tags decrypt generator key string rounds

With the development of symmetric cipher, the DES data Encryption Standard algorithm, because of its small key length (56 bits), has not adapted to the requirements of today's distributed open Network for data encryption security, so 1997 NIST publicly recruited new data encryption Standard, namely AES[1]. After a tricycle selection, the Rijndael algorithm submitted by the Belgian Joan Daeman and Vincent Rijmen was proposed as the final algorithm for AES. This algorithm will become a new data encryption standard in the United States and is widely used in various fields. Although people have different views on AES, but overall, AES as a new generation of data encryption standards converge on the strong security, high-performance, high efficiency, ease of use and flexible advantages. The AES design has three key lengths: 128,192,256 bits, whereas AES's 128 keys are 1021 times times stronger than Des's 56 keys [2]. The AES algorithm mainly includes three aspects: wheel change, circle number and key expansion.  This paper takes 128 as an example to introduce the basic principle of the algorithm, and combine the AVR assembly language to realize the Advanced Data encryption algorithm AES. AES is a packet key, the algorithm input 128-bit data, the key length is 128 bits. NR represents the number of rounds that are encrypted for a data group (the relationship between the number of cryptographic rounds and key lengths, as shown in table 1). Each round requires the participation of an extended key Expandedkey (i) with the same length as the input packet. Because of the limited encryption key k length in the external input, a key extender (keyexpansion) is used in the algorithm to extend the external key k to a longer bit string to generate the encryption and decryption keys for each round.
1.1-Circle Change
AES each Circle transformation consists of the following three layers:
Nonlinear Layer--subbyte transform;
Line-line mixed layer--shiftrow and mixcolumn operation;
Key addition Layer--perform addroundkey operation.
The ①subbyte transform is a nonlinear byte conversion that acts on each byte of the state, and can be mapped by the computed s box.
②shiftrow is a byte transposition. It loops the rows in the state according to different offsets, which are also selected according to NB (3).
③ in the Mixcolumn transformation, each column in the state is regarded as the result of multiplying the polynomial a (x) on the GF (28) and the fixed polynomial C (x). The coefficients of the B (x) =c (x) *a (x) are calculated as follows: * operations are not ordinary multiplication operations, but special operations, i.e. B (x) =c (x) A (x) (mod x4+1) for this operation B0=02. A0+03. A1+a2+a3 Xtime (a0) = 02. A0 among them, symbols ". "The same-remainder multiplication of a eight irreducible polynomial [3]."
For the inverse change, the matrix C is changed to the corresponding D, i.e. B (x) =d (x) *a (x).
The ④ key plus layer operation (addround) is a bitwise "XOR" of the corresponding byte in the Circle key state.
⑤ according to the nature of the linear variation [1], the decryption operation is the inverse change of the encryption change. This is no longer described in detail.
1.2-Wheel Change
For different packet lengths, the corresponding wheel change times are different, as shown in table 1.
1.3 Key expansion


The AES algorithm uses the external input key K (the word number of the key string is NK) and obtains the extended key of 4 (nr+1) Word through the extender of the key. It involves the following three modules: ① position transform (rotword)--Changing a 4-byte sequence [a,b,c,d] to [b,c,d,a];②s-Box transform (subword)--Substituting a 4-byte for a S-box; ③ Transform Rcon--rcon represents 32-bit bit words [ xi-1,00,00,00]. Here the X is (02), such as rcon[1]=[01000000];rcon[2]=[02000000];rcon[3]=[04000000] ... Extension key generation: The former NK word for the extended key is the external key k; the word w[] equals the "XOR", or "w[]=w[[i-1]]w[[i-nk]" of the former "W[[i-1" (formerly NK Word w[[i-nk)]. But if I is a multiple of Nk, then W=w[i-nk]subword (Rotword (w[[i-1)]) Rcon[i/nk].



AES symmetric encryption and decryption


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 key generator
*2. Initialize the key generator according to the ecnoderules rule
*3. Generate key
*4. Create and initialize a cipher
*5. Content encryption
*6. return string
* /
public static String AESEncode(String encodeRules,String content){
Try {
//1. Construct key generator, specified as AES algorithm, case insensitive
KeyGenerator keygen=KeyGenerator.getInstance("AES");
//2. Initialize the key generator according to the ecnoderules rule
//Generate a 128 bit random source based on the incoming byte array
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
//3. Generate the original symmetric key
SecretKey original_key=keygen.generateKey();
//4. Get the byte array of the original symmetric key
byte [] raw=original_key.getEncoded();
//5. Generate AES key according to byte array
SecretKey key=new SecretKeySpec(raw, "AES");
//6. AES self cipher according to the specified algorithm
Cipher cipher=Cipher.getInstance("AES");
//7. Initialize the cipherer. The first parameter is the encryption mode or decrypt mode operation. The second parameter is the key used
cipher.init(Cipher.ENCRYPT_MODE, key);
//8. Get the byte array of encrypted content (set to UTF-8 here), otherwise, if there is a mixture of Chinese and English in the content, it will be decrypted as garbled code
byte [] byte_encode=content.getBytes("utf-8");
//9. According to the initialization method of the cipher -- encryption: encrypt the data
byte [] byte_AES=cipher.doFinal(byte_encode);
//10. Convert encrypted data to string
//No package will be found in base64encoder
//Solution:
//In the build path of the project, first remove the JRE system library, and then add the JRE system library. After recompilation, everything is normal.
String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
//11. Return string
return 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's a mistake, add nulll
return null;        
}
/ *
* declassified
*Decryption process:
*1. The same as encryption step 1-4
*2. Reverse spinning the encrypted string into byte [] array
*3. Decrypt the encrypted content
* /
public static String AESDncode(String encodeRules,String content){
Try {
//1. Construct key generator, specified as AES algorithm, case insensitive
KeyGenerator keygen=KeyGenerator.getInstance("AES");
//2. Initialize the key generator according to the ecnoderules rule
//Generate a 128 bit random source based on the incoming byte array
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
//3. Generate the original symmetric key
SecretKey original_key=keygen.generateKey();
//4. Get the byte array of the original symmetric key
byte [] raw=original_key.getEncoded();
//5. Generate AES key according to byte array
SecretKey key=new SecretKeySpec(raw, "AES");
//6. AES self cipher according to the specified algorithm
Cipher cipher=Cipher.getInstance("AES");
//7. Initialize the cipherer. The first parameter is the encryption mode or decrypt mode operation. The second parameter is the key used
cipher.init(Cipher.ENCRYPT_MODE, key);
//8. Get the byte array of encrypted content (set to UTF-8 here), otherwise, if there is a mixture of Chinese and English in the content, it will be decrypted as garbled code
byte [] byte_encode=content.getBytes("utf-8");
//9. According to the initialization method of the cipher -- encryption: encrypt the data
byte [] byte_AES=cipher.doFinal(byte_encode);
//10. Convert encrypted data to string
//No package will be found in base64encoder
//Solution:
//In the build path of the project, first remove the JRE system library, and then add the JRE system library. After recompilation, everything is normal.
String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
//11. Return string
return 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's a mistake, add nulll
Return null;
}
/ *
* declassified
*Decryption process:
*1. The same as encryption step 1-4
*2. Reverse spinning the encrypted string into byte [] array
*3. Decrypt the encrypted content
* /
public static String AESDncode(String encodeRules,String content){
Try {
//1. Construct key generator, specified as AES algorithm, case insensitive
KeyGenerator keygen=KeyGenerator.getInstance("AES");
//2. Initialize the key generator according to the ecnoderules rule
//Generate a 128 bit random source based on the incoming byte array
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
//3. Generate the original symmetric key
SecretKey original_key=keygen.generateKey();
//4. Get the byte array of the original symmetric key
byte [] raw=original_key.getEncoded();
//5. Generate AES key according to byte array
SecretKey key=new SecretKeySpec(raw, "AES");
//6. AES self cipher according to the specified algorithm
Cipher cipher=Cipher.getInstance("AES");
//7. Initialize the cipherer. The first parameter is the encryption mode or decrypt mode operation. The second parameter is the key used
cipher.init(Cipher.DECRYPT_MODE, key);
//8. Decode encrypted and encoded contents into byte array
byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
/ *
* declassified
* /
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's a mistake, add nulll
Return 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 encryption rules");
String encodeRules=scanner.next();
System. Out. Println ("please enter the content to be encrypted:");
String content = scanner.next();
System. Out. Println ("according to the input rules" + encoderules + "the encrypted ciphertext is:" + Se. Aesencode (encoderules, content));
/ *
* declassified
* /
System.out.println ("use AES symmetric decryption, please enter the encryption rules: (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 input rules" + encoderules + "the decrypted plaintext is:" + Se. Aesdncode (encoderules, content));
}
}

Test results:







Using AES symmetric encryption, enter the rules for encryption
use AES symmetric encryption
Enter the content to be encrypted: use AES symmetric encryption
to use AES symmetric encryption based on the rules of the input encrypted cipher is: z0nwrnphghgxhn0cqjls58ycjhmcbfer33rws7lw+ay=
using AES symmetric decryption, enter the rules for encryption: (must be the same as encryption)
use AES symmetric encryption
Please enter the content to decrypt (redaction):
z0nwrnphghgxhn0cqjls58ycjhmcbfer33rws7lw+ay=
using AES symmetric encryption to decrypt the plaintext according to the rules entered is: using AES symmetric encryption




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.