什么是AES加密算法
AES是对称加密算法,也就是通信双方使用同一个密钥K。
A和B先沟通密钥K,然后A使用K对明文加密,生成密文H,将密文发给B,B收到密文后用密钥K解密。
java语言实现代码
package AES;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
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;
/**
* @author qingnianren
*/
public class AES{
/**
* 生成密钥
*
* @return
* @throws NoSuchAlgorithmException
*/
public static SecretKey generateKey() throws NoSuchAlgorithmException {
//自动生成密钥
//实例化支持AES算法的密钥生成器(算法名称命名需按规定,否则抛出异常)
KeyGenerator secretGenerator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
secretGenerator.init(secureRandom);
//生成密钥
SecretKey secretKey = secretGenerator.generateKey();
//generateKey()方法返回自动生成的密钥值
return secretKey;
}
static Charset charset = Charset.forName("UTF-8");
/**
* 加密
*
* @param content
* @param secretKey
* @return
*/
public static byte[] encrypt(String content, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { // 加密
return aes(content.getBytes(charset), Cipher.ENCRYPT_MODE, secretKey);
}
/**
* 解密
*
* @param contentArray
* @param secretKey
* @return
*/
public static String decrypt(byte[] contentArray, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { // 解密
byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey);
return new String(result, charset);
}
private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(mode, secretKey);
byte[] result = cipher.doFinal(contentArray);
return result;
}
public static void main(String[] args) {
System.out.println("请输入要加密的明文:");
//从键盘读入要加密的明文
Scanner in =new Scanner(System.in);
String content=in.nextLine();
SecretKey secretKey;
try {
long timeStartEncry = System.currentTimeMillis();
// 生成密钥,调用自动生成密钥的函数
secretKey = generateKey();
byte[] encryptResult = encrypt(content, secretKey);
long timeEndEncry = System.currentTimeMillis();
System.out.println("加密后的结果为==" + new String(encryptResult, charset));
String decryptResult = decrypt(encryptResult, secretKey);
System.out.println("解密后的结果==" + decryptResult);
System.out.println("加密用时:" + (timeEndEncry - timeStartEncry));
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
}
}
运行结果·: