使用非对称算法RSA实现加解密和使用签名算法SHA1WithRSA、MD5withRSA生成签名以及验签
不啰嗦,直接上源码
package com.hudai.platform.manager.util; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
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.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
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.apache.tomcat.util.http.fileupload.IOUtils;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* @author WanHongLei
* @version 创建时间:2019年2月13日 上午10:27:06 类说明
*/
public class RSAUtils {
/**
* 字符串编码
*/
public static final String CHARSET = "UTF-8";
/**
* 加密算法RSA
*/
public static final String RSA_ALGORITHM = "RSA";
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";// SHA1WithRSA MD5withRSA private static final Logger logger = LoggerFactory.getLogger(RSAUtils.class); /**
* 创建公钥私钥
*
* @param keySize
* 1024 2048
* @return
*/
public static Map<String, String> createKeys(int keySize) {
// 为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try {
kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
} // 初始化KeyPairGenerator对象,密钥长度
kpg.initialize(keySize);
// 生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
// 得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
// 得到私钥
Key privateKey = keyPair.getPrivate();
String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded()); Map<String, String> keyPairMap = new HashMap<String, String>();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKeyOfPKCS8", privateKeyStr);
keyPairMap.put("privateKeyOfPKCS1", getPrivateKeyOfPKCS1(privateKeyStr)); return keyPairMap;
} /**
* 得到公钥
*
* @param publicKey
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
// 通过X509编码的Key指令获得公钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
} /**
* 得到私钥pkcs8
*
* @param privateKey
* 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// 通过PKCS#8编码的Key指令获得私钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
} public static String getPrivateKeyOfPKCS1(String privateKey){
try {
byte[] privBytes = Base64.decodeBase64(privateKey); PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(privBytes);
ASN1Encodable encodable = pkInfo.parsePrivateKey();
ASN1Primitive primitive = encodable.toASN1Primitive();
byte[] privateKeyPKCS1 = primitive.getEncoded(); return pkcs1ToPem(privateKeyPKCS1,false);
} catch (IOException e) {
logger.error("PKCS8ToPKCS1 error", e);
return null;
} catch (Exception e) {
logger.error("PKCS8ToPKCS1 error", e);
return null;
}
} public static String pkcs1ToPem(byte[] pcks1KeyBytes,boolean isPublic) throws Exception{
String type;
if(isPublic){
type = "RSA PUBLIC KEY";
}else{
type = "RSA PRIVATE KEY";
} PemObject pemObject = new PemObject(type, pcks1KeyBytes);
StringWriter stringWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(stringWriter);
pemWriter.writeObject(pemObject);
pemWriter.close();
String pemString = stringWriter.toString(); return pemString;
} /**
* 公钥加密
*
* @param data
* @param publicKey
* @return
*/
public static String publicEncrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
publicKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
} /**
* 私钥解密
*
* @param data
* @param privateKey
* @return
*/ public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data),
privateKey.getModulus().bitLength()), CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
} /**
* 私钥加密
*
* @param data
* @param privateKey
* @return
*/ public static String privateEncrypt(String data, RSAPrivateKey privateKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET),
privateKey.getModulus().bitLength()));
} catch (Exception e) {
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
} /**
* 公钥解密
*
* @param data
* @param publicKey
* @return
*/ public static String publicDecrypt(String data, RSAPublicKey publicKey) {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data),
publicKey.getModulus().bitLength()), CHARSET);
} catch (Exception e) {
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
} /**
* 分段处理
*
* @param cipher
* @param opmode
* @param datas
* @param keySize
* @return
*/
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize) {
int maxBlock = 0;
if (opmode == Cipher.DECRYPT_MODE) {
maxBlock = keySize / 8;
} else {
maxBlock = keySize / 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;
} /**
* RSA签名
*
* @param content
* 待签名数据
* @param privateKey
* 商户私钥
* @param encode
* 字符集编码
* @return 签名值
*/
public static String sign(String content, String privateKey, String encode) {
try {
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)); KeyFactory keyf = KeyFactory.getInstance(RSA_ALGORITHM);
PrivateKey priKey = keyf.generatePrivate(priPKCS8); java.security.Signature signature = java.security.Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(priKey);
signature.update(content.getBytes(encode)); byte[] signed = signature.sign(); return Base64.encodeBase64URLSafeString(signed);
} catch (Exception e) {
throw new RuntimeException("签名发生异常", e);
}
} /**
* RSA验签名检查
*
* @param content 待签名数据
* @param sign 签名值
* @param publicKey 分配给开发商公钥
* @param encode 字符集编码
* @return 布尔值
*/
public static boolean verify(String content, String sign, String publicKey, String encode) {
try {
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
byte[] encodedKey = Base64.decodeBase64(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); java.security.Signature signature = java.security.Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(pubKey);
signature.update(content.getBytes(encode)); boolean bverify = signature.verify(Base64.decodeBase64(sign));
return bverify; } catch (Exception e) {
e.printStackTrace();
} return false;
} public static void main(String[] args) throws UnsupportedEncodingException, Exception {
Map<String, String> keyMap = createKeys(2048);
String publicKey = keyMap.get("publicKey");
String privateKeyOfPKCS8 = keyMap.get("privateKeyOfPKCS8");
String privateKeyOfPKCS1 = keyMap.get("privateKeyOfPKCS1"); System.out.println("publicKey:\n" + publicKey);
System.out.println("privateKeyOfPKCS8:\n" + privateKeyOfPKCS8);
System.out.println("privateKeyOfPKCS1:\n" + privateKeyOfPKCS1); String src = "app_id=35456878542&biz_data={\"order_no\":\"201811307810149579\",\"order_status\":100,\"update_time\":1543566391}&format=json&method=api.v2.order.orderfeedback&sign_type=RSA×tamp=1543566391&version=1.0"; String sign = sign(src, privateKeyOfPKCS8, CHARSET);
System.out.println("sign:\n" + sign); boolean verify = verify(src, sign, publicKey, CHARSET);
System.out.println("verify:" + verify); String privateEncrypt = privateEncrypt(src, getPrivateKey(privateKeyOfPKCS8));
System.out.println("privateEncrypt:\n" + privateEncrypt); String publicDecrypt = publicDecrypt(privateEncrypt, getPublicKey(publicKey));
System.out.println("publicDecrypt:\n" + publicDecrypt); String publicEncrypt = publicEncrypt(src, getPublicKey(publicKey));
System.out.println("publicEncrypt:\n" + publicEncrypt); String privateDecrypt = privateDecrypt(publicEncrypt, getPrivateKey(privateKeyOfPKCS8));
System.out.println("privateDecrypt:\n" + privateDecrypt); }
}
使用非对称算法RSA实现加解密和使用签名算法SHA1WithRSA、MD5withRSA生成签名以及验签的更多相关文章
- erlang的RSA签名与验签
1.RSA介绍 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对 其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥,即公钥,而 ...
- JAVA的非对称加密算法RSA——加密和解密
原文转载至:https://www.cnblogs.com/OnlyCT/p/6586856.html 第一部分:RSA算法原理与加密解密 一.RSA加密过程简述 A和B进行加密通信时,B首先要生成一 ...
- RSA,AES加解密算法的实现
目录 Python实现RSA公钥加密算法 RSA公钥加密算法原理 RSA算法的Python实现 AES加解密算法实现 AES加解密算法原理 AES加解密算法Python实现 参考文献 Python实现 ...
- 前后端java+vue 实现rsa 加解密与摘要签名算法
RSA 加密.解密.签名.验签.摘要,前后端java+vue联调测试通过 直接上代码 // 注意:加密密文与签名都是唯一的,不会变化.// 注意:vue 端密钥都要带pem格式.java 不要带pem ...
- .NET RSA解密、签名、验签
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Sec ...
- RSA后台签名前台验签的应用(前台采用jsrsasign库)
写在前面 安全测试需要, 为防止后台响应数据返给前台过程中被篡改前台再拿被篡改后的数据进行接下来的操作影响正常业务, 决定采用RSA对响应数据进行签名和验签, 于是有了这篇<RSA后台签名前台验 ...
- 几个例子理解对称加密与非对称加密、公钥与私钥、签名与验签、数字证书、HTTPS加密方式
# 原创,转载请留言联系 为什么会出现这么多加密啊,公钥私钥啊,签名啊这些东西呢?说到底还是保证双方通信的安全性与完整性.例如小明发一封表白邮件给小红,他总不希望给别人看见吧.而各种各样的技术就是为了 ...
- Delphi支付宝支付【支持SHA1WithRSA(RSA)和SHA256WithRSA(RSA2)签名与验签】
作者QQ:(648437169) 点击下载➨Delphi支付宝支付 支付宝支付api文档 [Delphi支付宝支付]支持条码支付.扫码支付.交易查询.交易退款.退款查询.交易撤 ...
- Delphi RSA签名与验签【支持SHA1WithRSA(RSA1)、SHA256WithRSA(RSA2)和MD5WithRSA签名与验签】
作者QQ:(648437169) 点击下载➨ RSA签名与验签 [delphi RSA签名与验签]支持3种方式签名与验签(SHA1WithRSA(RSA1).SHA256WithRSA(RSA2)和M ...
随机推荐
- "mysql"."innodb_table_stats" not found 故障解决
故障描述 "mysql"."innodb_table_stats" 表不存在 "mysql"."innodb_index_stat ...
- 与SVN相关的程序的调试问题【转】
解决eclipse中出现Resource is out of sync with the file system问题. 分析:有时候因为时间紧迫的原因,所以就没去管它,今天再次遇到它,实在看着不爽,所 ...
- JZOJ 5455. 【NOIP2017提高A组冲刺11.6】拆网线
455. [NOIP2017提高A组冲刺11.6]拆网线 (File IO): input:tree.in output:tree.out Time Limits: 1000 ms Memory L ...
- Java课堂作业详解
今天的Java课堂留下了一个作业:使用Eclipse编写一个程序,使输入的两个数进行加和,并且输出他们的和.对于这个题目,我们首先可以把它分解成为三个不同的小步骤 第一步就是输入这两个数,因为我们无需 ...
- git之简单入门及操作~
看了bili的教程,https://www.bilibili.com/video/av23853294?from=search&seid=3300012850779227291 特此整理下. ...
- C语言中float如何存储?(转载)
float 内存如何存储的 类型 存储位数 总位数 偏移值(offset) 数符(S) 阶码(E) 尾数(M) 短实数(float) 1 8 23 32 127 长实数(double) 1 11 52 ...
- Codeforces Round #456 (Div. 2) B. New Year's Eve
传送门:http://codeforces.com/contest/912/problem/B B. New Year's Eve time limit per test1 second memory ...
- Android引导页过多导致OOM内存泄漏
摘要:前几天推广我们APP的时候,有些手机加载引导页的时候会闪退或崩溃,在Bugly显示是OOM异常. 然后Bugly上面显示的解决方案是: 该异常表示未能成功分配字节内存,通常是因为内存不足导 ...
- 在MAC下使用Robotframework+Selenium2【第一枪】robotframework安装步骤
最近使用苹果的MAC Pro本本,感受着苹果系统的新鲜,确实让我手忙脚乱一阵,毕竟使用windows系统太长时间了,刚开始用MAC Pro确实感觉别扭,用了一段,发现MAC系统还不错,好了,转入正题. ...
- 「微信小程序免费辅导教程」25,基本内容组件text的使用及个人帐号允许的服务类目