多密钥签名(通过传入密钥签名)<br>
功能：如果有多个商户号接入银联,每个商户号对应不同的证书可以使用此方法:传入私钥证书和密码(并且在acp_sdk.properties中 配置 acpsdk.singleMode=false)<br>
@param reqData 请求报文map<br>
@param secureKey 签名对称密钥<br>
@param encoding 上送请求报文域encoding字段的值<br>
@return　签名后的map对象<br>
322816
public static Map<String, String> signBySecureKey(Map<String, String> reqData, String secureKey, String encoding) {
		reqData = SDKUtil.filterBlank(reqData);
		SDKUtil.signBySecureKey(reqData, secureKey, encoding);
		return reqData;
	}
427599
public static String decryptData(String base64EncryptedInfo, String certPath, 
			String certPwd, String encoding) {
		return SecureUtil.decryptData(base64EncryptedInfo, encoding, CertUtil
				.getSignCertPrivateKeyByStoreMap(certPath, certPwd));
	}
774453
public static String encryptData(String data, String encoding) {
		return SecureUtil.encryptData(data, encoding, CertUtil
				.getEncryptCertPublicKey());
	}
1363113
public static String encode(byte[] rawData) {
        StringBuilder buffer = new StringBuilder(4 * rawData.length / 3);

        int pos = 0;
        int iterations = rawData.length / 3;
        for (int i = 0; i < iterations; i++) {
            int value = ((rawData[pos++] & 0xFF) << 16) |
                    ((rawData[pos++] & 0xFF) << 8) | (rawData[pos++] & 0xFF);

            buffer.append(BASE64_ALPHABET[(value >>> 18) & 0x3F]);
            buffer.append(BASE64_ALPHABET[(value >>> 12) & 0x3F]);
            buffer.append(BASE64_ALPHABET[(value >>> 6) & 0x3F]);
            buffer.append(BASE64_ALPHABET[value & 0x3F]);
        }

        switch (rawData.length % 3) {
            case 1:
                buffer.append(BASE64_ALPHABET[(rawData[pos] >>> 2) & 0x3F]);
                buffer.append(BASE64_ALPHABET[(rawData[pos] << 4) & 0x3F]);
                buffer.append("==");
                break;
            case 2:
                int value = ((rawData[pos++] & 0xFF) << 8) | (rawData[pos] & 0xFF);
                buffer.append(BASE64_ALPHABET[(value >>> 10) & 0x3F]);
                buffer.append(BASE64_ALPHABET[(value >>> 4) & 0x3F]);
                buffer.append(BASE64_ALPHABET[(value << 2) & 0x3F]);
                buffer.append("=");
                break;
        }

        return buffer.toString();
    }
915007
public byte[] encryptData(PublicKey key,byte[] data)
    {
    	try {
    		if(data==null || data.length<=0)
    		{
    			return null;
    		}
			Cipher cipher=Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return cipher.doFinal(data);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
    	return null;
    }
800007
public CMSEnvelopedData encode(final byte[] messageData)
            throws MessageEncodingException {
        LOGGER.debug("Encoding pkcsPkiEnvelope");
        CMSEnvelopedDataGenerator edGenerator = new CMSEnvelopedDataGenerator();
        CMSTypedData envelopable = new CMSProcessableByteArray(messageData);
        RecipientInfoGenerator recipientGenerator;
        try {
            recipientGenerator = new JceKeyTransRecipientInfoGenerator(
                    recipient);
        } catch (CertificateEncodingException e) {
            throw new MessageEncodingException(e);
        }
        edGenerator.addRecipientInfoGenerator(recipientGenerator);
        LOGGER.debug(
                "Encrypting pkcsPkiEnvelope using key belonging to [dn={}; serial={}]",
                recipient.getSubjectDN(), recipient.getSerialNumber());

        OutputEncryptor encryptor;
        try {
            encryptor = new JceCMSContentEncryptorBuilder(encAlgId).build();
        } catch (CMSException e) {
            throw new MessageEncodingException(e);
        }
        try {
            CMSEnvelopedData pkcsPkiEnvelope = edGenerator.generate(
                    envelopable, encryptor);

            LOGGER.debug("Finished encoding pkcsPkiEnvelope");
            return pkcsPkiEnvelope;
        } catch (CMSException e) {
            throw new MessageEncodingException(e);
        }
    }
1206611
public static boolean validate(Map<String, String> resData, String encoding) {
		LogUtil.writeLog("验签处理开始");
		if (isEmpty(encoding)) {
			encoding = "UTF-8";
		}
		String signMethod = resData.get(SDKConstants.param_signMethod);
		String version = resData.get(SDKConstants.param_version);
		if (SIGNMETHOD_RSA.equals(signMethod) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
			// 获取返回报文的版本号
			if (VERSION_5_0_0.equals(version) || VERSION_1_0_0.equals(version) || VERSION_5_0_1.equals(version)) {
				String stringSign = resData.get(SDKConstants.param_signature);
				LogUtil.writeLog("签名原文：["+stringSign+"]");
				// 从返回报文中获取certId ，然后去证书静态Map中查询对应验签证书对象
				String certId = resData.get(SDKConstants.param_certId);
				LogUtil.writeLog("对返回报文串验签使用的验签公钥序列号：["+certId+"]");
				// 将Map信息转换成key1=value1&key2=value2的形式
				String stringData = coverMap2String(resData);
				LogUtil.writeLog("待验签返回报文串：["+stringData+"]");
				try {
					// 验证签名需要用银联发给商户的公钥证书.
					return SecureUtil.validateSignBySoft(CertUtil
							.getValidatePublicKey(certId), SecureUtil
							.base64Decode(stringSign.getBytes(encoding)),
							SecureUtil.sha1X16(stringData, encoding));
				} catch (UnsupportedEncodingException e) {
					LogUtil.writeErrorLog(e.getMessage(), e);
				} catch (Exception e) {
					LogUtil.writeErrorLog(e.getMessage(), e);
				}
			} else if (VERSION_5_1_0.equals(version)) {
				// 1.从返回报文中获取公钥信息转换成公钥对象
				String strCert = resData.get(SDKConstants.param_signPubKeyCert);
//				LogUtil.writeLog("验签公钥证书：["+strCert+"]");
				X509Certificate x509Cert = CertUtil.genCertificateByStr(strCert);
				if(x509Cert == null) {
					LogUtil.writeErrorLog("convert signPubKeyCert failed");
					return false;
				}
				// 2.验证证书链
				if (!CertUtil.verifyCertificate(x509Cert)) {
					LogUtil.writeErrorLog("验证公钥证书失败，证书信息：["+strCert+"]");
					return false;
				}
				
				// 3.验签
				String stringSign = resData.get(SDKConstants.param_signature);
				LogUtil.writeLog("签名原文：["+stringSign+"]");
				// 将Map信息转换成key1=value1&key2=value2的形式
				String stringData = coverMap2String(resData);
				LogUtil.writeLog("待验签返回报文串：["+stringData+"]");
				try {
					// 验证签名需要用银联发给商户的公钥证书.
					boolean result = SecureUtil.validateSignBySoft256(x509Cert
							.getPublicKey(), SecureUtil.base64Decode(stringSign
							.getBytes(encoding)), SecureUtil.sha256X16(
							stringData, encoding));
					LogUtil.writeLog("验证签名" + (result? "成功":"失败"));
					return result;
				} catch (UnsupportedEncodingException e) {
					LogUtil.writeErrorLog(e.getMessage(), e);
				} catch (Exception e) {
					LogUtil.writeErrorLog(e.getMessage(), e);
				}
			}

		} else if (SIGNMETHOD_SHA256.equals(signMethod)) {
			// 1.进行SHA256验证
			String stringSign = resData.get(SDKConstants.param_signature);
			LogUtil.writeLog("签名原文：["+stringSign+"]");
			// 将Map信息转换成key1=value1&key2=value2的形式
			String stringData = coverMap2String(resData);
			LogUtil.writeLog("待验签返回报文串：["+stringData+"]");
			String strBeforeSha256 = stringData
					+ SDKConstants.AMPERSAND
					+ SecureUtil.sha256X16Str(SDKConfig.getConfig()
							.getSecureKey(), encoding);
			String strAfterSha256 = SecureUtil.sha256X16Str(strBeforeSha256,
					encoding);
			boolean result =  stringSign.equals(strAfterSha256);
			LogUtil.writeLog("验证签名" + (result? "成功":"失败"));
			return result;
		} else if (SIGNMETHOD_SM3.equals(signMethod)) {
			// 1.进行SM3验证
			String stringSign = resData.get(SDKConstants.param_signature);
			LogUtil.writeLog("签名原文：["+stringSign+"]");
			// 将Map信息转换成key1=value1&key2=value2的形式
			String stringData = coverMap2String(resData);
			LogUtil.writeLog("待验签返回报文串：["+stringData+"]");
			String strBeforeSM3 = stringData
					+ SDKConstants.AMPERSAND
					+ SecureUtil.sm3X16Str(SDKConfig.getConfig()
							.getSecureKey(), encoding);
			String strAfterSM3 = SecureUtil
					.sm3X16Str(strBeforeSM3, encoding);
			boolean result =  stringSign.equals(strAfterSM3);
			LogUtil.writeLog("验证签名" + (result? "成功":"失败"));
			return result;
		}
		return false;
	}
839892
public static String encrypt(String secretKey, String plainText) {
        if (plainText == null) {
            return null;
        } else if (plainText.startsWith("$CRYPT::")) {
             // Avoid encrypting already encrypted text - APIMAN-1201
             return plainText;
        }
        
        byte[] encrypted;
        Cipher cipher;
        try {
            SecretKeySpec skeySpec = keySpecFromSecretKey(secretKey);
            
            cipher = Cipher.getInstance("AES"); //$NON-NLS-1$
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        try {
            encrypted = cipher.doFinal(plainText.getBytes());
        } catch (IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException(e);
        }
        return "$CRYPT::" + new String(Base64.encodeBase64(encrypted)); //$NON-NLS-1$
    }
271371
public static String encryptValueAsJwtRsaOeap256Aes256Sha512(final Key key, final Serializable value) {
        return encryptValueAsJwt(key, value, KeyManagementAlgorithmIdentifiers.RSA_OAEP_256,
            CipherExecutor.DEFAULT_CONTENT_ENCRYPTION_ALGORITHM);
    }
948346
public static String getFirstResourceId(final CacheKey key) {
    try {
      if (key instanceof MultiCacheKey) {
        List<CacheKey> keys = ((MultiCacheKey) key).getCacheKeys();
        return secureHashKey(keys.get(0));
      } else {
        return secureHashKey(key);
      }
    } catch (UnsupportedEncodingException e) {
      // This should never happen. All VMs support UTF-8
      throw new RuntimeException(e);
    }
  }
858507
public static String encryptByAES(final String content, final String key) {
        try {
            final KeyGenerator kgen = KeyGenerator.getInstance("AES");
            final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes());
            kgen.init(128, secureRandom);
            final SecretKey secretKey = kgen.generateKey();
            final byte[] enCodeFormat = secretKey.getEncoded();
            final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            final Cipher cipher = Cipher.getInstance("AES");
            final byte[] byteContent = content.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            final byte[] result = cipher.doFinal(byteContent);

            return Hex.encodeHexString(result);
        } catch (final Exception e) {
            LOGGER.log(Level.WARN, "Encrypt failed", e);

            return null;
        }
    }
205976
public static String encrypt(CharSequence data, CharSequence cipherKey) {
		final int dataLen = data.length();
		final int cipherKeyLen = cipherKey.length();

		final char[] cipherArray = new char[dataLen];
		for (int i = 0; i < dataLen / cipherKeyLen + 1; i++) {
			for (int t = 0; t < cipherKeyLen; t++) {
				if (t + i * cipherKeyLen < dataLen) {
					final char dataChar = data.charAt(t + i * cipherKeyLen);
					final char cipherKeyChar = cipherKey.charAt(t);
					cipherArray[t + i * cipherKeyLen] = (char) ((dataChar + cipherKeyChar - 64) % 95 + 32);
				}
			}
		}

		return String.valueOf(cipherArray);
	}
993775
public static String decryptByPrivateKey(String data, String privateKey, String fillMode) throws Exception {
		byte[] encryptedData = base64.decode(data);
		byte[] keyBytes = base64.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		// Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		Cipher cipher = Cipher.getInstance(fillMode);

		cipher.init(Cipher.DECRYPT_MODE, privateK);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return new String(decryptedData);
	}
923149
private byte[] doCipher(Cipher cipher, Key key, byte[] datas) {
        log.debug("开始非对称的加解密");
        RSAKey rsaKey = (RSAKey) key;

        //计算block大小
        int maxBlock = rsaKey.getModulus().bitLength() / 8;
        //加密时需要减11
        if (key instanceof RSAPublicKey) {
            maxBlock = maxBlock - 11;
        }

        log.debug("当前block大小为：[{}]，开始加/解密", maxBlock);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            for (int i = 0, offset = 0; datas.length > offset; i++, offset = maxBlock * i) {
                if (datas.length - offset > maxBlock) {
                    out.write(cipher.doFinal(datas, offset, maxBlock));
                } else {
                    out.write(cipher.doFinal(datas, offset, datas.length - offset));
                }
            }

            byte[] result = out.toByteArray();
            IOUtils.closeQuietly(out);
            return result;
        } catch (IOException | IllegalBlockSizeException | BadPaddingException e) {
            log.warn("RSA加/解密失败", e);
            throw new SecureException(e);
        }
    }
831852
public static byte[] normalizeKey(byte[] keyData) {
        if (keyData == null) {
            return RSG.generate(16).getBytes(StandardCharsets.UTF_8);
        } else {
            return normalizeKey(new String(keyData, StandardCharsets.UTF_8))
                    .getBytes(StandardCharsets.UTF_8);
        }
    }
911148
public static byte[] decrypt(byte[] data, byte[] key) {
        checkNotNull(data);
        checkNotNull(key);
        checkArgument(key.length >= 5 && key.length <= 256);
        StreamCipher rc4 = new RC4Engine();
        rc4.init(false, new KeyParameter(key));
        byte[] decrypted = new byte[data.length];
        rc4.processBytes(data, 0, data.length, decrypted, 0);
        return decrypted;
    }
882722
private static @Nullable SecretKey loadSymmetricKey(Context context, KeyPair wrapperKey) throws NoSuchPaddingException,
	                                                                                                NoSuchAlgorithmException,
	                                                                                                InvalidKeyException {
		String encryptedSymmetricKey = getKeyPrefs(context).getString(PREFS_KEY_SYMMETRIC_KEY, null);
		if (StringUtils.isNullOrEmpty(encryptedSymmetricKey)) {
			return null;
		}

		return unwrapSymmetricKey(wrapperKey, encryptedSymmetricKey);
	}