支付系统中的常用工具

本贴最后更新于 2484 天前,其中的信息可能已经时异事殊
  • StringUtils.java

  处理常用字符串:判断是否为空 isEmpty(String value);

  按字典排序并拼接参数:createLinkString(Map params);

  import java.util.ArrayList;
  import java.util.Collections;
  import java.util.List;
  import java.util.Map;

  public class StringUtils {
	  /**
	   * 判断字符数组是否为空
	   */
	  public static boolean areNotEmpty(String... values) {
		  boolean result = true;
		  if (values == null || values.length == 0) {
			  result = false;
		  } else {
			  for (String value : values) {
				  result &= !isEmpty(value);
			  }
		  }
		  return result;
	  }

	  /**
	   * 把数组所有元素排序,并按照"name1=value1&name2=value2..."字符拼接成字符串
	   * 
	   * @param params
	   *            需要排序并参与字符拼接的参数组
	   * @return 拼接后字符串
	   */
	  public static String createLinkString(Map<String, String> params) {

		  List<String> keys = new ArrayList<String>(params.keySet());
		  Collections.sort(keys);

		  String prestr = "";

		  for (int i = 0; i < keys.size(); i++) {
			  String key = keys.get(i);
			  String value = params.get(key);

			  if (i == keys.size() - 1) {
				  prestr = prestr + key + "=" + value;
			  } else {
				  prestr = prestr + key + "=" + value + "&";
			  }
		  }

		  return prestr;
	  }

	  /**
	   * 判断字符串是否为空
	   * <ul>
	   * <li>isEmpty(null) = true</li>
	   * <li>isEmpty("") = true</li>
	   * <li>isEmpty("   ") = true</li>
	   * <li>isEmpty("abc") = false</li>
	   * </ul>
	   * 
	   * @param value
	   *            目标字符串
	   * @return true/false
	   */
	  public static boolean isEmpty(String value) {
		  int strLen;
		  if (value == null || (strLen = value.length()) == 0) {
			  return true;
		  }
		  for (int i = 0; i < strLen; i++) {
			  if ((Character.isWhitespace(value.charAt(i)) == false)) {
				  return false;
			  }
		  }
		  return true;
	  }
  }
  • 支付系统中的签名和验签 SignUtils.java
    import java.io.InputStream;
    import java.security.KeyStore;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.cert.Certificate;
    import java.security.cert.CertificateFactory;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import org.apache.commons.codec.binary.Base64;

    /**

    */
    public class SignUtils {

    /**  */
    // 缓存公钥和私钥
    public static Map<String, Object> certMap = new java.util.concurrent.ConcurrentHashMap<String, Object>();
    
    /**
     * 
     *
     * @param sArray 
     * @return 
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
    
    	Map<String, String> result = new HashMap<String, String>();
    
    	if (sArray == null || sArray.size() <= 0) {
    		return result;
    	}
    
    	for (String key : sArray.keySet()) {
    		String value = sArray.get(key);
    		if (value == null || StringUtils.isEmpty(value)
    				|| key.equalsIgnoreCase("sign")) {
    			continue;
    		}
    		result.put(key, value);
    	}
    
    	return result;
    }
    
    
    /**
     * 
     *
     * @param sortedParams 
     * @return 
     */
    public static String getSignContent(Map<String, String> sortedParams) {
    	StringBuffer content = new StringBuffer();
    	List<String> keys = new ArrayList<String>(sortedParams.keySet());
    	Collections.sort(keys);
    	int index = 0;
    	for (int i = 0; i < keys.size(); i++) {
    		String key = keys.get(i);
    		String value = sortedParams.get(key);
    		if (StringUtils.areNotEmpty(key, value)) {
    			content.append((index == 0 ? "" : "&") + key + "=" + value);
    			index++;
    		}
    	}
    	return content.toString();
    }
    
    
    /**
     * 
     * 签名
     * @param params 业务参数 
     * @param charset 编码
     * @param pfxCertFileInputStream 证书输入流 
     * @param rsaPassword  私钥pkcs12证书密码
     * @param algorithmName rsa算法名
     * @return 
     * @throws Exception 
     */
    public static String rsaSign(Map<String, String> params, String charset,
    		InputStream pfxCertFileInputStream,String rsaPassword, String algorithmName) throws Exception {
    	String signContent = getSignContent(params);
    
    	return rsaSign(signContent, charset, pfxCertFileInputStream,rsaPassword, algorithmName);
    }
    
    /**
     * 
     *
     * @param content 
     * @param charset 
     * @param pfxCertFileInputStream 
     * @param rsaPassword 
     * @param algorithmName 
     * @return 
     * @throws Exception 
     */
    public static String rsaSign(String content, String charset,
    		InputStream pfxCertFileInputStream,String rsaPassword, String algorithmName) throws Exception {
    	try {
    		PrivateKey priKey = getPrivateKeyFromPKCS12(
    				rsaPassword,
    				pfxCertFileInputStream);
    
    		java.security.Signature signature = java.security.Signature
    				.getInstance(algorithmName);
    
    		signature.initSign(priKey);
    
    		if (StringUtils.isEmpty(charset)) {
    			signature.update(content.getBytes());
    		} else {
    			signature.update(content.getBytes(charset));
    		}
    
    		byte[] signed = signature.sign();
    
    		String sign = new String(Base64.encodeBase64(signed), charset);
    
    
    		return sign;
    	} catch (Exception e) {
    		throw new Exception("RSAcontent = " + content + "; charset = "
    				+ charset, e);
    	}
    }
    
    /**
     * 
     *
     * @param publicCertFileInputStream 
     * @param params 
     * @param sign 
     * @param charset 
     * @param algorithmName 
     * @return 
     * @throws Exception 
     */
    public static boolean rsaCheckContent(
    		InputStream publicCertFileInputStream, Map<String, String> params,
    		String sign, String charset,String algorithmName) throws Exception {
    	String content = StringUtils.createLinkString(SignUtils
    			.paraFilter(params));
    
    	return rsaCheckContent(publicCertFileInputStream, content, sign,
    			charset, algorithmName);
    }
    
    
    /**
     * 
     *
     * @param publicCertFileInputStream 
     * @param content 
     * @param sign 
     * @param charset 
     * @param algorithmName 
     * @return 
     * @throws Exception 
     */
    public static boolean rsaCheckContent(
    		InputStream publicCertFileInputStream, String content, String sign,
    		String charset, String algorithmName) throws Exception {
    	boolean bFlag = false;
    	try {
    		java.security.Signature signetcheck = java.security.Signature
    				.getInstance(algorithmName);
    		signetcheck
    				.initVerify(getPublicKeyFromCert(publicCertFileInputStream));
    		signetcheck.update(content.getBytes(charset));
    		if (signetcheck.verify(Base64.decodeBase64(sign.getBytes(charset)))) {
    			bFlag = true;
    			System.out.println("签名成功!");
    		}else{
    			System.out.println("签名失败!");
    		}
    	} catch (Exception e) {
    		throw new Exception("验证签名异常");
    	}
    
    	return bFlag;
    }
    
    /**
     * 读取公钥,x509格式.
     *
     * @param ins 
     * @return 
     * @throws Exception 
     */
    public static PublicKey getPublicKeyFromCert(InputStream ins)
    		throws Exception {
    	PublicKey pubKey = (PublicKey) certMap.get("PublicKey");
    	if (pubKey != null) {
    		return pubKey;
    	}
    
    	try {
    		CertificateFactory cf = CertificateFactory.getInstance("X.509");
    		Certificate cac = cf.generateCertificate(ins);
    		pubKey = cac.getPublicKey();
    		certMap.put("PublicKey", pubKey);
    	} catch (Exception e) {
    		if (ins != null)
    			ins.close();
    		throw e;
    	} finally {
    		if (ins != null) {
    			ins.close();
    		}
    	}
    
    	return pubKey;
    }
    
    /**
     * 读取PKCS12格式的key(私钥)pfx格式.
     *
     * @param rsaPassword 
     * @param ins 
     * @return 
     * @throws Exception 
     */
    public static PrivateKey getPrivateKeyFromPKCS12(String rsaPassword,
    		InputStream ins) throws Exception {
    	PrivateKey priKey = (PrivateKey) certMap.get("PrivateKey");
    	if (priKey != null) {
    		return priKey;
    	}
    
    	KeyStore keystoreCA = KeyStore.getInstance("PKCS12");
    	try {
    		// 读取CA根证书
    		keystoreCA.load(ins, rsaPassword.toCharArray());
    
    		Enumeration<?> aliases = keystoreCA.aliases();
    		String keyAlias = null;
    		if (aliases != null) {
    			while (aliases.hasMoreElements()) {
    				keyAlias = (String) aliases.nextElement();
    				// 获取CA私钥
    				priKey = (PrivateKey) (keystoreCA.getKey(keyAlias,
    						rsaPassword.toCharArray()));
    				if (priKey != null) {
    					certMap.put("PrivateKey", priKey);
    					break;
    				}
    			}
    		}
    	} catch (Exception e) {
    		if (ins != null)
    			ins.close();
    		throw e;
    	} finally {
    		if (ins != null) {
    			ins.close();
    		}
    	}
    
    	return priKey;
    }
    

    }

相关帖子

欢迎来到这里!

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

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

推荐标签 标签

  • WebClipper

    Web Clipper 是一款浏览器剪藏扩展,它可以帮助你把网页内容剪藏到本地。

    3 引用 • 9 回帖 • 2 关注
  • Sym

    Sym 是一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)系统平台。

    下一代的社区系统,为未来而构建

    523 引用 • 4581 回帖 • 692 关注
  • 反馈

    Communication channel for makers and users.

    123 引用 • 906 回帖 • 191 关注
  • Firefox

    Mozilla Firefox 中文俗称“火狐”(正式缩写为 Fx 或 fx,非正式缩写为 FF),是一个开源的网页浏览器,使用 Gecko 排版引擎,支持多种操作系统,如 Windows、OSX 及 Linux 等。

    7 引用 • 30 回帖 • 454 关注
  • 友情链接

    确认过眼神后的灵魂连接,站在链在!

    24 引用 • 373 回帖 • 2 关注
  • Shell

    Shell 脚本与 Windows/Dos 下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比 Windows 下的批处理更强大,比用其他编程程序编辑的程序效率更高,因为它使用了 Linux/Unix 下的命令。

    122 引用 • 73 回帖
  • Redis

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

    284 引用 • 247 回帖 • 183 关注
  • CloudFoundry

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

    5 引用 • 18 回帖 • 149 关注
  • uTools

    uTools 是一个极简、插件化、跨平台的现代桌面软件。通过自由选配丰富的插件,打造你得心应手的工具集合。

    5 引用 • 13 回帖 • 1 关注
  • wolai

    我来 wolai:不仅仅是未来的云端笔记!

    1 引用 • 11 回帖
  • H2

    H2 是一个开源的嵌入式数据库引擎,采用 Java 语言编写,不受平台的限制,同时 H2 提供了一个十分方便的 web 控制台用于操作和管理数据库内容。H2 还提供兼容模式,可以兼容一些主流的数据库,因此采用 H2 作为开发期的数据库非常方便。

    11 引用 • 54 回帖 • 642 关注
  • 自由行
  • IPFS

    IPFS(InterPlanetary File System,星际文件系统)是永久的、去中心化保存和共享文件的方法,这是一种内容可寻址、版本化、点对点超媒体的分布式协议。请浏览 IPFS 入门笔记了解更多细节。

    20 引用 • 245 回帖 • 229 关注
  • 支付宝

    支付宝是全球领先的独立第三方支付平台,致力于为广大用户提供安全快速的电子支付/网上支付/安全支付/手机支付体验,及转账收款/水电煤缴费/信用卡还款/AA 收款等生活服务应用。

    29 引用 • 347 回帖 • 1 关注
  • Netty

    Netty 是一个基于 NIO 的客户端-服务器编程框架,使用 Netty 可以让你快速、简单地开发出一个可维护、高性能的网络应用,例如实现了某种协议的客户、服务端应用。

    49 引用 • 33 回帖 • 21 关注
  • 负能量

    上帝为你关上了一扇门,然后就去睡觉了....努力不一定能成功,但不努力一定很轻松 (° ー °〃)

    85 引用 • 1201 回帖 • 455 关注
  • GitHub

    GitHub 于 2008 年上线,目前,除了 Git 代码仓库托管及基本的 Web 管理界面以外,还提供了订阅、讨论组、文本渲染、在线文件编辑器、协作图谱(报表)、代码片段分享(Gist)等功能。正因为这些功能所提供的便利,又经过长期的积累,GitHub 的用户活跃度很高,在开源世界里享有深远的声望,并形成了社交化编程文化(Social Coding)。

    207 引用 • 2031 回帖
  • 宕机

    宕机,多指一些网站、游戏、网络应用等服务器一种区别于正常运行的状态,也叫“Down 机”、“当机”或“死机”。宕机状态不仅仅是指服务器“挂掉了”、“死机了”状态,也包括服务器假死、停用、关闭等一些原因而导致出现的不能够正常运行的状态。

    13 引用 • 82 回帖 • 36 关注
  • Hadoop

    Hadoop 是由 Apache 基金会所开发的一个分布式系统基础架构。用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。

    82 引用 • 122 回帖 • 614 关注
  • 域名

    域名(Domain Name),简称域名、网域,是由一串用点分隔的名字组成的 Internet 上某一台计算机或计算机组的名称,用于在数据传输时标识计算机的电子方位(有时也指地理位置)。

    43 引用 • 208 回帖
  • 机器学习

    机器学习(Machine Learning)是一门多领域交叉学科,涉及概率论、统计学、逼近论、凸分析、算法复杂度理论等多门学科。专门研究计算机怎样模拟或实现人类的学习行为,以获取新的知识或技能,重新组织已有的知识结构使之不断改善自身的性能。

    76 引用 • 37 回帖
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    180 引用 • 447 回帖
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    69 引用 • 190 回帖 • 493 关注
  • MongoDB

    MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是一个基于分布式文件存储的数据库,由 C++ 语言编写。旨在为应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。

    90 引用 • 59 回帖 • 3 关注
  • V2Ray
    1 引用 • 15 回帖
  • Unity

    Unity 是由 Unity Technologies 开发的一个让开发者可以轻松创建诸如 2D、3D 多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

    25 引用 • 7 回帖 • 249 关注
  • Flume

    Flume 是一套分布式的、可靠的,可用于有效地收集、聚合和搬运大量日志数据的服务架构。

    9 引用 • 6 回帖 • 592 关注