进行签名的加密

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. BZOJ_3963_[WF2011]MachineWorks_斜率优化+CDQ分治

    BZOJ_3963_[WF2011]MachineWorks_斜率优化+CDQ分治 Description 你是任意性复杂机器公司(Arbitrarily Complex Machines, ACM) ...

  2. WC2017游记

    Day0 到杭州之后出了点锅换了辆车,等了好久才开= =到宿舍发现路由器就在房门口,稳啊,过了一会儿就连不上了= =而且只有门口那个连不上,可以连上楼下的= =之后干了啥也忘了…… Day1 上午直接 ...

  3. 「网络流24题」「LuoguP4014」 分配问题

    Description 有 n 件工作要分配给 n 个人做.第 i 个人做第 j 件工作产生的效益为 cij.试设计一个将 n 件工作分配给 n 个人做的分配方案,使产生的总效益最大. Input 文 ...

  4. Educational Codeforces Round 23

    A题 分析:注意两个点之间的倍数差,若为偶数则为YES,否则为NO #include "iostream" #include "cstdio" #include ...

  5. [NOIP 2018 Day1] 简要题解

    [题目链接] 铺设道路 : https://www.luogu.org/problemnew/show/P5019 货币系统 : https://www.luogu.org/problemnew/sh ...

  6. .NETFramework:Stream

    ylbtech-.NETFramework:Stream 1.返回顶部 1. #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutral, Publi ...

  7. 【旧文章搬运】Windows内核常见数据结构(线程相关)

    原文发表于百度空间,2008-7-24========================================================================== 线程是进程的 ...

  8. wcf中事务的操作

    using System; using System.ServiceModel; namespace Larryle.Wcf.ServiceContract.Transaction { [Servic ...

  9. 洛谷 - P1361 - 小M的作物 - 最小割 - 最大权闭合子图

    第一次做最小割,不是很理解. https://www.luogu.org/problemnew/show/P1361 要把东西分进两类里,好像可以应用最小割的模板,其中一类A作为源点,另一类B作为汇点 ...

  10. Mybatis 未设置主键映射报错;Cause: java.sql.SQLSyntaxErrorException: Unknown column 'system_id' in 'field list'

    使用MyBatis的时候,主键的字段建议绑定在Bean的属性上面, import javax.persistence.*; public class User { @Id @Column(name = ...