All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.app.common.encrypt.EncryUtil Maven / Gradle / Ivy

The newest version!
package com.app.common.encrypt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.TreeMap;

public class EncryUtil {

	/**
	 * 生成RSA签名
	 */
	public static String handleRSA(TreeMap map,
			String privateKey) {
		String str = JSON.toJSONString(map);
		map = JSON.parseObject(str,
				new TypeReference>() {
				});
		StringBuffer sbuffer = new StringBuffer();
		for (Entry entry : map.entrySet()) {
			sbuffer.append(entry.getValue());
		}
		String signTemp = sbuffer.toString();

		String sign = "";
		if (StringUtils.isNotEmpty(privateKey)) {
			sign = RSA.sign(signTemp, privateKey);
		}
		return sign;
	}

	/**
	 * 对返回的结果进行验签
	 * 
	 * @param data
	 *            返回的业务数据密文
	 * @param encrypt_key
	 *            返回的对AesKey加密后的密文
	 * @param publickKey
	 *            提供的公钥
	 * @param merchantPrivateKey
	 *            商户自己的私钥
	 * @return 验签是否通过
	 * @throws Exception
	 */
	public static boolean checkDecryptAndSign(String data, String encrypt_key,
			String publickKey, String merchantPrivateKey) throws Exception {

		/** 1.使用YBprivatekey解开aesEncrypt。 */
		String AESKey = "";
		try {
			AESKey = RSA.decrypt(encrypt_key, merchantPrivateKey);
		} catch (Exception e) {
			/** AES密钥解密失败 */
			e.printStackTrace();
			return false;
		}

		/** 2.用aeskey解开data。取得data明文 */
		String realData = AES.decryptFromBase64(data, AESKey);

		TreeMap map = JSON.parseObject(realData,
				new TypeReference>() {
				});

		/** 3.取得data明文sign。 */
		String sign = StringUtils.trimToEmpty(map.get("secSignature"));

		/** 4.对map中的值进行验证 */
		StringBuffer signData = new StringBuffer();
		Iterator> iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Entry entry = iter.next();

			/** 把sign参数隔过去 */
			if (StringUtils.equals((String) entry.getKey(), "secSignature")) {
				continue;
			}
			signData.append(entry.getValue() == null ? "" : entry.getValue());
		}

		/** 5. result为true时表明验签通过 */
		boolean result = RSA.checkSign(signData.toString(), sign, publickKey);

		return result;
	}

	/**
	 * 生成hmac
	 */
	public static String handleHmac(TreeMap map, String hmacKey) {
		StringBuffer sbuffer = new StringBuffer();
		for (Entry entry : map.entrySet()) {
			sbuffer.append(entry.getValue());
		}
		String hmacTemp = sbuffer.toString();

		String hmac = "";
		if (StringUtils.isNotEmpty(hmacKey)) {
			hmac = Digest.hmacSHASign(hmacTemp, hmacKey, Digest.ENCODE);
		}
		return hmac;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy