目录
一、工具类demo1
二、工具类demo2
三、工具类demo3
package com.ykx.transfer.contorller;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
public class RSADemo {
public static final String ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM="MD5withRSA";
private static String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDazJE8JgkL4hXA5pJwuBu9skcCrA6cQBGws3G0rmIp/K51sqGVCradW8ait03/5/sUKoHDF2tu89dcuhTYBxgidMDmyBlAznU8WRt9FrgCtlhq4evcq+ZeUAPyXtvBMU18gNJq0EctJbszjTBkGvHuEuJes5lPs3nT+eHG1edwfQIDAQAB";
private static String privatekey = ;
public void Test() throws Exception {}
public static PublicKey getPublicKey(String key) throws Exception {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
Base64.decodeBase64(key));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
public static PrivateKey getPrivateKey(String key)
throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec privatekeySpec = new PKCS8EncodedKeySpec(
Base64.decodeBase64(key));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(privatekeySpec);
}
public static byte[] encrypt(String text, PublicKey key) {
byte[] cipherText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
/**
* RSA算法使用公钥校验数字签名
*
* @param data 参与签名的明文字符串
* @param key RSA公钥字符串
* @param sign RSA签名得到的经过Base64编码的字符串
* @return true--验签通过,false--验签未通过
*/
public static boolean buildRSAverifyByPublicKey(String data, String key, String sign) {
try {
//通过X509编码的Key指令获得公钥对象
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Signature signature = Signature.getInstance("MD5withRSA");
signature.initVerify(publicKey);
signature.update(data.getBytes("utf-8"));
return signature.verify(java.util.Base64.getDecoder().decode(sign));
} catch (Exception e) {
throw new RuntimeException("验签字符串[" + data + "]时遇到异常", e);
}
}
public static void main(String[] args) throws Exception{
HttpPost post = new HttpPost("http://127.0.0.1:8081/transfer/placeorder");
//获取securityKey
PublicKey publicKey = getPublicKey(publickey);
PrivateKey privateKey = getPrivateKey(privatekey);
//拼装查询条件xxx=xxx&yyy=yyy&zzz=zzz
String param = "startStationCode=8001qj&pathPoint=綦江";
//签名
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initSign(privateKey);
sig.update(param.getBytes());
byte[] sign = sig.sign();
String signature = Base64.encodeBase64String(sign);
//加密
byte[] encrypt = encrypt(param, publicKey);
String encodeBase64String = Base64.encodeBase64String(encrypt);
//拼装json格式请求参数
JSONObject json = new JSONObject();
json.put("data", encodeBase64String);
json.put("signature",signature);
StringEntity entity = new StringEntity(json.toString(),"UTF-8");
//设置content编码及类型
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
//模拟http post请求发送信息
HttpClient client = HttpClients.createDefault();
HttpResponse response = client.execute(post);
System.out.println(response.getStatusLine().getStatusCode());
if(response.getStatusLine().getStatusCode() ==200){
HttpEntity entity_r = response.getEntity();
String personal = EntityUtils.toString(entity_r);
System.out.println(personal);
}
}
}
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
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.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import com.ykx.orderCenter.dubbo.security.StreamUtil;
import sun.misc.BASE64Decoder;
/**
* 类名称:util
* 类描述:
* 创建人:Administrator
* 创建时间:2019年7月23日 下午4:22:13
* 修改人:Administrator
* 修改时间:2019年7月23日 下午4:22:13
* 修改备注:
* @version
*/
public class RSASignUtil {
/** 签名算法 */
private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA";
/** 签名类型*/
private static final String SIGN_TYPE_RSA = "RSA";
/** 算法长度,默认2048*/
public static final int KEY_SIZE = 2048;
/**
* 初始化RSA算法密钥对
*
* @param keysize RSA1024已经不安全了,建议2048
* @return 经过Base64编码后的公私钥Map, 键名分别为publicKey和privateKey
*/
public static Map initRSAKey(int keysize) {
if (keysize != KEY_SIZE) {
throw new IllegalArgumentException("RSA1024已经不安全了,请使用" + KEY_SIZE + "初始化RSA密钥对");
}
//为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance(SIGN_TYPE_RSA);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm-->[" + SIGN_TYPE_RSA + "]");
}
//初始化KeyPairGenerator对象,不要被initialize()源码表面上欺骗,其实这里声明的size是生效的
kpg.initialize(KEY_SIZE);
//生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
//得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = java.util.Base64.getEncoder().encodeToString(publicKey.getEncoded());
//得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = java.util.Base64.getEncoder().encodeToString(privateKey.getEncoded());
Map keyPairMap = new HashMap();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
/**
*
* @Description: 字符串转公钥方法1
* @param:@param key
* @param:@return
* @param:@throws Exception
* @return:PublicKey
* @throws:
*
* @version: v1.0.0
* @author: Administrator
* @date: 2019年7月24日 上午11:06:36
*/
public static PublicKey getPublicKeyFromX509(String key) throws Exception {
InputStream ins=new ByteArrayInputStream(key.getBytes());
KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE_RSA);
StringWriter writer = new StringWriter();
StreamUtil.io(new InputStreamReader(ins), writer);
byte[] encodedKey = writer.toString().getBytes();
encodedKey = Base64.decodeBase64(encodedKey);
return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
}
/**
*
* @Description: 字符串转公钥方法2
* @param:@param key
* @param:@return
* @param:@throws Exception
* @return:PublicKey
* @throws:
*
* @version: v1.0.0
* @author: Administrator
* @date: 2019年7月24日 上午11:06:36
*/
public static PublicKey getPublicKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE_RSA);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
}
/**
*
* @Description: 字符串转私钥方法1
* @param:@param key
* @param:@return
* @param:@throws Exception
* @return:PrivateKey
* @throws:
*
* @version: v1.0.0
* @author: Administrator
* @date: 2019年7月24日 上午11:06:39
*/
public static PrivateKey getPrivateKey(String key) throws Exception {
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
// 通过PKCS#8编码的Key指令获得私钥对象
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE_RSA);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
return privateKey;
}
/**
*
* @Description: TODO字符串转私钥方法2
* @param:@param key
* @param:@return
* @param:@throws Exception
* @return:PrivateKey
* @throws:
* @version: v1.0.0
* @author: Administrator
* @date: 2019年11月12日 下午4:56:50
*/
public static PrivateKey getPrivateKeyFromPKCS8(String key) throws Exception {
InputStream ins=new ByteArrayInputStream(key.getBytes());
if (ins == null || StringUtils.isEmpty(SIGN_TYPE_RSA)) {
return null;
}
KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE_RSA);
byte[] encodedKey = StreamUtil.readText(ins).getBytes();
encodedKey = Base64.decodeBase64(encodedKey);
return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
}
/**
*
* @Description: 处理待加密数据处理为URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串stringA。
* 特别注意以下重要规则:
* ◆ 参数名ASCII码从小到大排序(字典序);
* ◆ 如果参数的值为空不参与签名;
* ◆ 参数名区分大小写;
* @param:@param params
* @param:@return
* @return:String
* @throws:
* @version: v1.0.0
* @author: Administrator
* @date: 2019年11月12日 下午2:09:36
*/
public static String getSignCheckContent(Map params) {
if (params == null) {
return null;
}
StringBuffer content = new StringBuffer();
List keys = new ArrayList(params.keySet());
Collections.sort(keys);
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
content.append((i == 0 ? "" : "&") + key + "=" + value);
}
return content.toString();
}
/**
* 私钥签名
*
* @param data 待签名的明文字符串
* @param privateKey RSA私钥字符串
* @return RSA私钥签名后的经过Base64编码的字符串
* @throws Exception
*/
@SuppressWarnings("unused")
private static String sign(String data, String privateKey,String charset){
try {
PrivateKey priKey =getPrivateKey(privateKey);
Signature signature = Signature.getInstance(SIGN_SHA256RSA_ALGORITHMS);
signature.initSign(priKey);
if (StringUtils.isEmpty(charset)) {
signature.update(data.getBytes());
} else {
signature.update(data.getBytes(charset));
}
return new String(Base64.encodeBase64(signature.sign()));
// return Base64.getEncoder().encodeToString(signature.sign());
} catch (Exception e) {
throw new RuntimeException("签名字符串[" + data + " ]时遇到异常", e);
}
}
/**
* 公钥 验签
* @param srcData 原始字符串
* @param publicKey 公钥
* @param sign 签名
* @return 是否验签通过
*/
@SuppressWarnings("unused")
private static boolean verify(String data, String publicKey, String sign,String charset){
try {
PublicKey pubKey = getPublicKey(publicKey);
Signature signature = Signature.getInstance(SIGN_SHA256RSA_ALGORITHMS);
signature.initVerify(pubKey);
if (StringUtils.isEmpty(charset)) {
signature.update(data.getBytes());
} else {
signature.update(data.getBytes(charset));
}
return signature.verify(Base64.decodeBase64(sign.getBytes()));
} catch (Exception e) {
throw new RuntimeException("验签字符串[" + data + " ]时遇到异常", e);
}
}
/**
*
* @Description: 公钥验签
* @param:@param params
* @param:@param publicKey
* @param:@param charset
* @param:@param sign
* @param:@return
* @return:boolean
* @throws:
* @version: v1.0.0
* @author: Administrator
* @date: 2019年11月12日 下午2:12:38
*/
public static boolean rsa256Check(Map params, String publicKey, String charset,String sign) {
String content = getSignCheckContent(params);
return verify(content, sign, publicKey, charset);
}
}
import java.io.ByteArrayOutputStream;
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.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import org.apache.commons.io.IOUtils;
/**
* 加解密工具类
*/
public final class EncryptDecryptUtil {
public static final String CHARSET = "UTF-8";
//密钥算法
public static final String ALGORITHM_RSA = "RSA";
//RSA 签名算法
public static final String ALGORITHM_RSA_SIGN = "SHA256WithRSA";
public static final int ALGORITHM_RSA_PRIVATE_KEY_LENGTH = 2048;
private EncryptDecryptUtil() {
}
/**
* 初始化RSA算法密钥对
*
* @param keysize RSA1024已经不安全了,建议2048
* @return 经过Base64编码后的公私钥Map, 键名分别为publicKey和privateKey
*/
public static Map initRSAKey(int keysize) {
if (keysize != ALGORITHM_RSA_PRIVATE_KEY_LENGTH) {
throw new IllegalArgumentException("RSA1024已经不安全了,请使用" + ALGORITHM_RSA_PRIVATE_KEY_LENGTH + "初始化RSA密钥对");
}
//为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance(ALGORITHM_RSA);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm-->[" + ALGORITHM_RSA + "]");
}
//初始化KeyPairGenerator对象,不要被initialize()源码表面上欺骗,其实这里声明的size是生效的
kpg.initialize(ALGORITHM_RSA_PRIVATE_KEY_LENGTH);
//生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
//得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
//得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
Map keyPairMap = new HashMap();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
/**
* RSA算法公钥加密数据
*
* @param data 待加密的明文字符串
* @param key RSA公钥字符串
* @return RSA公钥加密后的经过Base64编码的密文字符串
*/
public static String buildRSAEncryptByPublicKey(String data, String key) {
try {
//通过X509编码的Key指令获得公钥对象
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.getEncoder().encodeToString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET)));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* RSA算法公钥解密数据
*
* @param data 待解密的经过Base64编码的密文字符串
* @param key RSA公钥字符串
* @return RSA公钥解密后的明文字符串
*/
public static String buildRSADecryptByPublicKey(String data, String key) {
try {
//通过X509编码的Key指令获得公钥对象
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data)), CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* RSA算法私钥加密数据
*
* @param data 待加密的明文字符串
* @param key RSA私钥字符串
* @return RSA私钥加密后的经过Base64编码的密文字符串
*/
public static String buildRSAEncryptByPrivateKey(String data, String key) {
try {
//通过PKCS#8编码的Key指令获得私钥对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.getEncoder().encodeToString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET)));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* RSA算法私钥解密数据
* @param data 待解密的经过Base64编码的密文字符串
* @param key RSA私钥字符串
* @return RSA私钥解密后的明文字符串
*/
public static String buildRSADecryptByPrivateKey(String data, String key) {
try {
//通过PKCS#8编码的Key指令获得私钥对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.getDecoder().decode(data)), CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* RSA算法使用私钥对数据生成数字签名
*
* @param data 待签名的明文字符串
* @param key RSA私钥字符串
* @return RSA私钥签名后的经过Base64编码的字符串
*/
public static String buildRSASignByPrivateKey(String data, String key) {
try {
//通过PKCS#8编码的Key指令获得私钥对象
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance(ALGORITHM_RSA_SIGN);
signature.initSign(privateKey);
signature.update(data.getBytes(CHARSET));
return Base64.getEncoder().encodeToString(signature.sign());
} catch (Exception e) {
throw new RuntimeException("签名字符串[" + data + "]时遇到异常", e);
}
}
/**
* RSA算法使用公钥校验数字签名
*
* @param data 参与签名的明文字符串
* @param key RSA公钥字符串
* @param sign RSA签名得到的经过Base64编码的字符串
* @return true--验签通过,false--验签未通过
*/
public static boolean buildRSAverifyByPublicKey(String data, String key, String sign) {
try {
//通过X509编码的Key指令获得公钥对象
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Signature signature = Signature.getInstance(ALGORITHM_RSA_SIGN);
signature.initVerify(publicKey);
signature.update(data.getBytes(CHARSET));
return signature.verify(Base64.getDecoder().decode(sign));
} catch (Exception e) {
throw new RuntimeException("验签字符串[" + data + "]时遇到异常", e);
}
}
/**
* RSA算法分段加解密数据
*
* @param cipher 初始化了加解密工作模式后的javax.crypto.Cipher对象
* @param opmode 加解密模式,值为javax.crypto.Cipher.ENCRYPT_MODE/DECRYPT_MODE
* @return 加密或解密后得到的数据的字节数组
*/
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = ALGORITHM_RSA_PRIVATE_KEY_LENGTH / 8;
} else {
maxBlock = ALGORITHM_RSA_PRIVATE_KEY_LENGTH / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try {
while (datas.length > offSet) {
if (datas.length - offSet > maxBlock) {
buff = cipher.doFinal(datas, offSet, maxBlock);
} else {
buff = cipher.doFinal(datas, offSet, datas.length - offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
} catch (Exception e) {
throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
public static void main(String[] args) {
String privateKey="秘钥";
String publicKey="公钥";
System.out.println("签名:"+buildRSASignByPrivateKey("ABCabc123测试", privateKey));
System.out.println("校验:"+buildRSAverifyByPublicKey("ABCabc123测试",publicKey,buildRSASignByPrivateKey("ABCabc123测试", privateKey)));
}
}