![]()
package com.oms.common.utils;
import com.nh.oms.common.utils.encoder.BASE64Decoder;
import com.nh.oms.common.utils.encoder.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AesUtil {
//实际的加密解密操作
private static byte[] Operation(byte[] src,String key,int mode) throws Exception{
if (key==null) {
System.out.println("Key不能为空");
return null;
}
if (key.length()!=16) {
System.out.println("Key需要16位长度");
return null;
}
byte[] raw=key.getBytes("utf-8");
SecretKeySpec keySpec=new SecretKeySpec(raw, "AES");
Cipher cipher=Cipher.getInstance("AES");
cipher.init(mode, keySpec);
byte[] encrypted=cipher.doFinal(src);
return encrypted;
}
public static byte[] encrypt(byte[] src, String key) throws Exception {
return Operation(src, key, Cipher.ENCRYPT_MODE);
}
public static byte[] decrypt(byte[] src, String key) throws Exception {
return Operation(src, key, Cipher.DECRYPT_MODE);
}
public static String encryptStr(String src, String key) throws Exception {
byte[] resultByte = Operation(src.getBytes("utf-8"), key, Cipher.ENCRYPT_MODE);
return new BASE64Encoder().encode(resultByte);
}
public static String decryptStr(String src, String key) throws Exception {
byte[] base64Byte=new BASE64Decoder().decodeBuffer(src);
byte[] base64ResultByte = Operation(base64Byte, key, Cipher.DECRYPT_MODE);
return new String(base64ResultByte);
}
public static void main(String[] args) {
try {
//我是加密密钥
String key = "securitysecurity";
String content = "这是机密文件不能泄露";
System.out.println("加密前:" +content);
System.out.println("密钥:" +key);
try {
String enCodeStr=encryptStr(content, key);
System.out.println("\n加密后Base64的数据,这个可在C#/.NET解密:");
System.out.println(enCodeStr);
System.out.println("\nBase64解密后的数据:");
String deCodeStr=decryptStr(enCodeStr, key);
System.out.println(deCodeStr);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}