package com.ruoyi.system.utils.xiMaUtil;
|
|
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.IvParameterSpec;
|
import javax.crypto.spec.SecretKeySpec;
|
import java.security.Security;
|
|
/**
|
*
|
* 加密方式:AES CBC模式
|
* Key:ciicciicciicciic
|
* IV:ciic2022ciic2022
|
* 例:
|
* 加密前:1234567890
|
* 加密后:10ed567b9d42a385926d6166f97008ce
|
*
|
* 测试地址参考:http://tool.chacuo.net/cryptaes/
|
* AES加密模式:CBC 填充:pkcs7padding 数据块:128位 密码:ciicciicciicciic 偏移量:ciic2022ciic2022 输出:hex 字符集:utf8编码(unicode编码)
|
*
|
*/
|
public class AesUtil {
|
|
static {
|
Security.addProvider(new BouncyCastleProvider());
|
}
|
|
public static void main(String[] args) {
|
try {
|
//根据指定字符串生成秘钥
|
/*KeyGenerator kg = KeyGenerator.getInstance("AES");
|
kg.init(128,new SecureRandom("ceshi".getBytes()));
|
SecretKey sk = kg.generateKey();
|
String keyStr = Base64.getEncoder().encodeToString(sk.getEncoded());
|
byte[] iv = Base64.getDecoder().decode(keyStr);
|
byte[] key = Base64.getDecoder().decode(keyStr); */
|
|
String key = "7bc47ce80ff74c1cbebad1ced111243d";
|
String iv = "69b84732eace4e6a";
|
String content = "1234567890";
|
String encrypted = encrypt(key, iv, content);
|
System.out.println("加密后: " + encrypted);
|
|
String raw = decrypt(key, iv , encrypted);
|
System.out.println("解密后: " + raw);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
|
public static String encrypt(String key, String iv, String content) {
|
try {
|
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");//"算法/模式/补码方式"
|
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
|
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ips);
|
return Hex.byteToHex(cipher.doFinal(content.getBytes()));
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
|
public static String decrypt(String key,String iv, String content) {
|
|
try {
|
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
|
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
|
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ips);
|
return new String(cipher.doFinal(Hex.hexToByte(content)) );
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
}
|