RSA 签名 / 验签工具

本贴最后更新于 1942 天前,其中的信息可能已经渤澥桑田

依赖 jar 包下载

zmxysdkjava20170605134301.jar
zmxysdkjava20170605134301source.jar

代码如下

   import com.antgroup.zmxy.openplatform.api.ZhimaApiException;
   import com.antgroup.zmxy.openplatform.api.internal.util.Base64Util;
   import com.antgroup.zmxy.openplatform.api.internal.util.CoderUtil;
   import com.antgroup.zmxy.openplatform.api.internal.util.EncryptionModeEnum;
   import com.antgroup.zmxy.openplatform.api.internal.util.SignTypeEnum;
   import com.antgroup.zmxy.openplatform.api.internal.util.json.ExceptionErrorListener;
   import com.antgroup.zmxy.openplatform.api.internal.util.json.JSONValidatingReader;
	import java.io.ByteArrayOutputStream;
	import java.security.Key;
	import java.security.KeyFactory;
	import java.security.PrivateKey;
	import java.security.PublicKey;
	import java.security.Signature;
	import java.security.spec.PKCS8EncodedKeySpec;
	import java.security.spec.RSAPrivateKeySpec;
	import java.security.spec.RSAPublicKeySpec;
	import java.security.spec.X509EncodedKeySpec;
	import java.util.Iterator;
	import java.util.Map;
	import javax.crypto.Cipher;

   import org.apache.log4j.Logger;

	public class PKRSACoderUtil extends CoderUtil{
    
  	protected static Logger log = Logger.getLogger(PKRSACoderUtil.class);
  
  	public static final String KEY_ALGORTHM = "RSA";
  	public static final String SPECIFIC_KEY_ALGORITHM = "RSA/ECB/PKCS1Padding";
  	public static final String SIGNATURE_ALGORITHM = "SHA256WITHRSA";
  	public static String encrypt(String paramsString, String charset, String publicKey)
    throws Exception
  	{
    	byte[] encryptedResult = encryptByPublicKey(paramsString.getBytes(charset), publicKey, null);
    	return Base64Util.byteArrayToBase64(encryptedResult);
  	}
 	public static String encrypt(String paramsString, String charset, String publicKey, EncryptionModeEnum encryptionType)
    throws Exception
  	{
    	byte[] encryptedResult = encryptByPublicKey(paramsString.getBytes(charset), publicKey, encryptionType);


    	return Base64Util.byteArrayToBase64(encryptedResult);
  	}


  	public static String sign(String data, String charset, String privateKey)
    throws Exception
  	{
    	byte[] dataInBytes = data.getBytes(charset);
   	 String signParams = sign(dataInBytes, privateKey);
   	 return signParams;
  	}



  	public static String sign(SignTypeEnum signType, String data, String charset, String privateKey)
    throws Exception
  	{
   	 byte[] dataInBytes = data.getBytes(charset);
   	 String signParams = sign(signType, dataInBytes, privateKey);
   	 return signParams;
  	}

  	public static String decrypt(String data, String key, String charset)
    throws Exception
  	{
    	byte[] byte64 = Base64Util.base64ToByteArray(data);
    	byte[] encryptedBytes = decryptByPrivateKey(byte64, key, null);
   	 return new String(encryptedBytes, charset);
  	}


 	 public static String decrypt(String data, String key, String charset, EncryptionModeEnum encryptionType)
    throws Exception
  	{
   	 byte[] byte64 = Base64Util.base64ToByteArray(data);
   	 byte[] encryptedBytes = decryptByPrivateKey(byte64, key, encryptionType);
   	 return new String(encryptedBytes, charset);
 	 }


 	 public static byte[] decryptByPrivateKey(byte[] data, String key, EncryptionModeEnum encryptionType)
    throws Exception
 	 {
   	 byte[] decryptedData = null;


    	byte[] keyBytes = decryptBASE64(key);

    	PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

   	 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(2, privateKey);

    	int maxDecryptBlockSize;
    	if (encryptionType != null)
     	 maxDecryptBlockSize = getMaxDecryptBlockSizeByEncryptionType(encryptionType);
    	else {
     	 maxDecryptBlockSize = getMaxDecryptBlockSize(keyFactory, privateKey);
    	}

    	ByteArrayOutputStream bout = new ByteArrayOutputStream();
   	 try {
    	  int dataLength = data.length;
    	  for (int i = 0; i < dataLength; i += maxDecryptBlockSize) {
       	 int decryptLength = (dataLength - i < maxDecryptBlockSize) ? dataLength - i : maxDecryptBlockSize;

       	 byte[] doFinal = cipher.doFinal(data, i, decryptLength);
        	bout.write(doFinal);
     	 }
     	 decryptedData = bout.toByteArray();
   	 } finally {
     	 if (bout != null) {
      	  bout.close();
     	 }
   	 }

    	return decryptedData;
  	}


  	public static byte[] encryptByPublicKey(byte[] data, String key, EncryptionModeEnum encryptionType)
    throws Exception
 	 {
    	byte[] encryptedData = null;


    	byte[] keyBytes = decryptBASE64(key);

    	X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    	KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    	Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);


   	 Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    	cipher.init(1, publicKey);

   	 int maxEncryptBlockSize;
    	if (encryptionType != null)
     	 maxEncryptBlockSize = getMaxEncryptBlockSizeByEncryptionType(encryptionType);
    	else {
     	 maxEncryptBlockSize = getMaxEncryptBlockSize(keyFactory, publicKey);
   	 }

    	ByteArrayOutputStream bout = new ByteArrayOutputStream();
    	try {
     	 int dataLength = data.length;
      	for (int i = 0; i < data.length; i += maxEncryptBlockSize) {
        	int encryptLength = (dataLength - i < maxEncryptBlockSize) ? dataLength - i : maxEncryptBlockSize;

        	byte[] doFinal = cipher.doFinal(data, i, encryptLength);
        	bout.write(doFinal);
     	 }
      	encryptedData = bout.toByteArray();
   	 } finally {
     	 if (bout != null) {
       	 bout.close();
      	}
   	 }
    	return encryptedData;
 	 }

  	public static String sign(byte[] data, String privateKey)
    throws Exception
 	 {
   	 return sign(SignTypeEnum.SHA1WITHRSA, data, privateKey);
 	 }


 	 public static String sign(SignTypeEnum signType, byte[] data, String privateKey)
    throws Exception
  	{
   	 byte[] keyBytes = decryptBASE64(privateKey);

    	PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);

    	KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    	PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);


    	Signature signature = Signature.getInstance(signType.getDesc());
    	signature.initSign(privateKey2);
    	signature.update(data);

   	 return encryptBASE64(signature.sign());
 	 }


  public static boolean verify(byte[] data, String publicKey, String sign)
    throws Exception
  {
    return verify(SignTypeEnum.SHA1WITHRSA, data, publicKey, sign);
  }



  public static boolean verify(SignTypeEnum signType, byte[] data, String publicKey, String sign)
    throws Exception
  {
    byte[] keyBytes = decryptBASE64(publicKey);

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);

    Signature signature = Signature.getInstance(signType.getDesc());
    signature.initVerify(publicKey2);
    signature.update(data);
    return signature.verify(decryptBASE64(sign));
  }



  public static String decryptResponse(String fullResponse, String privateKey, String charset, EncryptionModeEnum encryptionType)
    throws Exception
  {
    String decryptedRsp = null;
    Map rootJson = parseResponseMap(fullResponse);
    for (Iterator it = rootJson.keySet().iterator(); it.hasNext(); ) {
      String key = (String)it.next();
      if (key.endsWith("_response")) {
        String value = (String)rootJson.get(key);
        decryptedRsp = value;
      }
    }

    if (((Boolean)rootJson.get("encrypted")).booleanValue()) {
      decryptedRsp = decrypt(decryptedRsp, privateKey, charset, encryptionType);
    }
    return decryptedRsp;
  }



  public static void verifySign(String fullResponse, String decryptedBizResponse, String publicKey, String charset)
    throws Exception
  {
    verifySign(SignTypeEnum.SHA1WITHRSA, fullResponse, decryptedBizResponse, publicKey, charset);
  }



  public static void verifySign(SignTypeEnum signType, String fullResponse, String decryptedBizResponse, String publicKey, String charset)
    throws Exception
  {
    Map rootJson = parseResponseMap(fullResponse);
    String sign = (String)rootJson.get("biz_response_sign");

    if ((sign != null) && (sign.length() > 0)) {
      boolean success = verify(signType, decryptedBizResponse.getBytes(charset), publicKey, sign);

      if (!(success))
        throw new ZhimaApiException("验签失败: " + sign.toString());
    }
  }

  public static Map parseResponseMap(String fullResponse)
    throws ZhimaApiException
  {
    JSONValidatingReader reader = new JSONValidatingReader(new ExceptionErrorListener());
    Object rootObj = reader.read(fullResponse);
    if (rootObj instanceof Map) {
      Map rootJson = (Map)rootObj;
      return rootJson;
    }

    throw new ZhimaApiException("返回结果格式有误:" + fullResponse);
  }








  private static int getMaxEncryptBlockSize(KeyFactory keyFactory, Key key)
    throws Exception
  {
    int maxLength = 117;
    try {
      RSAPublicKeySpec publicKeySpec = (RSAPublicKeySpec)keyFactory.getKeySpec(key, RSAPublicKeySpec.class);
      int keyLength = publicKeySpec.getModulus().bitLength();
      maxLength = keyLength / 8 - 11;
    }
    catch (Exception e) {
    }
    return maxLength;
  }






  private static int getMaxEncryptBlockSizeByEncryptionType(EncryptionModeEnum encryptionType)
  {
    if (encryptionType == EncryptionModeEnum.RSA1024)
      return 117;
    if (encryptionType == EncryptionModeEnum.RSA2048) {
      return 245;
    }

    return 117;
  }








  private static int getMaxDecryptBlockSize(KeyFactory keyFactory, Key key)
    throws Exception
  {
    int maxLength = 128;
    try {
      RSAPrivateKeySpec publicKeySpec = (RSAPrivateKeySpec)keyFactory.getKeySpec(key, RSAPrivateKeySpec.class);
      int keyLength = publicKeySpec.getModulus().bitLength();
      maxLength = keyLength / 8;
    }
    catch (Exception e) {
    }
    return maxLength;
  }






  private static int getMaxDecryptBlockSizeByEncryptionType(EncryptionModeEnum encryptionType)
  {
    if (encryptionType == EncryptionModeEnum.RSA1024)
      return 128;
    if (encryptionType == EncryptionModeEnum.RSA2048) {
      return 256;
    }

    return 128;
  }
}

验签代码

/**

 * 验证签名
 * @return
 * @throws Exception 
 */
public static boolean checksign(JSONObject jsonObject,String platpublickey) throws Exception{
	//获取签名
	String sign = jsonObject.getString("sign");
	//json对象转换成map
	Map<String,Object> bizParams = getTextParams(jsonObject);
	String content = unurlgetSignCheckContentV2(bizParams).trim().replace("\\/", "/");
	return PKRSACoderUtil.verify(SignTypeEnum.SHA256WITHRSA, content.getBytes(SysUtil.CHARSET),platpublickey, sign);
}

签名代码

/**
 * 生成签名
 * 
 * 
 * @return
 * 
 */
public static String producesignByJson(JSONObject jsonObject ,String zzrsprivatekey){
	String signstr="";
	try{
			String content = unurlgetSignCheckContentV2(getTextParams(jsonObject)).trim();
			signstr = PKRSACoderUtil.sign(SignTypeEnum.SHA256WITHRSA, content, SysUtil.CHARSET, zzrsprivatekey);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return signstr;
}	
  • RSA
    8 引用 • 5 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • OAuth

    OAuth 协议为用户资源的授权提供了一个安全的、开放而又简易的标准。与以往的授权方式不同之处是 oAuth 的授权不会使第三方触及到用户的帐号信息(如用户名与密码),即第三方无需使用用户的用户名与密码就可以申请获得该用户资源的授权,因此 oAuth 是安全的。oAuth 是 Open Authorization 的简写。

    36 引用 • 103 回帖 • 16 关注
  • golang

    Go 语言是 Google 推出的一种全新的编程语言,可以在不损失应用程序性能的情况下降低代码的复杂性。谷歌首席软件工程师罗布派克(Rob Pike)说:我们之所以开发 Go,是因为过去 10 多年间软件开发的难度令人沮丧。Go 是谷歌 2009 发布的第二款编程语言。

    495 引用 • 1386 回帖 • 329 关注
  • 人工智能

    人工智能(Artificial Intelligence)是研究、开发用于模拟、延伸和扩展人的智能的理论、方法、技术及应用系统的一门技术科学。

    77 引用 • 159 回帖
  • OpenStack

    OpenStack 是一个云操作系统,通过数据中心可控制大型的计算、存储、网络等资源池。所有的管理通过前端界面管理员就可以完成,同样也可以通过 Web 接口让最终用户部署资源。

    10 引用 • 5 关注
  • BND

    BND(Baidu Netdisk Downloader)是一款图形界面的百度网盘不限速下载器,支持 Windows、Linux 和 Mac,详细介绍请看这里

    107 引用 • 1281 回帖 • 29 关注
  • Facebook

    Facebook 是一个联系朋友的社交工具。大家可以通过它和朋友、同事、同学以及周围的人保持互动交流,分享无限上传的图片,发布链接和视频,更可以增进对朋友的了解。

    4 引用 • 15 回帖 • 458 关注
  • SQLite

    SQLite 是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是全世界使用最为广泛的数据库引擎。

    4 引用 • 7 回帖
  • QQ

    1999 年 2 月腾讯正式推出“腾讯 QQ”,在线用户由 1999 年的 2 人(马化腾和张志东)到现在已经发展到上亿用户了,在线人数超过一亿,是目前使用最广泛的聊天软件之一。

    45 引用 • 557 回帖 • 160 关注
  • 反馈

    Communication channel for makers and users.

    124 引用 • 907 回帖 • 223 关注
  • Redis

    Redis 是一个开源的使用 ANSI C 语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库,并提供多种语言的 API。从 2010 年 3 月 15 日起,Redis 的开发工作由 VMware 主持。从 2013 年 5 月开始,Redis 的开发由 Pivotal 赞助。

    284 引用 • 248 回帖 • 123 关注
  • Sublime

    Sublime Text 是一款可以用来写代码、写文章的文本编辑器。支持代码高亮、自动完成,还支持通过插件进行扩展。

    10 引用 • 5 回帖
  • WiFiDog

    WiFiDog 是一套开源的无线热点认证管理工具,主要功能包括:位置相关的内容递送;用户认证和授权;集中式网络监控。

    1 引用 • 7 回帖 • 561 关注
  • GraphQL

    GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并没有和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑。

    4 引用 • 3 回帖 • 16 关注
  • 倾城之链
    23 引用 • 66 回帖 • 121 关注
  • 京东

    京东是中国最大的自营式电商企业,2015 年第一季度在中国自营式 B2C 电商市场的占有率为 56.3%。2014 年 5 月,京东在美国纳斯达克证券交易所正式挂牌上市(股票代码:JD),是中国第一个成功赴美上市的大型综合型电商平台,与腾讯、百度等中国互联网巨头共同跻身全球前十大互联网公司排行榜。

    14 引用 • 102 回帖 • 403 关注
  • iOS

    iOS 是由苹果公司开发的移动操作系统,最早于 2007 年 1 月 9 日的 Macworld 大会上公布这个系统,最初是设计给 iPhone 使用的,后来陆续套用到 iPod touch、iPad 以及 Apple TV 等产品上。iOS 与苹果的 Mac OS X 操作系统一样,属于类 Unix 的商业操作系统。

    84 引用 • 139 回帖 • 1 关注
  • PHP

    PHP(Hypertext Preprocessor)是一种开源脚本语言。语法吸收了 C 语言、 Java 和 Perl 的特点,主要适用于 Web 开发领域,据说是世界上最好的编程语言。

    165 引用 • 407 回帖 • 509 关注
  • jQuery

    jQuery 是一套跨浏览器的 JavaScript 库,强化 HTML 与 JavaScript 之间的操作。由 John Resig 在 2006 年 1 月的 BarCamp NYC 上释出第一个版本。全球约有 28% 的网站使用 jQuery,是非常受欢迎的 JavaScript 库。

    63 引用 • 134 回帖 • 724 关注
  • 单点登录

    单点登录(Single Sign On)是目前比较流行的企业业务整合的解决方案之一。SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

    9 引用 • 25 回帖 • 2 关注
  • Markdown

    Markdown 是一种轻量级标记语言,用户可使用纯文本编辑器来排版文档,最终通过 Markdown 引擎将文档转换为所需格式(比如 HTML、PDF 等)。

    165 引用 • 1474 回帖
  • Ant-Design

    Ant Design 是服务于企业级产品的设计体系,基于确定和自然的设计价值观上的模块化解决方案,让设计者和开发者专注于更好的用户体验。

    17 引用 • 23 回帖 • 3 关注
  • CloudFoundry

    Cloud Foundry 是 VMware 推出的业界第一个开源 PaaS 云平台,它支持多种框架、语言、运行时环境、云平台及应用服务,使开发人员能够在几秒钟内进行应用程序的部署和扩展,无需担心任何基础架构的问题。

    5 引用 • 18 回帖 • 149 关注
  • 酷鸟浏览器

    安全 · 稳定 · 快速
    为跨境从业人员提供专业的跨境浏览器

    3 引用 • 59 回帖 • 23 关注
  • InfluxDB

    InfluxDB 是一个开源的没有外部依赖的时间序列数据库。适用于记录度量,事件及实时分析。

    2 引用 • 55 关注
  • 服务器

    服务器,也称伺服器,是提供计算服务的设备。由于服务器需要响应服务请求,并进行处理,因此一般来说服务器应具备承担服务并且保障服务的能力。

    124 引用 • 580 回帖
  • 996
    13 引用 • 200 回帖 • 6 关注
  • Latke

    Latke 是一款以 JSON 为主的 Java Web 框架。

    70 引用 • 533 回帖 • 735 关注