package com.framework.loippi.plugins.wxapppay.withdrawalbank;
import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.plugins.wxapppay.MD5;
import com.framework.loippi.plugins.wxapppay.MD5Util;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.springframework.util.ResourceUtils;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.security.PublicKey;
import java.util.*;
public class WeChatWithdrawalBankUtil {
private static final String TRANS_URL = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
// 微信商户appkey
private static String appKey = ConfigCache.getConfig("wx.pay.key");
// 微信商户证书路径
private static String certPath = ConfigCache.getConfig("wx.pay.ssl.pkcs12File");
// 微信支付分配的商户号
private static String mchId = ConfigCache.getConfig("wx.pay.mchId");
//证书密码
private static String sslPassword = ConfigCache.getConfig("wx.pay.ssl.password");
//pkcs1公钥路径
private static String keyfile = ConfigCache.getConfig("wx.pay.ssl.publicFile");
// 请求器的配置
private static RequestConfig requestConfig;
// 连接超时时间,默认10秒
private static int socketTimeout = 10000;
// 传输超时时间,默认30秒
private static int connectTimeout = 30000;
/**
*银行卡提现
* @param partnerTradeNo 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有其他字符) 必填
* @param encBankNo 收款方银行卡号
* @param encTrueName 收款方用户名
* @param bankCode 银行卡所在开户行编号 t_system_bank的bank_id字段
* @param amount 付款金额 单位为元 必填
* @param desc 付款备注 必填
* @return result 返回结果列子(是一个xml字符串):
* <xml>
* <return_code><![CDATA[SUCCESS]]></return_code>
* <return_msg><![CDATA[支付成功]]></return_msg>
* <result_code><![CDATA[SUCCESS]]></result_code>
* <err_code><![CDATA[SUCCESS]]></err_code>
* <err_code_des><![CDATA[微信侧受理成功]]></err_code_des>
* <nonce_str><![CDATA[50780e0cca98c8c8e814883e5caa672e]]></nonce_str>
* <mch_id><![CDATA[2302758702]]></mch_id>
* <partner_trade_no><![CDATA[1212121221278]]></partner_trade_no>
* <amount>500</amount>
* <payment_no><![CDATA[10000600500852017030900000020006012]]></payment_no>
* <cmms_amt>0</cmms_amt>
* </xml>
*判断 失败:result.contains("CDATA[FAIL]") 返回true 失败 false成功
* SAXBuilder saxBuilder = new SAXBuilder();
* Document doc = saxBuilder.build(new StringReader(result));
* 获取错误原因:return doc.getRootElement().getChild("err_code_des").getValue();
* 成功 获取交易单号:return doc.getRootElement().getChild("payment_no").getValue();
*/
public static String doTransfers(String partnerTradeNo, String encBankNo, String encTrueName,String bankCode,BigDecimal amount, String desc){
String result ="success";
try
{
String nonceStr = genNonceStr();
String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
StringBuffer pkcs1Path = new StringBuffer();
pkcs1Path.append("classpath:").append(keyfile);
PublicKey pub=RSAUtils.getPubKey(pkcs1Path.toString(),"RSA");
byte[] estr=RSAUtils.encrypt(encBankNo.getBytes(),pub,2048, 11,rsa); //对银行账号进行加密
encBankNo =WxBase64.encode(estr);//并转为base64格式
byte[] estr2=RSAUtils.encrypt(encTrueName.getBytes(),pub,2048, 11,rsa); //对银行账号进行加密
encTrueName=WxBase64.encode(estr2);//并转为base64格式
SortedMap<String, String> parameters = new TreeMap<String, String>();
parameters.put("amount", amount.multiply(new BigDecimal("100")).intValue()+"");
parameters.put("desc", desc);
parameters.put("mch_id", mchId);
parameters.put("nonce_str", nonceStr);
parameters.put("enc_bank_no", encBankNo);
parameters.put("enc_true_name", encTrueName);
parameters.put("bank_code", bankCode);
parameters.put("partner_trade_no", partnerTradeNo);
parameters.put("sign", createSign(parameters, appKey));
String data = SortedMaptoXml(parameters);
// 3.加载证书请求接口
System.out.println(data);
result = weChatWithdrawal(data);
System.out.println("------aaaaa------"+result);
}
catch (Exception e)
{
e.printStackTrace();
return "银行卡提现失败";
}
return result;
}
/**
* 证书使用
* 微信提现
*/
@SuppressWarnings("deprecation")
public static String weChatWithdrawal(String data) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
StringBuffer pkcsPath = new StringBuffer();
pkcsPath.append("classpath:").append(certPath);
System.out.println("certPath"+certPath);
InputStream instream = null;
try {
instream = ResourceUtils.getURL(pkcsPath.toString()).openStream();
} catch (IOException var10) {
}
if (instream == null) {
return null;
}
String result = "";
try {
keyStore.load(instream, sslPassword.toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, sslPassword.toCharArray())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[]{"TLSv1"},
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
try {
HttpPost httppost = new HttpPost(TRANS_URL);
StringEntity entitys = new StringEntity(data,"UTF-8");
httppost.setEntity((HttpEntity) entitys);
// 根据默认超时限制初始化requestConfig
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
// 设置请求器的配置
httppost.setConfig(requestConfig);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity,"UTF-8");
} finally {
response.close();
}
} finally {
httpclient.close();
}
return result;
}
/**
* 生成32位随机数字
*/
public static String genNonceStr() {
Random random = new Random();
return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
}
/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
public static String createSign(SortedMap<String, String> packageParams, String AppKey) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + AppKey);
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign;
}
/**
* @param params
* @Author: WQY
* @Description:请求值转换为xml格式 SortedMap转xml
* @Date: 2017-9-7 17:18
*/
private static String SortedMaptoXml(SortedMap<String, String> params) {
StringBuilder sb = new StringBuilder();
Set es = params.entrySet();
Iterator it = es.iterator();
sb.append("<xml>\n");
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
sb.append("<" + k + ">");
sb.append(v);
sb.append("</" + k + ">\n");
}
sb.append("</xml>");
return sb.toString();
}
public static void main(String[] args) {
try {
String results = WeChatWithdrawalBankUtil.doTransfers("20200921111523187","6227000131211350787","孙从刚","1003",new BigDecimal("1"),"");
System.out.println("-----" +results);
}catch(Exception e){
e.printStackTrace();
}
}
}
----------------------------------------------------------------------
package com.framework.loippi.plugins.wxapppay.withdrawalbank;
import org.springframework.util.ResourceUtils;
import javax.crypto.Cipher;
import java.io.*;
import java.lang.reflect.Method;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RSAUtils {
public static void main(String[] args) throws Exception {
String encBankAcctNo = "622202120**********"; //加密的银行账号
String encBankAcctName = "张三"; //加密的银行账户名
//注意 这里的 pksc8_public.pem 是上一步获取微信支付公钥后经openssl 转化成PKCS8格式的公钥
String keyfile = "D:/item/shunlu/dubbo-config/src/main/resources/dev/publicPKCS8.pem"; //读取PKCS8密钥文件
PublicKey pub=getPubKey(keyfile,"RSA");
String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
byte[] estr=encrypt(encBankAcctNo.getBytes("UTF-8"),pub,2048, 11,rsa); //对银行账号进行加密
encBankAcctNo =WxBase64.encode(estr);//并转为base64格式---- 调用付款需要传的 银行卡号
byte[] name=encrypt(encBankAcctName.getBytes("UTF-8"),pub,2048, 11,rsa); //对银行账号进行加密
encBankAcctName =WxBase64.encode(name);//并转为base64格式--调用付款需要传的 用户名
//将加密后的卡号和用户名 输出
System.out.println("encBankAcctNo---"+encBankAcctNo);
System.out.println("encBankAcctName---"+encBankAcctName);
}
public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {
int keyByteSize = keyLength / 8;
int decryptBlockSize = keyByteSize - reserveSize;
int nBlock = encryptedBytes.length / keyByteSize;
ByteArrayOutputStream outbuf = null;
try {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
outbuf = new ByteArrayOutputStream(nBlock * decryptBlockSize);
for (int offset = 0; offset < encryptedBytes.length; offset += keyByteSize) {
int inputLen = encryptedBytes.length - offset;
if (inputLen > keyByteSize) {
inputLen = keyByteSize;
}
byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, inputLen);
outbuf.write(decryptedBlock);
}
outbuf.flush();
return outbuf.toByteArray();
} catch (Exception e) {
throw new Exception("DEENCRYPT ERROR:", e);
} finally {
try{
if(outbuf != null){
outbuf.close();
}
}catch (Exception e){
outbuf = null;
throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);
}
}
}
public static byte[] encrypt(byte[] plainBytes, PublicKey publicKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {
int keyByteSize = keyLength / 8;
int encryptBlockSize = keyByteSize - reserveSize;
int nBlock = plainBytes.length / encryptBlockSize;
if ((plainBytes.length % encryptBlockSize) != 0) {
nBlock += 1;
}
ByteArrayOutputStream outbuf = null;
try {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
outbuf = new ByteArrayOutputStream(nBlock * keyByteSize);
for (int offset = 0; offset < plainBytes.length; offset += encryptBlockSize) {
int inputLen = plainBytes.length - offset;
if (inputLen > encryptBlockSize) {
inputLen = encryptBlockSize;
}
byte[] encryptedBlock = cipher.doFinal(plainBytes, offset, inputLen);
outbuf.write(encryptedBlock);
}
outbuf.flush();
return outbuf.toByteArray();
} catch (Exception e) {
throw new Exception("ENCRYPT ERROR:", e);
} finally {
try{
if(outbuf != null){
outbuf.close();
}
}catch (Exception e){
outbuf = null;
throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);
}
}
}
public static PrivateKey getPriKey(String privateKeyPath,String keyAlgorithm){
PrivateKey privateKey = null;
InputStream inputStream = null;
try {
if(inputStream==null){
System.out.println("hahhah1!");
}
inputStream = new FileInputStream(privateKeyPath);
privateKey = getPrivateKey(inputStream,keyAlgorithm);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null){
try {
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return privateKey;
}
public static PublicKey getPubKey(String publicKeyPath,String keyAlgorithm){
PublicKey publicKey = null;
InputStream inputStream = null;
try
{
inputStream = ResourceUtils.getURL(publicKeyPath).openStream();
publicKey = getPublicKey(inputStream,keyAlgorithm);
} catch (Exception e) {
e.printStackTrace();//EAD PUBLIC KEY ERROR
} finally {
if (inputStream != null){
try {
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return publicKey;
}
public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws Exception {
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String readLine = null;
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
org.bouncycastle.asn1.pkcs.RSAPublicKey rsaPublicKey = org.bouncycastle.asn1.pkcs.RSAPublicKey.getInstance(
org.bouncycastle.util.encoders.Base64.decode(sb.toString()));
java.security.spec.RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent());
java.security.KeyFactory keyFactory = java.security.KeyFactory.getInstance(keyAlgorithm);
//下行出错 java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=127, too big.
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return publicKey;
} catch (Exception e) {
e.printStackTrace();
throw new Exception("READ PUBLIC KEY ERROR:", e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
inputStream = null;
throw new Exception("INPUT STREAM CLOSE ERROR:", e);
}
}
}
public static PrivateKey getPrivateKey(InputStream inputStream, String keyAlgorithm) throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String readLine = null;
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') {
continue;
} else {
sb.append(readLine);
sb.append('\r');
}
}
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decodeBase64(sb.toString()));
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
return privateKey;
} catch (Exception e) {
throw new Exception("READ PRIVATE KEY ERROR:" ,e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
inputStream = null;
throw new Exception("INPUT STREAM CLOSE ERROR:", e);
}
}
}
//一下面是base64的编码和解码
public static String encodeBase64(byte[]input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, new Object[]{input});
return (String)retObj;
}
/***
* decode by Base64
*/
public static byte[] decodeBase64(String input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, input);
return (byte[])retObj;
}
}
-------------------------------------------------------------------------
package com.framework.loippi.plugins.wxapppay.withdrawalbank;
/**
* base64加密工具类
*/
public class WxBase64 {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println("number of triplets = " + numberTriplets);
}
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug) {
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
}
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
if (fDebug) {
System.out.println("val2 = " + val2);
System.out.println("k4 = " + (k << 4));
System.out.println("vak = " + (val2 | (k << 4)));
}
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug) {
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1 >> 2));
}
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;//should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}//if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
return null;//if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)//last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)//last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { //No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
-------------------------------------------------------------
package com.framework.loippi.plugins.wxapppay.withdrawalbank;
//import java.io.IOException;
//import java.io.StringReader;
import java.io.StringWriter;
//import java.security.KeyFactory;
//import java.security.PrivateKey;
//import java.security.Security;
//import java.security.interfaces.RSAPrivateCrtKey;
//import java.security.spec.EncodedKeySpec;
//import java.security.spec.InvalidKeySpecException;
//import java.security.spec.PKCS8EncodedKeySpec;
//import java.security.spec.RSAPrivateKeySpec;
//import java.util.List;
//import org.bouncycastle.asn1.ASN1Encodable;
import com.loippi.core.gen.utils.StringUtils;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
//import org.bouncycastle.asn1.ASN1Primitive;
//import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
//import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.util.io.pem.PemObject;
//import org.bouncycastle.util.io.pem.PemReader;
import org.bouncycastle.util.io.pem.PemWriter;
//import org.bouncycastle.openssl.MiscPEMGenerator;
//import org.bouncycastle.openssl.PKCS8Generator;
//import com.ctrip.lzyan.test.cipher.cscm.RsaPemUtil;
//import com.google.common.base.Joiner;
//import com.google.common.base.Splitter;
//import com.google.common.base.Strings;
//import com.google.common.collect.Lists;
import org.apache.commons.codec.binary.Base64;
/**
* Transform PKCS format
* PKCS#1 -> PKCS#8
* PKCS#8 -> PKCS#1
*
*/
public class RsaPkcsTransformer {
// private static final String COMMENT_BEGIN_FLAG = "-----";
// private static final String RETURN_FLAG_R = "\r";
// private static final String RETURN_FLAG_N = "\n";
//format PKCS#8 to PKCS#1
public static String formatPkcs8ToPkcs1(String rawKey) throws Exception {
String result = null;
//extract valid key content
String validKey = rawKey;//RsaPemUtil.extractFromPem(rawKey); // pem文件多行合并为一行
// if(!Strings.isNullOrEmpty(validKey))
if (!StringUtils.isEmpty(validKey))
{
//将BASE64编码的私钥字符串进行解码
byte[] encodeByte = Base64.decodeBase64(validKey);
//==========
//pkcs8Bytes contains PKCS#8 DER-encoded key as a byte[]
PrivateKeyInfo pki = PrivateKeyInfo.getInstance(encodeByte);
RSAPrivateKeyStructure pkcs1Key = RSAPrivateKeyStructure.getInstance(pki.getPrivateKey());
byte[] pkcs1Bytes = pkcs1Key.getEncoded();//etc.
//==========
String type = "RSA PRIVATE KEY";
result = format2PemString(type, pkcs1Bytes);
}
return result;
}
//format PKCS#1 to PKCS#8
public static String formatPkcs1ToPkcs8(String rawKey) throws Exception {
String result = null;
//extract valid key content
String validKey = rawKey;//RsaPemUtil.extractFromPem(rawKey); // pem文件多行合并为一行
// if(!Strings.isNullOrEmpty(validKey))
if (!StringUtils.isEmpty(validKey))
{
//将BASE64编码的私钥字符串进行解码
byte[] encodeByte = Base64.decodeBase64(validKey);
AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(PKCSObjectIdentifiers.pkcs8ShroudedKeyBag); //PKCSObjectIdentifiers.pkcs8ShroudedKeyBag
// ASN1Object asn1Object = ASN1Object.fromByteArray(encodeByte);
ASN1Object asn1Object = ASN1ObjectIdentifier.fromByteArray(encodeByte);
PrivateKeyInfo privKeyInfo = new PrivateKeyInfo(algorithmIdentifier, asn1Object);
byte[] pkcs8Bytes = privKeyInfo.getEncoded();
String type = "PRIVATE KEY";
// result = format2PemString(type, pkcs8Bytes); // 格式化为pem多行格式输出
return Base64.encodeBase64String(pkcs8Bytes); // 直接一行字符串输出
}
return result;
}
// Write to pem file
// 字符串换行显示
private static String format2PemString(String type, byte[] privateKeyPKCS1) throws Exception {
PemObject pemObject = new PemObject(type, privateKeyPKCS1);
StringWriter stringWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(stringWriter);
pemWriter.writeObject(pemObject);
pemWriter.close();
String pemString = stringWriter.toString();
return pemString;
}
//=== Testing ===
public static void main(String[] args) throws Exception {
String rawKey_pkcs1 = "";
String rawKey_pkcs8 = "";
rawKey_pkcs1 = "MIIBCgKCAQEAtZr8QLrHAzGlkWJBLgWNANTklzsZDCmptBAe/1uZiCIwV/GX9oWbDxd2WsczA5TenOVOLs0DWZVqgp07uqKSlfT6ujslVQ+RDgWhY2ZBq4koKmQOjbcx5cNG/ameIAMXLGmXiU8EWm48naqxCvkUjZzeW2okN/dLCvi8b6mkJ6GYWB9jNfk5/8I+Bu8GTgpsNt3MEnUDCQPjMnxdr44OxH2AHvQJ6zHHJMZyNrfMh/8CWyb1vb1ElCzr10Zy5URRa7r98Ne6ejZC8nV7C5OzDNil7ktuqEnwIDAQAB";
// rawKey_pkcs8 = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOAPGRrVTxJYZKfl9TBvScnX4l5dEDomwMQqk40miMhsXad+Actaw2fhvOflZ5tzpZkvHQbItNC5kZp0VW5WrZ1CoSyursfAgMBAAECgYBi1oYujhZZc3LAnOUT6QJvB00BT+Qv0VZi1P/k/vM0Jmde1OlYiLkZT5Cl+/OaUB+rqo/7fDvvCAbz+oZCx3yAa7ebJ2LQiaYP2wl2GGwm5ZmEIwz6qa9Ka8b+C8iv5t0SY+GkJClrcEu95SQUMD86fB9NUvqu7BlrIzO5OgHpYQJBAPrcbH0NlWFihLFHupKaIZ/9ON84m6xNyuZzbtnlfkxLfprdTH1n5z0RpgWV1ndw/M/nbW6A1W9l2i8qoUohxDkCQQDkph4oFWWSstpqZIS7lYBfcOonqINGoSPMyhVp3kHUjuQkc742KNTE0dpZpKos4e6Tftf4QCNJOjPPA6QrBuoXAkEAzU2GEBYE0e1x0TB11bMEn836NF08shf8XPvNldBGu6PxWkaQafWV/pmp+No26gtzK6coHQ6dHo0Jsh4+X9AgqQJAaARCN830FVaUEk6EK6oJamG9xCje/6SS2rkcILthi0ct9n9JCu5sTNWC1cEZQa3OkP7lVSQoaUm3A/gOGRzeJQJBALCIUq5B7852WRiTUviZvQfR/PL7/qZjHJSqlNdTD/oFUM7KjC/OJ6H2iHZmGdBLtg8FbPllfPBQfhhXAarGLAA=";
String formatKey1 = formatPkcs1ToPkcs8(rawKey_pkcs1);
// String formatKey2 = formatPkcs8ToPkcs1(rawKey_pkcs8);
System.out.println(formatKey1);
//System.out.println(formatKey2);
}
}