进行签名的加密

package com.goboosoft.common.pay.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map; import org.apache.commons.codec.binary.Base64; /**
* Description:
*
* @author cy
* @date 2019年02月28日 14:30
* version 1.0
*/
public class RSA { private static final String SIGN_TYPE_RSA = "RSA"; private static final String SIGN_TYPE_RSA2 = "RSA2"; private static final String SIGN_ALGORITHMS = "SHA1WithRSA"; private static final String SIGN_SHA256RSA_ALGORITHMS = "SHA256WithRSA"; private static final int DEFAULT_BUFFER_SIZE = ; /**
* RSA/RSA2 生成签名
*
* @param map 包含 sign_type、privateKey、charset
* @return
* @throws Exception
*/
public static String rsaSign(Map map) throws Exception {
PrivateKey priKey = null;
java.security.Signature signature = null;
String signType = map.get("sign_type").toString();
String privateKey = map.get("privateKey").toString();
String charset = map.get("charset").toString();
String content = getSignContent(map);
map.put("content", content);
System.out.println("请求参数生成的字符串为:" + content);
if (SIGN_TYPE_RSA.equals(signType)) {
priKey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, new ByteArrayInputStream(privateKey.getBytes()));
signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
} else if (SIGN_TYPE_RSA2.equals(signType)) {
priKey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, new ByteArrayInputStream(privateKey.getBytes()));
signature = java.security.Signature.getInstance(SIGN_SHA256RSA_ALGORITHMS);
} else {
throw new Exception("不是支持的签名类型 : : signType=" + signType);
}
signature.initSign(priKey); if (StringUtils.isEmpty(charset)) {
signature.update(content.getBytes());
} else {
signature.update(content.getBytes(charset));
} byte[] signed = signature.sign(); return new String(Base64.encodeBase64(signed)); } /**
* RSA2 生成签名
*
* @param
* @return
* @throws Exception
*/
public static String rsa2Sign(String content,String charset,String privateKey) throws Exception {
PrivateKey priKey = null;
java.security.Signature signature = null; priKey = getPrivateKeyFromPKCS8(SIGN_TYPE_RSA, new ByteArrayInputStream(privateKey.getBytes()));
signature = java.security.Signature.getInstance(SIGN_SHA256RSA_ALGORITHMS);
signature.initSign(priKey);
signature.update(content.getBytes(charset));
byte[] signed = signature.sign();
return new String(Base64.encodeBase64(signed)); } /**
* 验签方法
*
* @param content 参数的合成字符串格式: key1=value1&key2=value2&key3=value3...
* @param sign
* @param publicKey
* @param charset
* @param signType
* @return
*/
public static boolean rsaCheck(Map map, String sign) throws Exception {
java.security.Signature signature = null;
String signType = map.get("sign_type").toString();
String privateKey = map.get("privateKey").toString();
String charset = map.get("charset").toString();
String content = map.get("content").toString();
String publicKey = map.get("publicKey").toString();
System.out.println(">>验证的签名为:" + sign);
System.out.println(">>生成签名的参数为:" + content);
PublicKey pubKey = getPublicKeyFromX509("RSA", new ByteArrayInputStream(publicKey.getBytes()));
if (SIGN_TYPE_RSA.equals(signType)) {
signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
} else if (SIGN_TYPE_RSA2.equals(signType)) {
signature = java.security.Signature.getInstance(SIGN_SHA256RSA_ALGORITHMS);
} else {
throw new Exception("不是支持的签名类型 : signType=" + signType);
}
signature.initVerify(pubKey); if (StringUtils.isEmpty(charset)) {
signature.update(content.getBytes());
} else {
signature.update(content.getBytes(charset));
} return signature.verify(Base64.decodeBase64(sign.getBytes()));
} public static PrivateKey getPrivateKeyFromPKCS8(String algorithm, InputStream ins) throws Exception {
if (ins == null || StringUtils.isEmpty(algorithm)) {
return null;
} KeyFactory keyFactory = KeyFactory.getInstance(algorithm); byte[] encodedKey = readText(ins).getBytes(); encodedKey = Base64.decodeBase64(encodedKey); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
} public static PublicKey getPublicKeyFromX509(String algorithm, InputStream ins) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(algorithm); StringWriter writer = new StringWriter();
io(new InputStreamReader(ins), writer, -); byte[] encodedKey = writer.toString().getBytes(); encodedKey = Base64.decodeBase64(encodedKey); return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
} /**
* 把参数合成成字符串
*
* @param sortedParams
* @return
*/
public static String getSignContent(Map<String, String> sortedParams) {
StringBuffer content = new StringBuffer();
// app_id,method,charset,sign_type,version,bill_type,timestamp,bill_date
String[] sign_param = sortedParams.get("sign_param").split(",");// 生成签名所需的参数
List<String> keys = new ArrayList<String>();
for (int i = ; i < sign_param.length; i++) {
keys.add(sign_param[i]);
}
Collections.sort(keys);
int index = ;
for (int i = ; i < keys.size(); i++) {
String key = keys.get(i);
/*if ("biz_content".equals(key)) {
content.append(
(index == 0 ? "" : "&") + key + "={\"bill_date\":\"" + sortedParams.get("bill_date") + "\",")
.append("\"bill_type\":\"" + sortedParams.get("bill_type") + "\"}");
index++;
} else {*/
String value = sortedParams.get(key);
if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)) {
content.append((index == ? "" : "&") + key + "=" + value);
index++;
}
// }
}
return content.toString();
} private static String readText(InputStream ins) throws IOException {
Reader reader = new InputStreamReader(ins);
StringWriter writer = new StringWriter(); io(reader, writer, -);
return writer.toString();
} private static void io(Reader in, Writer out, int bufferSize) throws IOException {
if (bufferSize == -) {
bufferSize = DEFAULT_BUFFER_SIZE >> ;
} char[] buffer = new char[bufferSize];
int amount; while ((amount = in.read(buffer)) >= ) {
out.write(buffer, , amount);
}
} }

RSA2的更多相关文章

  1. 服务端集成支付宝踩过的坑RSA、RSA2

    坑 在配置蚂蚁开发平台的时候,切记一定要注意选择的加密方式是RSA,还是RSA2.因为这两种方式生成的支付宝公匙是不一样的.RSA2对应的是2048位支付宝公匙.在配置类Config中,要根据加密方式 ...

  2. 【支付宝】"验签出错,sign值与sign_type参数指定的签名类型不一致:sign_type参数值为RSA,您实际用的签名类型可能是RSA2"

    问题定位:从描述就可以看的出来了,你现在sign_type是  RSA类型的,要改成跟你现在用的签名类型一致的类型,也就是 要改为 RSA2 PHP为例 // 新版只支持此种签名方式 商户生成签名字符 ...

  3. Rsa2验签报错【java.security.SignatureException: Signature length not correct】的解决办法

    在进行RSA2进行验签的时候,报了以下错误: java.security.SignatureException: Signature length not correct: got 344 but w ...

  4. 生成RSA2公钥、私钥

    RSA2是一种被使用广泛的非对称加密算法. openssl OpenSSL> genrsa -out app_private_key.pem # 私钥RSA2 OpenSSL> rsa - ...

  5. Rsa2加密报错java.security.spec.InvalidKeySpecException的解决办法

    最近在和支付宝支付做个对接,Java项目中用到了RSA2进行加解密,在加密过程中遇到了错误: java.security.spec.InvalidKeySpecException: java.secu ...

  6. 创 PHP RSA2 签名算法

        什么是RSA2 ? RSA2 是在原来SHA1WithRSA签名算法的基础上,新增了支持SHA256WithRSA的签名算法. 该算法比SHA1WithRSA有更强的安全能力. 为了您的应用安 ...

  7. Delphi支付宝支付【支持SHA1WithRSA(RSA)和SHA256WithRSA(RSA2)签名与验签】

    作者QQ:(648437169) 点击下载➨Delphi支付宝支付             支付宝支付api文档 [Delphi支付宝支付]支持条码支付.扫码支付.交易查询.交易退款.退款查询.交易撤 ...

  8. Delphi RSA签名与验签【支持SHA1WithRSA(RSA1)、SHA256WithRSA(RSA2)和MD5WithRSA签名与验签】

    作者QQ:(648437169) 点击下载➨ RSA签名与验签 [delphi RSA签名与验签]支持3种方式签名与验签(SHA1WithRSA(RSA1).SHA256WithRSA(RSA2)和M ...

  9. 支付宝支付回调方法RSA2验签失败处理方法

    支付宝支付签名方式RSA2生成支付时使用的是支付宝公钥和应用私钥, 而不是应用公钥,支付宝公钥的生成是根据上传应用公钥而变动的, 所以在做回调的时候参数ALIPAY_PUBLIC_KEY也需要传支付宝 ...

随机推荐

  1. 【ZJOI 2008】树的统计

    [题目链接] 点击打开链接 [算法] 树链剖分模板题 [代码] #include<bits/stdc++.h> using namespace std; #define MAXN 3000 ...

  2. sizeof()解析(原)

    (一)基本概念     sizeof操作符以字节形式给出了其操作数的存储大小.操作数可以是一个表达式或括在括号内的类型名.操作数的存储大小由操作数的类型决定. (二)使用方法 1.用于数据类型     ...

  3. bzoj 2083 Intelligence test —— 思路+vector

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2083 先把所有子序列都存下来,总长度应该有限制,所以用 vector 存: 要做到 O(n) ...

  4. iconMoon---小图标小记

    IcoMoon 是一个免费的图标库.可以下载自己需要的图标 三.使用流程.操作演示 进入主页,点击下图所示区域开始: 每个图标你都是可以自己进行标记的(移上去会看到Edit, 点击之),然后—— 注: ...

  5. YARN(MapReduce 2)运行MapReduce的过程-源码分析

    这是我的分析,当然查阅书籍和网络.如有什么不对的,请各位批评指正.以下的类有的并不完全,只列出重要的方法. 如要转载,请注上作者以及出处. 一.源码阅读环境 需要安装jdk1.7.0版本及其以上版本, ...

  6. Codeforces 702B【二分】

    题意: 给一个a数组,输出有多少对相加是等于2^x的.1<=a[i]<=1e9,n<=1e5 思路: a[i]+a[j]=2^x 对于每个a[i],枚举x,然后二分查找a[j]; p ...

  7. sql server编写通用脚本自动统计各表数据量心得

    工作过程中,如果一个数据库的表比较多,手工编写统计脚本就会比较繁琐,于是摸索出自动生成各表统计数据量脚本的通用方法,直接上代码: /* 脚本来源:https://www.cnblogs.com/zha ...

  8. bzoj 4145: [AMPPZ2014]The Prices【状压dp】

    设f[s][i]为已经买了集合s,当前在商店i,转移的话就是枚举新买的物品,两种情况,一种是在原商店买,不用付路费,另一种是从其他商店过来,这种再枚举从那个商店过来是不行的,记一个mn[s]为已经买了 ...

  9. 2019年BAT面试通关宝典:数据结构+JVM+并发编程+分布式...

    前言 金三银四俗称跳槽黄金季,很多同学都想趁着这段时间拿高薪,去更牛逼的公司工作,认识更多大牛,提升自己的职场竞争力. 那怎样才能通过BAT面试官的考核?怎样成为一名Offer收割机? 收割Offer ...

  10. 合作网络(Corporative Network )并查集+路径压缩

    #include <iostream> #include <algorithm> #include <string> using namespace std; + ...