mch 支付、代扣API调用签名验证

@param map 参与签名的参数
@param sign_type HMAC-SHA256 或 MD5
@param key mch key
@return boolean
326898
public static boolean validateSign(Map<String,String> map,String sign_type,String key){
		if(map.get("sign") == null){
			return false;
		}
		return map.get("sign").equals(generateSign(map,sign_type,key));
	}
365699
public static Map<String, String> buildSignAfterParasMap(Map<String, String> params, String paternerKey) {
		params.put("nonce_str", String.valueOf(System.currentTimeMillis()));
		String sign = PaymentKit.createSign(params, paternerKey);
		params.put("sign", sign);
		return params;
	}
708063
def _sha256_sign(self, method, url, headers, body):
        
        d = ''
        sign_headers = method.upper() + '|' + url + '|'
        for key, value in sorted(headers.items()):
            if key.startswith('X-Mcash-'):
                sign_headers += d + key.upper() + '=' + value
                d = '&'

        rsa_signature = base64.b64encode(
            self.signer.sign(SHA256.new(sign_headers)))

        return 'RSA-SHA256 ' + rsa_signature
1260928
public Map<String, String> build(SignType signType) throws Exception {
		Map<String, String> map = createMap();
		if(SignType.MD5 == signType) {
			map.put("sign_type", "MD5");
		}else {
			map.put("sign_type", "HMAC-SHA256");
		}
		map.put("sign", PaymentKit.createSign(map, getPaternerKey(), signType));
		return map;
	}
692267
function signStr(str, key) {
  var hmac = crypto.createHmac('sha1', key);
  hmac.update(str);
  return hmac.digest('base64').replace(/\+/g, '-').replace(/\//g, '_');
}
1366611
public static String buildRequestMysign(Map<String, String> params, String key, String signType) {
		String prestr = createLinkString(params); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
		if (signType.equals("MD5")) {
			return HashKit.md5(prestr.concat(key));
		}
		return null;
	}
297938
public static boolean validateSign(Map<String,String> map,String key){
		return validateSign(map, null, key);
	}
320669
private byte[] signRaw(BoxSignatureAlgorithm algorithm, String key, String webHookPayload,
            String deliveryTimestamp) {
        Mac mac = MAC_POOL.acquire(algorithm.javaProviderName);
        try {
            mac.init(new SecretKeySpec(key.getBytes(UTF_8), algorithm.javaProviderName));
            mac.update(UTF_8.encode(webHookPayload));
            mac.update(UTF_8.encode(deliveryTimestamp));
            return mac.doFinal();
        } catch (InvalidKeyException e) {
            throw new IllegalArgumentException("Invalid key: ", e);
        } finally {
            MAC_POOL.release(mac);
        }
    }
1236753
function _sign($key, $signatureAlgorithm)
    {
        switch (strtolower(get_class($key))) {
            case 'crypt_rsa':
                switch ($signatureAlgorithm) {
                    case 'md2WithRSAEncryption':
                    case 'md5WithRSAEncryption':
                    case 'sha1WithRSAEncryption':
                    case 'sha224WithRSAEncryption':
                    case 'sha256WithRSAEncryption':
                    case 'sha384WithRSAEncryption':
                    case 'sha512WithRSAEncryption':
                        $key->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm));
                        $key->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);

                        $this->currentCert['signature'] = base64_encode("\0" . $key->sign($this->signatureSubject));
                        return $this->currentCert;
                }
            default:
                return false;
        }
    }
293058
function( input, key ) {

    if( !Buffer.isBuffer( input ) )
      throw new TypeError( 'Input must be a buffer' )

    if( this.type === 'PLAIN' )
      return Buffer.allocUnsafe(0)

    if( !Buffer.isBuffer( key ) )
      throw new TypeError( 'Key must be a buffer' )

    var signature = this.type === 'HS' ?
      crypto.createHmac( this.algorithm + this.bits, key ) :
      crypto.createSign( this.algorithm + this.bits )

    signature.update( input )

    var digest = this.type === 'HS' ?
      signature.digest() :
      signature.sign( key )

    if( this.type === 'ES' )
      digest = this._signECDSA( digest )

    return digest

  }
1108595
public boolean isValidSignature(final Key key) {
        final byte[] computedHmac = key.sign(getVersion(), getTimestamp(), getInitializationVector(),
                getCipherText());
        return Arrays.equals(getHmac(), computedHmac);
    }
622908
public static Map<String, String> sign(Map<String, String> reqData,String encoding) {
		reqData = SDKUtil.filterBlank(reqData);
		SDKUtil.sign(reqData, encoding);
		return reqData;
	}
596210
public byte[] hmac(byte[] key)
	{
		try {
			Key secretKey = new SecretKeySpec(key, "HmacSHA1");
			Mac hmac_algo = Mac.getInstance("HmacSHA1");
			hmac_algo.init(secretKey);
			hmac_algo.update(this.data);
			for(Entry<String, byte[]> a: this.annotations.entrySet())   // this is in a fixed order because it is a SortedMap
			{
				if(!a.getKey().equals("HMAC"))
					hmac_algo.update(a.getValue());
			}
			return hmac_algo.doFinal();
		} catch (NoSuchAlgorithmException e) {
			throw new PyroException("invalid hmac algorithm",e);
		} catch (InvalidKeyException e) {
			throw new PyroException("invalid hmac key",e);
		}
	}
846583
protected static final byte[] signISO9796(byte[][] key, byte[] data, int off, int len) throws Exception {
        CachingKey ck = new CachingKey(key, data, off, len);
        CachingKey result = cryptoKeysMap.get(ck);

        if (result != null) {
            result.successfulUses += 1;
            result.reused = true;
            return result.result;
        } else {
            if (cryptoKeysMap.size() > MAX_CACHE) {
                try {
                    CachingKey[] keys = cryptoKeysMap.keySet().toArray(new CachingKey[cryptoKeysMap.size()]);
                    Arrays.sort(keys, cachingKeyComparator);
                    if (cachingKeyComparator.compare(keys[0], keys[keys.length - 1]) < 0) {
                        for (int i = 0; i < cryptoKeysMap.size() / 5; i++) {
                            cryptoKeysMap.remove(keys[i]);
                            keys[i + 1 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 2 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 3 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[i + 4 * cryptoKeysMap.size() / 5].successfulUses--;
                        }
                    } else {
                        for (int i = 0; i < cryptoKeysMap.size() / 5; i++) {
                            cryptoKeysMap.remove(keys[keys.length - 1 - i]);
                            keys[keys.length - 1 - i - 1 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 2 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 3 * cryptoKeysMap.size() / 5].successfulUses--;
                            keys[keys.length - 1 - i - 4 * cryptoKeysMap.size() / 5].successfulUses--;
                        }
                    }
                } catch (Exception e) {
                    // do nothing. since this code is used for the command line utility, no log is taken.
                }
                 
            }
        }

        /** Invoked by LTPADigSignature **/
        BigInteger n = new BigInteger(key[0]);
        BigInteger e = new BigInteger(key[2]);
        BigInteger p = new BigInteger(key[3]);
        BigInteger q = new BigInteger(key[4]);
        BigInteger d = e.modInverse((p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)));
        KeyFactory kFact = null;
        if (LTPAKeyUtil.isIBMJCEAvailable()) {
            kFact = KeyFactory.getInstance(CRYPTO_ALGORITHM, IBMJCE_NAME);
        } else {
            kFact = KeyFactory.getInstance(CRYPTO_ALGORITHM);
        }


        BigInteger pep = new BigInteger(key[5]);
        BigInteger peq = new BigInteger(key[6]);
        BigInteger crtC = new BigInteger(key[7]);
        RSAPrivateCrtKeySpec privCrtKeySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, pep, peq, crtC);
        PrivateKey privKey = kFact.generatePrivate(privCrtKeySpec);

        Signature rsaSig = null;
        if (LTPAKeyUtil.isIBMJCEAvailable()) {
            rsaSig = Signature.getInstance(SIGNATURE_ALGORITHM, IBMJCE_NAME);
        } else {
            rsaSig = Signature.getInstance(SIGNATURE_ALGORITHM);
        }
        rsaSig.initSign(privKey);
        rsaSig.update(data, off, len);
        byte[] sig = rsaSig.sign();

        cryptoKeysMap.put(ck, ck);
        ck.result = sig;
        ck.successfulUses = 0;

        return sig;
    }
129208
def sign(self, msg, key):
        
        h = hmac.HMAC(key, self.algorithm(), default_backend())
        h.update(msg)
        return h.finalize()
664951
public static String hmacMd5(String data, String key) {
        return hmacMd5(data.getBytes(), key.getBytes());
    }
791977
public static String hmacSHA256(String stringSignTemp, String partnerKey)  throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
		Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
		SecretKeySpec secret_key = new SecretKeySpec(partnerKey.getBytes(), "HmacSHA256");
		sha256_HMAC.init(secret_key);
		return byteArrayToHexString(sha256_HMAC.doFinal(stringSignTemp.getBytes("utf-8")));
	}