search
HomeJavajavaTutorialSharing a simple example of implementing AES encryption algorithm in Java

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)); 
   
 } 
  
}

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
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
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools