AES加解密算法
程序员文章站
2022-03-12 22:27:03
...
package com.becom.common.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
- AES加解密算法
*/
@SuppressWarnings(“restriction”)
public class AESUtil {
// **偏移量
public static final String IV = “1234567812345678”;
/**
* 加密
* @param content 需要加密的内容
* @param password 加***,**必须16位
* @return
*/
public static String encrypt(String content, String password){
try {
byte[] raw = password.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// 算法/模式/补码方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 使用CBC模式,需要一个向量iv,可增加加密算法的强度
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// 此处使用BASE64做转码功能,同时能起到2次加密的作用。
byte[] encrypted = cipher.doFinal(content.getBytes());
return new BASE64Encoder().encode(encrypted);
}catch(Exception e){
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param content 待解密内容
* @param password 解***
* @return
*/
public static String decrypt(String content, String password){
try {
byte[] raw = password.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
// 先用base64解密
byte[] encrypted = new BASE64Decoder().decodeBuffer(content);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
return originalString;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
String cKey = "teacher_edu_app_";
String cSrc = "123456";
System.out.println(cSrc);
// 加密
String enString = AESUtil.encrypt(cSrc, cKey);
System.out.println("加密后的字串是:" + enString);
// 解密
String DeString = AESUtil.decrypt("cyFzF/vlavw5WlgUVb18Gg==", cKey);
System.out.println("解密后的字串是:" + DeString);
}
}
上一篇: 一些想法题