Home Java javaTutorial Sharing a simple example of implementing AES encryption algorithm in Java

Sharing a simple example of implementing AES encryption algorithm in Java

Jan 24, 2017 am 11:09 AM

Advanced Encryption Standard (English: Advanced Encryption Standard, abbreviation: AES), also known as Rijndael encryption method in cryptography, is a block encryption standard adopted by the U.S. federal government. This standard is used to replace the original DES. It has been analyzed by many parties and is widely used around the world.
Most AES calculations are done in a special finite domain.
The AES encryption process operates on a 4×4 byte matrix. This matrix is ​​also called "state", and its initial value is a plaintext block (the size of an element in the matrix is ​​the size of the plaintext block A Byte). (The Rijndael encryption method supports larger blocks, and the number of matrix rows can be increased as appropriate.) When encrypting, each AES encryption cycle (except the last round) contains 4 steps:

AddRoundKey — Each byte in the matrix is ​​XORed with the round key; each subkey is generated by the key generation scheme.

SubBytes — Replace each byte with the corresponding byte using a lookup table through a non-linear replacement function.

ShiftRows — circularly shifts each row in the matrix.

MixColumns — To fully mix the operations of each row in the matrix. This step uses a linear transformation to blend the four bytes of each column.

The MixColumns step is omitted in the last encryption cycle and replaced by another AddRoundKey.

Basic implementation of Java:

package com.stone.security; 
  
import java.util.Arrays; 
  
import javax.crypto.Cipher; 
import javax.crypto.KeyGenerator; 
import javax.crypto.SecretKey; 
import javax.crypto.spec.IvParameterSpec; 
  
/** 
 * AES 算法 对称加密,密码学中的高级加密标准 2005年成为有效标准 
 */
public class AES { 
 static Cipher cipher; 
 static final String KEY_ALGORITHM = "AES"; 
 static final String CIPHER_ALGORITHM_ECB = "AES/ECB/PKCS5Padding"; 
 static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding"; 
/** 
 * AES/CBC/NoPadding 要求 
 * 密钥必须是16位的;Initialization vector (IV) 必须是16位 
 * 待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常: 
 * javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes 
 * 
 * 由于固定了位数,所以对于被加密数据有中文的, 加、解密不完整 
 * 
 * 可 以看到,在原始数据长度为16的整数n倍时,假如原始数据长度等于16*n,则使用NoPadding时加密后数据长度等于16*n, 
 * 其它情况下加密数据长 度等于16*(n+1)。在不足16的整数倍的情况下,假如原始数据长度等于16*n+m[其中m小于16], 
 * 除了NoPadding填充之外的任何方 式,加密数据长度都等于16*(n+1). 
 */
 static final String CIPHER_ALGORITHM_CBC_NoPadding = "AES/CBC/NoPadding"; 
  
 static SecretKey secretKey; 
   
 public static void main(String[] args) throws Exception { 
 method1("a*jal)k32J8czx囙国为国宽"); 
 method2("a*jal)k32J8czx囙国为国宽"); 
 method3("a*jal)k32J8czx囙国为国宽"); 
   
 method4("123456781234囙为国宽");// length = 16 
 method4("12345678abcdefgh");// length = 16 
   
 } 
  
 /** 
 * 使用AES 算法 加密,默认模式 AES/ECB 
 */
 static void method1(String str) throws Exception { 
 cipher = Cipher.getInstance(KEY_ALGORITHM); 
 //KeyGenerator 生成aes算法密钥 
 secretKey = KeyGenerator.getInstance(KEY_ALGORITHM).generateKey(); 
 System.out.println("密钥的长度为:" + secretKey.getEncoded().length); 
   
 cipher.init(Cipher.ENCRYPT_MODE, secretKey);//使用加密模式初始化 密钥 
 byte[] encrypt = cipher.doFinal(str.getBytes()); //按单部分操作加密或解密数据,或者结束一个多部分操作。 
   
 System.out.println("method1-加密:" + Arrays.toString(encrypt)); 
 cipher.init(Cipher.DECRYPT_MODE, secretKey);//使用解密模式初始化 密钥 
 byte[] decrypt = cipher.doFinal(encrypt); 
 System.out.println("method1-解密后:" + new String(decrypt)); 
   
 } 
  
 /** 
 * 使用AES 算法 加密,默认模式 AES/ECB/PKCS5Padding 
 */
 static void method2(String str) throws Exception { 
 cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB); 
 //KeyGenerator 生成aes算法密钥 
 secretKey = KeyGenerator.getInstance(KEY_ALGORITHM).generateKey(); 
 System.out.println("密钥的长度为:" + secretKey.getEncoded().length); 
   
 cipher.init(Cipher.ENCRYPT_MODE, secretKey);//使用加密模式初始化 密钥 
 byte[] encrypt = cipher.doFinal(str.getBytes()); //按单部分操作加密或解密数据,或者结束一个多部分操作。 
   
 System.out.println("method2-加密:" + Arrays.toString(encrypt)); 
 cipher.init(Cipher.DECRYPT_MODE, secretKey);//使用解密模式初始化 密钥 
 byte[] decrypt = cipher.doFinal(encrypt); 
 System.out.println("method2-解密后:" + new String(decrypt)); 
   
 } 
  
 static byte[] getIV() { 
 String iv = "1234567812345678"; //IV length: must be 16 bytes long 
 return iv.getBytes(); 
 } 
  
 /** 
 * 使用AES 算法 加密,默认模式 AES/CBC/PKCS5Padding 
 */
 static void method3(String str) throws Exception { 
 cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC); 
 //KeyGenerator 生成aes算法密钥 
 secretKey = KeyGenerator.getInstance(KEY_ALGORITHM).generateKey(); 
 System.out.println("密钥的长度为:" + secretKey.getEncoded().length); 
   
 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(getIV()));//使用加密模式初始化 密钥 
 byte[] encrypt = cipher.doFinal(str.getBytes()); //按单部分操作加密或解密数据,或者结束一个多部分操作。 
   
 System.out.println("method3-加密:" + Arrays.toString(encrypt)); 
 cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(getIV()));//使用解密模式初始化 密钥 
 byte[] decrypt = cipher.doFinal(encrypt); 
 System.out.println("method3-解密后:" + new String(decrypt)); 
   
 } 
  
 /** 
 * 使用AES 算法 加密,默认模式 AES/CBC/NoPadding 参见上面对于这种mode的数据限制 
 */
 static void method4(String str) throws Exception { 
 cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC_NoPadding); 
 //KeyGenerator 生成aes算法密钥 
 secretKey = KeyGenerator.getInstance(KEY_ALGORITHM).generateKey(); 
 System.out.println("密钥的长度为:" + secretKey.getEncoded().length); 
   
 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(getIV()));//使用加密模式初始化 密钥 
 byte[] encrypt = cipher.doFinal(str.getBytes(), 0, str.length()); //按单部分操作加密或解密数据,或者结束一个多部分操作。 
   
 System.out.println("method4-加密:" + Arrays.toString(encrypt)); 
 cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(getIV()));//使用解密模式初始化 密钥 
 byte[] decrypt = cipher.doFinal(encrypt); 
   
 System.out.println("method4-解密后:" + new String(decrypt)); 
   
 } 
  
}
Copy after login

For more simple examples of Java implementation of the AES encryption algorithm to share related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles