http协议数据交互是明文传送的,因此是非常危险的,信息可能会被截获或者被注入攻击。本文是在不使用https对数据使用RSA算法进行加密的个人笔记。
RSA是一种加密算法,生成公钥和私钥,使用公钥加密的数据可以用私钥解开,因此,公钥是可以公开的,私钥则是不应该公开的不宜在网络上传送。
具体算法如下:
1.创建一个ajax请求,后端响应,并生成一对私钥公钥,私钥后端保存着,公钥传送到前端。
2.将获得的公钥把想要传送的数据进行加密。
3.创建另一个ajax请求传送加密好的数据,后端接收到加密的数据,使用刚刚生成的私钥进行解密。
准备阶段:
创建RSA工具类
工具类出处:https://www.jianshu.com/p/ff8281f034f4
package RSA;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* Created by lake on 17-4-12.
*/
public class RSACoder {
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";
public static byte[] decryptBASE64(String key) {
return Base64.decodeBase64(key);
}
public static String encryptBASE64(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
/**
* 用私钥对信息生成数字签名
*
* @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));
}
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);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 解密
* 用私钥解密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(String data, String key)
throws Exception {
return decryptByPrivateKey(decryptBASE64(data),key);
}
/**
* 解密
* 用公钥解密
*
* @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);
}
/**
* 加密
* 用公钥加密
*
* @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());
}
/**
* 加密
* 用私钥加密
*
* @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 keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return encryptBASE64(key.getEncoded());
}
/**
* 取得公钥
*
* @param keyMap
* @return
* @throws Exception
*/
public static String getPublicKey(Map keyMap)
throws Exception {
Key key = keyMap.get(PUBLIC_KEY);
return encryptBASE64(key.getEncoded());
}
/**
* 初始化密钥
*
* @return
* @throws Exception
*/
public static Map initKey() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
Map keyMap = new HashMap(2);
keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
return keyMap;
}
}
创建ssm框架下的控制层并准备好需要的变量
并在maven导入net.sf.json的jar包。
import java.security.Key;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import RSA.RSACoder;
@Controller
@RequestMapping("/mycontroller")
public class myController {
public String privatekey="";
public String publickey="";
}
创建数据类Postdata
public class Postdata {
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
第一步,设计后端代码
import java.security.Key;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import RSA.RSACoder; //导入RSA工具类
@Controller
@RequestMapping("/mycontroller")
public class myController {
public String privatekey="";
public String publickey="";
@RequestMapping(value="/createkey")
@ResponseBody
public net.sf.json.JSONObject createkey(@RequestBody Postdata postdata){ //使用RSA工具类生成私钥和公钥并返回公钥给前端。
net.sf.json.JSONObject json =new net.sf.json.JSONObject();
try{
if("getpk".equals(postdata.getData()))
{
Map keyMap = RSACoder.initKey(); //生成公钥和私钥
publickey = RSACoder.getPublicKey(keyMap); //获取公钥
privatekey = RSACoder.getPrivateKey(keyMap); //获取私钥
System.err.println("公钥: \n\r" + publickeyuse);
System.err.println("私钥: \n\r" + privatekeyuse);
json.put("pkresult", "success");
json.put("pk", publickey); //返回公钥
}
else
{
json.put("pkresult", "failed");
}
} catch(Exception e){
e.printStackTrace();
json.put("pkresult", "error");
}
return json;
}
@RequestMapping(value="/decode")
@ResponseBody
public net.sf.json.JSONObject decode(@RequestBody Postdata postdata){ //获得加密好的数据并解密
net.sf.json.JSONObject json =new net.sf.json.JSONObject();
try{
System.out.println(postdata.getData()); //解密前的数据
if(!("".equals(privatekey))
{
System.out.println("privatekey:"+privatekey); //私钥
byte[] decodedData = RSACoder.decryptByPrivateKey(postdata.getData(),privatekey); //解密数据
String outputStr = new String(decodedData);
System.out.println(outputStr); //输出解密后的数据
}
json.put("result","success"); //返回成功的信息
System.out.println(json);
} catch(Exception e){
e.printStackTrace();
json.put("result", "error");
System.out.println(json);
}
return json;
}
}
第二步,设计前端代码,创建在jsp里的ajax请求
//引入jQuery包
//引入加密包
输入要加密的数据:
3.运行样例
输入:123456
公钥:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRmOIYVn+oChzyURzWHceevZE0b7LccFlZ2iwq5QRtUk2KsPYODOE4QmeKsqbwd44/cpT25BL5HYfHJCrX6rmwGbWQtR4QYefXnvNXvVraBHHxqb2NuYBwHU8Beadvkb98IPlsXyoEtBo6rZ7Uqg+9/ptkW885cvTOd4p5qL2V8QIDAQAB
私钥:
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJGY4hhWf6gKHPJRHNYdx569kTRvstxwWVnaLCrlBG1STYqw9g4M4ThCZ4qypvB3jj9ylPbkEvkdh8ckKtfqubAZtZC1HhBh59ee81e9WtoEcfGpvY25gHAdTwF5p2+Rv3wg+WxfKgS0GjqtntSqD73+m2Rbzzly9M53inmovZXxAgMBAAECgYBYI88roKGjHowrfUMRs/F2fZf7wGrs2+6bYGJAjWfCroJWpY4vL0jggAKiikhZZmbsrfbUB3oc6O2bdp+hGm3R5s5mUqHiPgtR+k4yEj86A3MHudVlA+rrn1mHBzuZ19N/zslwhx70nLWl/4pT0UIE2La2v2aA+RLc90P0nX9LSQJBAPa1gqTKoF3i8R4J5poLW1npySxcNRMdBlditT6UkP99gd8N64NbU8WYJgce2XIrHXCV7/Naf95dF2fto23EMCsCQQCXFJEfQYGyPepTbtPSKtRaJtUnzH4UU/SreRCkhJHrE01JncRZXX0X/yCUe3FeLwz3aGb1yQ7PF8XcxfDK8ehTAkA57zn0tNif85Enuq96cTxMiwgA8M5N5Lz+fGGPhpfeR3zeAojR2fp8JlSXy3jIxLMvIyasAQ6SC05Zy4ZbWnztAkEAilULl+nb/j9Q2joE+0+6Bh2+WGWWH7jLs2Hzih/Ul8ChqMErMoQ2cQ1qYGoy4IEGR1axx2TkCV0ED2SyWLBs/wJBAPKZb3s36Ovx3xBdH4xY+QGvfBALP5rTNrU2DDrLdgsCR7OfBm3k+C7AsJmeXoO9Z1H4bY92ChR/H0w9vj6S4Jk=
公钥加密后的数据:
TX436W71O/Vuj23rwFTJsKO81clt1OjRV+0vzGBkG8PixScRvjhy6Q3QxtYeB0NJF29lgB1bsqQrEdtc7RoOl5ybFQ6KQ23uD4NKGjHe6KzOKU7m0W1b5KYIaxYqcv02ovi1lrQAI/IMWP76qn+fOH5xAve5FvGPmt1e7BROmPk=
解密后:123456