为了保障数据对接的安全性,我们采用AES与RAS结合加解密的方案。
【服务方】生成一对 RSA 秘钥,自己保留私钥,将公钥由互联网交给【合作方】
【合作方】使用 AES 秘钥对要传送的报文数据(明文) Data 进行加密,生成密文 EncryData
【合作方】使用 RSA 公钥对AES秘钥加密,生成 EncryKey
【合作方】将加密后的 AES 秘钥 EncryKey 和加密后的报文 EncryData 通过网络传输给服务器端
【服务方】通过网络拿到上述步骤中的 EncryKey 和 EncryData
【服务方】用 RSA 私钥对 EncryKey (加密的 AES 秘钥)进行解密操作,得到 AesKey
【服务方】用 AesKey 解密传入过来的加密报文 EncryData,得到报文数据(明文) Data
RSAUtils
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
public class RSAUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
public static final String KEY_ALGORITHM = "RSA";
public static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String PUBLIC_KEY = "publicKey";
public static final String PRIVATE_KEY = "privateKey";
public static final int KEY_SIZE = 1024;
public static final String PLAIN_TEXT = "Hello world!";
public static final String DEFAULT_PRIVATE_KEY = "**********";
public static final String DEFAULT_PUBLIC_KEY = "**********";
/**
* 获取公钥
* @param publicKeyStr
* @return
* @throws Exception
*/
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
return restorePublicKey(publicKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (IOException e) {
throw new Exception("公钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 还原公钥,X509EncodedKeySpec 用于构建公钥的规范
* @param keyBytes
* @return
*/
public static PublicKey restorePublicKey(byte[] keyBytes) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
return publicKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
throw new Exception("");
}
}
/**
* 通过私钥KEY获取解密私钥
* @param privateKeyStr
* @return
* @throws Exception
*/
public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return restorePrivateKey(privateKey.getEncoded());
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (IOException e) {
throw new Exception("公钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
}
}
/**
* 获取私钥
* @param keyBytes
* @return
*/
public static PrivateKey restorePrivateKey(byte[] keyBytes) {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
try {
KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
// TODO Auto-generated catch block
LOGGER.error("获取私钥失败", e);
}
return null;
}
/**
* 加密,三步走
* @param key
* @param plainText
* @return
*/
public static byte[] RSAEncode(PublicKey key, byte[] plainText) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plainText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
LOGGER.error("加密失败", e);
}
return null;
}
/**
* 解密,三步走
* @param key
* @param encodedText
* @return
*/
public static byte[] RSADecode(PrivateKey key, byte[] encodedText) {
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(encodedText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
LOGGER.error("解密失败", e);
}
return null;
}
public static void main(String[] ar) throws Exception {
String str = "{\"a\":\"hello\"}";
System.out.println("待加密报文:" + str);
PublicKey publicKey = loadPublicKey(DEFAULT_PUBLIC_KEY);
PrivateKey privateKey = loadPrivateKey(DEFAULT_PRIVATE_KEY);
// String encodeStr = Base64.encodeBase64String(RSAEncode(publicKey, str.getBytes()));
// System.out.println("加密后密文:" + encodeStr);
// String decodeStr = new String(RSADecode(privateKey, Base64.decodeBase64(encodeStr)));
// System.out.println("解密后密文:" + decodeStr);
String randomKey = String.valueOf(System.currentTimeMillis());
System.out.println("随机KEY randomKey:"+randomKey);
String cipherText = AESUtils.encrypt(str,randomKey);
System.out.println("AES加密请求内容cipherText:"+cipherText);
String cipherKey = Base64.encodeBase64String(RSAEncode(publicKey, randomKey.getBytes()));
System.out.println("RSA加密后的key:"+cipherKey);
System.out.println("请求内容:{\"encryptStr\":\"" + cipherText+"\",\"aesKey\":\""+cipherKey+"\"}");
String key = new String(RSADecode(privateKey, Base64.decodeBase64(cipherKey)));
System.out.println("RSA私钥解密后的key:"+key);
String decodeData = AESUtils.decrypt(cipherText,key);
System.out.println("AES解密后:"+decodeData);
}
}
AESUtils
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class AESUtils{
private static final Logger LOGGER = LoggerFactory.getLogger(AESUtils.class);
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
/**
* AES 加密操作
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeBase64String(result);//通过Base64转码返回
} catch (Exception ex) {
LOGGER.error("加密失败",ex);
}
return null;
}
/**
* AES 解密操作
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String password) {
try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
//使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
//执行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
LOGGER.error("解密失败",ex);
}
return null;
}
/**
* 生成加密秘钥
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null;
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//AES 要求密钥长度为 128
kg.init(128, new SecureRandom(password.getBytes()));
//生成一个密钥
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
LOGGER.error("生成密钥失败",ex);
}
return null;
}
public static void main(String[] args) {
String s = "hello";
System.out.println("s:" + s);
String s1 = AESUtils.encrypt(s, "1234");
System.out.println("s1:" + s1);
}
}