package com.hif.utils;
import javax.crypto.*;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* @ClassName AesUtils
* @Author 偷了千千晚星
* @Date 2021/7/4
**/
public class AesUtils {
//algorithm名-"AES"
private static final String ALGORITHM = "AES";
//生成Key
public static SecretKey generateKey() throws NoSuchAlgorithmException {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);//根据算法名获得KeyGenerator实例
keyGenerator.init(new SecureRandom());//传入随机数初始化secretKey
SecretKey secretKey = keyGenerator.generateKey();
return secretKey;
}
//声明获取数组的字符格式(避免原字符中有中文出现的问题)
private static final String CHARSET_UTF8 = "UTF-8";
//加密
public static byte[] encrypt(String oriStr, SecretKey secretKey) throws UnsupportedEncodingException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
byte[] bytes = oriStr.getBytes(CHARSET_UTF8);//获取原字符串内容的bytes
byte[] secretBytes = doAES(bytes, Cipher.ENCRYPT_MODE, secretKey);//进行AES处理
return secretBytes;
}
//解密
public static String decrypt(byte[] secretBytes,SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
byte[] bytes = doAES(secretBytes, Cipher.DECRYPT_MODE, secretKey);//对加密后的bytes进行AES解密操作
String contentStr = new String(bytes);//将bytes转回String内容
return contentStr;
}
/**
* doAes AES处理
*
* @param oriBytes 初始数组
* @param opMode 操作模式(加密/解密)
* @return {@link byte[]}
*/
public static byte[] doAES(byte[] oriBytes,int opMode,SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(opMode,secretKey); //初始化cipher
/**
* 大量内容或是对部分内容加密使用cipher.update()+cipher.doFinal()
* 处理少量数据可以直接使用doFinal
*/
byte[] secretBytes = cipher.doFinal(oriBytes);
return secretBytes;
}
public static void main(String[] args) {
String oriStr = new String("你好,我是Celia");//要处理的原内容oriStr
try {
SecretKey secretKey = generateKey();//获取密码钥匙secretKey
//进行加密操作
byte[] secretBytes = encrypt(oriStr, secretKey);
//为了查看对secretBytes进行转字符串操作
String secretStr = new String(secretBytes,CHARSET_UTF8);
System.out.println("加密后的字节数组是:"+secretStr);
//进行解密操作
String contentStr = decrypt(secretBytes, secretKey);
System.out.println("解密后的内容字符是:"+contentStr);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | IllegalBlockSizeException | InvalidKeyException | BadPaddingException | NoSuchPaddingException e) {
e.printStackTrace();
}
}
}
比较简单的AES实现
最新推荐文章于 2024-05-27 13:00:00 发布