AES属于对称加密算法
RSA属于非对称加密算法
一,RSA 加解密工具类
package com.shch.health.util;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import javax.crypto.Cipher;
import com.google.common.collect.Maps;
/**
* Created by xiang.li on 2015/3/3. RSA 加解密工具类
*/
public class RSAUtil {
/**
* 定义加密方式
*/
protected final static String KEY_RSA = "RSA";
/**
* 定义签名算法
*/
protected final static String KEY_RSA_SIGNATURE = "MD5withRSA";
/**
* 定义公钥算法
*/
protected final static String KEY_RSA_PUBLICKEY = "RSAPublicKey";
/**
* 定义私钥算法
*/
protected final static String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";
protected final static String PRIVATEKEY = "30820276020100300D06092A864886F70D0101010500048202603082025C0201000281810089EBFDC41DE5968A586DD7B91F808E163BCF1A0F427D206A3B80D9D761A09444120229747F59433488CAAA0A99D0F3AF9DE03720251E0BDFF68B28E1C106DD66B7B4C7B7EEE7D2AA2B686695F975621876B33EE4B4641CDDC0B14FBDA96C722D9397D2E8AD74A46AC98B82A8A41F6D9527B3D8DEFB2A60D5A642E4709CFFB2150203010001028181008113A11D27B5B45BA942B37F8761F298104554682F9B96F894D3940C244BFA36727C1F7BEDAB0660661CF562926DA1821BC8B90E966E3642D6238A912CEB55CBE972129393667ED2D97718DBEBA6256394E3700A40202C1568E292E50EB0EAC3E0B838F56AF6F6C118E22EF5B18DB4104A07630CC7F383283B821B0568F82641024100C87B0E203F316D0D73348AA4448F60E87FC9BAEABD23DD33E5E55223706B9267216B5381181A84911FC6EA6A90A6BED10881FE7C8491612B39138FBD33A2B0AD024100B01DDE551696F55AC56F17E4B2E0C64DB6F4B6DD93116AC199959B26999416B553B2212B256846665B7E864310DC70913122A7DAE674C1AD2FD3DEF0FC08EC0902402723F7370E7F5CD62266E0A67F882A9859D28DBEA49CAAE425FF26912AB2A5CBA2B7AC7EE8B0CCAEF4B04635F5F5C80D5186E7A371D25C512EFC85B49FAF24A5024035F8B14DFA2241069442BB5BC6C5C37FC575B124AE11445A182B14E4FB63BAA1CF0863C9C928EF8A26B7DB856A01642DDA94F843C92436C65045E9A8885463A10240762C26ED98A3B0F07A6E5E38E3C23A59C6BD1F3CFDF4DD4545CDF5FE5191DD90CAAD8922447E6F65CE33E2040C9A2638EC2C54B9D6DBBC16974653E89BC520C8";
public final static String PUBLICKEY = "30819F300D06092A864886F70D010101050003818D003081890281810089EBFDC41DE5968A586DD7B91F808E163BCF1A0F427D206A3B80D9D761A09444120229747F59433488CAAA0A99D0F3AF9DE03720251E0BDFF68B28E1C106DD66B7B4C7B7EEE7D2AA2B686695F975621876B33EE4B4641CDDC0B14FBDA96C722D9397D2E8AD74A46AC98B82A8A41F6D9527B3D8DEFB2A60D5A642E4709CFFB2150203010001";
/**
* 初始化密钥
*
* @return
*/
public static Map<String, Object> init() {
Map<String, Object> map = null;
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA);
generator.initialize(1024);
KeyPair keyPair = generator.generateKeyPair();
// 公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 将密钥封装为map
map = Maps.newHashMap();
map.put(KEY_RSA_PUBLICKEY, publicKey);
map.put(KEY_RSA_PRIVATEKEY, privateKey);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return map;
}
/**
* 用私钥对信息生成数字签名
*
* @param data
* 加密数据
* @param privateKey
* 私钥
* @return
*/
public static String sign(byte[] data, String privateKey) {
String str = "";
try {
// 解密由base64编码的私钥
byte[] bytes = parseHexStr2Byte(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(bytes);
// 指定的加密算法
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
// 取私钥对象
PrivateKey key = factory.generatePrivate(pkcs);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
signature.initSign(key);
signature.update(data);
str = parseByte2HexStr(signature.sign());
}
catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 校验数字签名
*
* @param data
* 加密数据
* @param publicKey
* 公钥
* @param sign
* 数字签名
* @return 校验成功返回true,失败返回false
*/
public static boolean verify(byte[] data, String publicKey, String sign) {
boolean flag = false;
try {
// 解密由base64编码的公钥
byte[] bytes = parseHexStr2Byte(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
// 指定的加密算法
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
// 取公钥对象
PublicKey key = factory.generatePublic(keySpec);
// 用公钥验证数字签名
Signature signature = Signature.getInstance(KEY_RSA_SIGNATURE);
signature.initVerify(key);
signature.update(data);
flag = signature.verify(parseHexStr2Byte(sign));
}
catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 私钥解密
*
* @param data
* 加密数据
* @param key
* 私钥
* @return
*/
public static byte[] decryptByPrivateKey(byte[] data, String key) {
byte[] result = null;
try {
// 对私钥解密
byte[] bytes = parseHexStr2Byte(key);
// 取得私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PrivateKey privateKey = factory.generatePrivate(keySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
result = cipher.doFinal(data);
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 公钥解密
*
* @param data
* 加密数据
* @param key
* 公钥
* @return
*/
public static byte[] decryptByPublicKey(byte[] data, String key) {
byte[] result = null;
try {
// 对公钥解密
byte[] bytes = parseHexStr2Byte(key);
// 取得公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PublicKey publicKey = factory.generatePublic(keySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
result = cipher.doFinal(data);
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 公钥加密
*
* @param data
* 待加密数据
* @param key
* 公钥
* @return
*/
public static byte[] encryptByPublicKey(byte[] data, String key) {
byte[] result = null;
try {
byte[] bytes = parseHexStr2Byte(key);
// 取得公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PublicKey publicKey = factory.generatePublic(keySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
result = cipher.doFinal(data);
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 私钥加密
*
* @param data
* 待加密数据
* @param key
* 私钥
* @return
*/
public static byte[] encryptByPrivateKey(byte[] data, String key) {
byte[] result = null;
try {
byte[] bytes = parseHexStr2Byte(key);
// 取得私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(KEY_RSA);
PrivateKey privateKey = factory.generatePrivate(keySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(factory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
result = cipher.doFinal(data);
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 获取公钥
*
* @param map
* @return
*/
public static String getPublicKey(Map<String, Object> map) {
String str = "";
try {
Key key = (Key) map.get(KEY_RSA_PUBLICKEY);
str = parseByte2HexStr(key.getEncoded());
}
catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 获取私钥
*
* @param map
* @return
*/
public static String getPrivateKey(Map<String, Object> map) {
String str = "";
try {
Key key = (Key) map.get(KEY_RSA_PRIVATEKEY);
str = parseByte2HexStr(key.getEncoded());
}
catch (Exception e) {
e.printStackTrace();
}
return str;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* 测试方法
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String privateKey = PRIVATEKEY;
String publicKey = PUBLICKEY;
// // 生成公钥私钥
// Map<String, Object> map = init();
// publicKey = getPublicKey(map);
// privateKey = getPrivateKey(map);
System.out.println("公钥: \n\r" + publicKey);
System.out.println("私钥: \n\r" + privateKey);
System.out.println("公钥加密--------私钥解密");
String word = "你好,世界!";
byte[] encWord = encryptByPublicKey(word.getBytes(), publicKey);
String encw64 = parseByte2HexStr(encWord);
encWord = parseHexStr2Byte(encw64);
String decWord = new String(decryptByPrivateKey(encWord, privateKey));
System.out.println("加密前: " + word + "\n\r" + "解密后: " + decWord);
System.out.println("私钥加密--------公钥解密");
String english = "Hello, World!";
byte[] encEnglish = encryptByPrivateKey(english.getBytes(), privateKey);
String decEnglish = new String(decryptByPublicKey(encEnglish, publicKey));
System.out.println("加密前: " + english + "\n\r" + "解密后: " + decEnglish);
System.out.println("私钥签名——公钥验证签名");
// 产生签名
String sign = sign(encEnglish, privateKey);
System.out.println("签名:\r" + sign);
// 验证签名
boolean status = verify(encEnglish, publicKey, sign);
System.out.println("状态:\r" + status);
}
}
二,AESUtil aes加密解密工具
package com.shch.health.util;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
/**
* AES加密字符串
*
* @param content
* 需要被加密的字符串
* @param key
* 秘钥
* @return 密文
*/
public static byte[] encrypt(String content, byte[] key) {
try {
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return result;
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解密AES加密过的字符串
*
* @param content
* AES加密过过的内容
* @param key
* 秘钥
* @return 明文
*/
public static byte[] decrypt(byte[] content, byte[] key) {
try {
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));// 初始化为解密模式的密码器
byte[] result = cipher.doFinal(content);
return result; // 明文
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (NoSuchPaddingException e) {
e.printStackTrace();
}
catch (InvalidKeyException e) {
e.printStackTrace();
}
catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 生成一个AES密钥对象
*
* @return
*/
public static SecretKeySpec generateKey() {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom());
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
return key;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* 生成一个AES密钥
* @return
*/
public static byte[] generateKey2byte() {
return generateKey().getEncoded();
}
}
三,ASE与RSA结合使用
package com.shch.health.util;
import com.ykh.base.util.Validators;
public class EncryptUtil {
/**
* 解密
*
* @param aeskey
* AES通过RSA加密后的秘钥
* @param content
* AES加密的密文
*/
public static byte[] aesAndRsaDecrypt(byte[] aeskey, byte[] content) {
// 再使用解密到的AES秘钥对接收到的数据进行解密
return AESUtil.decrypt(content, aeskey);
}
/**
* 解密
*
* @param aeskey
* AES通过RSA加密后的秘钥
* @param content
* AES加密的密文
* @throws Exception
*/
public static byte[] aesAndRsaDecrypt(byte[] aeskey, String content) {
if (Validators.isEmpty(content)) {
return null;
}
return aesAndRsaDecrypt(aeskey, RSAUtil.parseHexStr2Byte(content));
}
public static byte[] getAESKey(String aeskey) {
// 1.使用RSA私钥解密接收到的AES秘钥密文
byte[] aeskey1 = RSAUtil.decryptByPrivateKey(RSAUtil.parseHexStr2Byte(aeskey), RSAUtil.PRIVATEKEY);
return aeskey1;
}
}