为了保证安全,现在web应用中,大部分都使用https了,但是https只对传输通道进行加密,一旦通道被破,明文数据就被攻击者获取了,为了保证数据传输过程中的安全性,需要对敏感数据传输前做一次加密,下面演示如何通过RSA加密,做到前后端数据的安全传输:
首先我们需要一个前端js加密工具,这个工具叫JSEncrypt,
官方主页:http://travistidwell.com/jsencrypt/
下载地址:https://github.com/travist/jsencrypt/archive/master.zip
要缩包里面有个jsencrypt.min.js文件,就是我们要导入的文件,首先jsp页面导入这个js文件;
<script src="js/jsencrypt.min.js"></script>
<script>
var encrypt = new JSEncrypt();
encrypt.setPublicKey("<%=RSAUtil.publicKey%>");
console.log("这是123456的密文:"+encrypt.encrypt("123456"));
</script>
java端解密:
System.out.println( RSACoder.decryptBase64AndRSAByPrivateKey("这里输入密文") );
RSAUtil是一个java工具类:
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.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 敏感信息加密
* @author zqz 20180818
*/
public class RSACoder {
private static Logger logger = LoggerFactory.getLogger(RSACoder.class);
public static final String KEY_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
private static final String PUBLIC_KEY = "RSAPublicKey";
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**公钥,请换掉这里的key,乱写的**/
public static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKsSDFQDGtwz9qRQC6PLuShXMfaRUY9Or4CwqQTiTiukU8rTjmk6xcWGarieJNTjLkGRUbTjzkSzcDtGt1AItLUbS0hZvsd4K7BsrkT67/oNI3xZ9f5mw8SPfvyZnnMvNTy9KkkssMz/TnXrZLg4FI3U5yNRZQVOUVSPIYcGFc1Z6zQIFwIDAQAB";
/**私钥,请换掉这里的key,乱写的**/
public static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmASDFScAgEAAoGBAMa3DP2pFALo8u5KFcx9pFRj06vgLCpBOJOK6RTytOOaTrFxYZquJ4k1OMuQSDdfffffRtOPORLNwO0a3UAi0tRtLSFm+BODgrsGyuRPrv+g0jfFn1/mbDxI9+/Jmecy81PL0qSSywzP9OdetkuDgUjdTnI1FlBU5RVI8hhwYVzVnrNAgXAgMBAAECgYAddPctBwpbYBLa9gqDNMDObbnsCaAiZ2auoHHq1AuyjaZKsYcJefWMZmJT8sScq1A88vFWca/td7cW4VZVXCVNASLC0TWUgGqe42NArT+2A9UiKJBO83JEdABo1UNlbhS2PdQRutsq8j1JyCwBehF7GcIlPbC0TcCKy1DMl2u5qQJBAPRDA3JwVHOs/eXkiQRjbpWEKZX2Fc6kbWIrf96oXQi7aRsrKVK/g4qgNNaNcCYn/VksCLfHbe74qed5sVBd1IMCQQDQQ7Tyyl2wshggxL+imuAp0lSjqYtFfD/9260voHPNfYX2LI8nWjwtdlKFLmKk0ErsKxd9aOxuRYLycRGbl7HdAkEA26IaSl+JAI6PqpSpQ4Ho4JZ7EjW5fBrLpFc63koDhaOGqgBQYvCD5jWR7U42hoi0vObkW+P+DMAZfmMlNf944wJAPe+ExpeMGVo9drFMVG0+sPFOHoXzVyzGUxabgIh1J+1mg3lo8UkSkGqZy+WpjF4tieKez7r+ZSTi9nrNw7nvOQJAM/hx/sLxeWfqfI92Etuq6HqkQ3ciVthkOPuMusGyX5rjl/g4vimrpJ43vH08vyyfsiDf5AK3mVuUfsNZAicyrg==";
static {
init();
}
public static void init() {
/**
* 生成key
*/
// Map<String, Key> keyMap;
// try {
// keyMap = RSACoder.initKey();
// publicKey = RSACoder.getPublicKey(keyMap);
// privateKey = RSACoder.getPrivateKey(keyMap);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// logger.error("初始化前端js加密秘钥失败:",e);
// }
logger.info("公钥: \n\r" + publicKey);
logger.info("私钥: \n\r" + privateKey);
}
public static byte[] decryptBASE64(String key) {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
public static byte[] decryptBase64AndRSAByPrivateKey(String data)throws Exception{
return decryptByPrivateKey(RSACoder.decryptBASE64(data),privateKey);
}
/**
* 私钥解密
* @param data 要解密的base64编码的数据;
* @param key 私钥的base64编码数据;
* @return
* @throws Exception
*/
public static byte[] decryptAndBase64ByPrivateKey(String data, String key) throws Exception{
return decryptByPrivateKey(RSACoder.decryptBASE64(data),key);
}
/**
* 公钥加密
* 返回base64字符串
* @param data
* @param key
* @return
* @throws Exception
*/
public static String encryptAndBase64ByPublicKey(String data,String key) throws Exception {
return encryptBASE64(encryptByPublicKey(data,key));
}
/**
*
* 用私钥对信息生成数字签名
*
* @param data 加密数据
* @param privateKey 私钥
* @return
* @throws Exception
*/
public static String sign(byte[] data, String privateKey) throws Exception {
// 解密由base64编码的私钥
byte[] keyBytes = decryptBASE64(privateKey);
// 构造PKCS8EncodedKeySpec对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取私钥匙对象
PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 用私钥对信息生成数字签名
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(priKey);
signature.update(data);
return encryptBASE64(signature.sign());
}
/**
* 校验数字签名
*
* @param data 加密数据
* @param publicKey 公钥
* @param sign 数字签名
* @return 校验成功返回true 失败返回false
* @throws Exception
*/
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
// 解密由base64编码的公钥
byte[] keyBytes = decryptBASE64(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(decryptBASE64(sign));
}
/**
* 使用私钥解密
* @param data
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, Key privateKey) throws Exception{
// 对数据解密
Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
return decryptByPrivateKey(data,privateKey);
}
/**
* 解密<br>
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(String data, String key)
throws Exception {
return decryptByPrivateKey(decryptBASE64(data),key);
}
/**
* 解密<br>
* 用公钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 加密<br>
* 用公钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(String data, String key)
throws Exception {
// 对公钥解密
byte[] keyBytes = decryptBASE64(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data.getBytes());
}
/**
* 加密<br>
* 用私钥加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = decryptBASE64(key);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 取得私钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String, Key> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
}
/**
* 取得公钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String, Key> keyMap)
throws Exception {
Key key = keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
}
/**
* 初始化密钥
*
* @return
* @throws NoSuchAlgorithmException
* @throws Exception
*/
public static Map<String, Key> initKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
Map<String, Key> keyMap = new HashMap<String, Key>(2);
keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
return keyMap;
}
}