package com.sinata.core.util.juhe;
|
|
|
|
import static com.sinata.core.util.juhe.TelecomUtil.MD5;
|
|
import java.io.UnsupportedEncodingException;
|
import javax.crypto.Cipher;
|
import javax.crypto.spec.SecretKeySpec;
|
import org.apache.commons.codec.binary.Base64;
|
|
public class SecurityAESTool {
|
|
/**
|
* AES加密
|
*
|
* @param str
|
* 明文
|
* @param key
|
* 秘钥
|
* @return
|
*/
|
public static String encrypt(String str, String key) {
|
byte[] crypted = null;
|
try {
|
|
SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
cipher.init(Cipher.ENCRYPT_MODE, skey);
|
|
String enStr = str;
|
crypted = cipher.doFinal(enStr.getBytes("UTF-8"));
|
} catch (Exception e) {
|
System.out.println(e.toString());
|
}
|
|
String body = new String(Base64.encodeBase64(crypted));
|
return body;
|
}
|
|
/**
|
* AES解密
|
*
|
* @param input
|
* @param key
|
* @return
|
*/
|
public static String decrypt(String input, String key) {
|
byte[] output = null;
|
String body = null;
|
if (input == null || key == null) {
|
return null;
|
}
|
try {
|
SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
cipher.init(Cipher.DECRYPT_MODE, skey);
|
byte[] b = Base64.decodeBase64(input);
|
// 解密
|
output = cipher.doFinal(b);
|
body = new String(output, "UTF-8");
|
} catch (Exception e) {
|
System.out.println(e.toString());
|
}
|
return body;
|
}
|
|
public static void main(String[] args) throws UnsupportedEncodingException {
|
String openid = "JH1ad5c53745350580f7c24ca4b09717de";
|
String key = MD5(openid).substring(0, 16);//取前16位作为加密密钥
|
//String key = MD5Util.encrypt(appId).toLowerCase(Locale.ROOT).substring(0,16);//秘钥
|
System.out.println(key);
|
//取lowerCase前16位
|
String realname = "米涛"; // 明文
|
String idcard = "510603199912053256"; // 明文
|
|
realname = SecurityAESTool.encrypt(realname, key);
|
System.out.println("realname:"+realname);
|
System.out.println("realname:"+SecurityAESTool.decrypt(realname, key));
|
idcard = SecurityAESTool.encrypt(idcard, key);
|
System.out.println("idcard:"+idcard);
|
System.out.println("idcard:"+SecurityAESTool.decrypt(idcard, key));
|
String mobile = "18283820718";
|
mobile = SecurityAESTool.encrypt(mobile, key);
|
System.out.println("mobile:"+mobile);
|
System.out.println("mobile:"+SecurityAESTool.decrypt(mobile, key));
|
|
}
|
}
|