关于微信新出的企业付款到银行卡API的问题(二)

按照微信企业付款到银行卡接口文档,调用转账接口后,返回的XML:


<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[支付失败]]></return_msg><result_code><![CDATA[FAIL]]></result_code><err_code><![CDATA[PARAM_ERROR]]></err_code><err_code_des><![CDATA[参数错误:未输入省份或城市信息]]></err_code_des><nonce_str><![CDATA[45eeaf49882e4d40b72112c748f84fa3]]></nonce_str><mch_id><![CDATA[1486000000]]></mch_id><partner_trade_no><![CDATA[7ea298da4450439c96190d9f9614a770]]></partner_trade_no><amount>10000</amount></xml>


 目前我的问题仍没有解决,我把我实现的主要代码和过程贴出来,大家交流下,问题出在哪里。
第一步,获取微信公钥,调用https://fraud.mch.weixin.qq.com/risk/getpublickey 接口,返回的是
-----BEGIN RSA PUBLIC KEY----- 开头的字符串,将此字符串存为文件,例如文件名为wx_pubkey2048.pem (PKCS#1格式)。
第二步:
将PKCS#1格式文件转换为 PKCS#8格式,使用下面的命令:
openssl rsa -RSAPublicKey_in -in wx_pubkey2048.pem -pubout
此命令会生成-----BEGIN PUBLIC KEY-----开头,-----END PUBLIC KEY-----结尾的字符串,将字符串建立一个新文件例如ps8.pem存储起来,
-----BEGIN PUBLIC KEY----- 是第一行 ,-----END PUBLIC KEY-----是末尾一行,中间是一长串字符串。
第三步,我从网上抄了一个RSA的程序,出处忘记了,大家参考一下:
package org.openjweb.core.util;
import java.io.BufferedReader;  
import java.io.BufferedWriter;  
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileReader;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.security.InvalidKeyException;  
import java.security.KeyFactory;  
import java.security.KeyPair;  
import java.security.KeyPairGenerator;  
import java.security.NoSuchAlgorithmException;  
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;  
  
import java.security.interfaces.RSAPrivateKey;  
import java.security.interfaces.RSAPublicKey;  
import java.security.spec.InvalidKeySpecException;  
import java.security.spec.PKCS8EncodedKeySpec;  
import java.security.spec.X509EncodedKeySpec;  
  
import javax.crypto.BadPaddingException;  
import javax.crypto.Cipher;  
import javax.crypto.IllegalBlockSizeException;  
import javax.crypto.NoSuchPaddingException;  
//http://blog.csdn.net/wangqiuyun/article/details/42143957
public class RSAUtil 
{

/** 
     * 字节数据转字符串专用集合 
     */  
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',  
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };  
    
    
    /** 
     * 随机生成密钥对 
     */  
    public static void genKeyPair(String filePath) {  
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象  
        KeyPairGenerator keyPairGen = null;  
        try {  
            keyPairGen = KeyPairGenerator.getInstance("RSA");  
        } catch (NoSuchAlgorithmException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        // 初始化密钥对生成器,密钥大小为96-1024位  
        keyPairGen.initialize(1024,new SecureRandom());  
        // 生成一个密钥对,保存在keyPair中  
        KeyPair keyPair = keyPairGen.generateKeyPair();  
        // 得到私钥  
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();  
        // 得到公钥  
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  
        try {  
            // 得到公钥字符串  
            String publicKeyString = Base64.encode(publicKey.getEncoded());  
            // 得到私钥字符串  
            String privateKeyString = Base64.encode(privateKey.getEncoded());  
            // 将密钥对写入到文件  
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");  
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");  
            BufferedWriter pubbw = new BufferedWriter(pubfw);  
            BufferedWriter pribw = new BufferedWriter(prifw);  
            pubbw.write(publicKeyString);  
            pribw.write(privateKeyString);  
            pubbw.flush();  
            pubbw.close();  
            pubfw.close();  
            pribw.flush();  
            pribw.close();  
            prifw.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    
/** 
     * 从字符串中加载公钥 
     *  
     * @param publicKeyStr 
     *            公钥数据字符串 
     * @throws Exception 
     *             加载公钥时产生的异常 
     */  
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)  
            throws Exception {  
        try {  
        System.out.println("公钥串:::");
        System.out.println(publicKeyStr);
            byte[] buffer = Base64.decode(publicKeyStr);  
           // KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            //RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING 无此算法
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);  
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("公钥非法");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥数据为空");  
        }  
    }  
    
    /** 
     * 从文件中输入流中加载公钥 
     *  
     * @param in 
     *            公钥输入流 
     * @throws Exception 
     *             加载公钥时产生的异常 
     */  
    public static String loadPublicKeyByFile(String path) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(path  
                    + "/publicKey.keystore"));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("公钥数据流读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("公钥输入流为空");  
        }  
    }  
    
    /** 
     * 从文件中加载私钥 
     *  
     * @param keyFileName 
     *            私钥文件名 
     * @return 是否成功 
     * @throws Exception 
     */  
    public static String loadPrivateKeyByFile(String path) throws Exception {  
        try {  
            BufferedReader br = new BufferedReader(new FileReader(path  
                    + "/privateKey.keystore"));  
            String readLine = null;  
            StringBuilder sb = new StringBuilder();  
            while ((readLine = br.readLine()) != null) {  
                sb.append(readLine);  
            }  
            br.close();  
            return sb.toString();  
        } catch (IOException e) {  
            throw new Exception("私钥数据读取错误");  
        } catch (NullPointerException e) {  
            throw new Exception("私钥输入流为空");  
        }  
    }  
  
    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)  
            throws Exception {  
        try {  
            byte[] buffer = Base64.decode(privateKeyStr);  
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");  
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此算法");  
        } catch (InvalidKeySpecException e) {  
            throw new Exception("私钥非法");  
        } catch (NullPointerException e) {  
            throw new Exception("私钥数据为空");  
        }  
    }  
    /** 
     * 公钥加密过程 
     *  
     * @param publicKey 
     *            公钥 
     * @param plainTextData 
     *            明文数据 
     * @return 
     * @throws Exception 
     *             加密过程中的异常信息 
     */  
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)  
            throws Exception {  
        if (publicKey == null) {  
            throw new Exception("加密公钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
            // byte[] estr=encrypt(str.getBytes(),pub,2048, 11,"RSA/ECB/PKCS1Padding");  
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
            byte[] output = cipher.doFinal(plainTextData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此加密算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("加密公钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("明文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("明文数据已损坏");  
        }  
    }  
  
    /** 
     * 私钥加密过程 
     *  
     * @param privateKey 
     *            私钥 
     * @param plainTextData 
     *            明文数据 
     * @return 
     * @throws Exception 
     *             加密过程中的异常信息 
     */  
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)  
            throws Exception {  
        if (privateKey == null) {  
            throw new Exception("加密私钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);  
            byte[] output = cipher.doFinal(plainTextData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此加密算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("加密私钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("明文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("明文数据已损坏");  
        }  
    }  
  
    /** 
     * 私钥解密过程 
     *  
     * @param privateKey 
     *            私钥 
     * @param cipherData 
     *            密文数据 
     * @return 明文 
     * @throws Exception 
     *             解密过程中的异常信息 
     */  
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)  
            throws Exception {  
        if (privateKey == null) {  
            throw new Exception("解密私钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.DECRYPT_MODE, privateKey);  
            byte[] output = cipher.doFinal(cipherData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此解密算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("解密私钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("密文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("密文数据已损坏");  
        }  
    }  
  
    /** 
     * 公钥解密过程 
     *  
     * @param publicKey 
     *            公钥 
     * @param cipherData 
     *            密文数据 
     * @return 明文 
     * @throws Exception 
     *             解密过程中的异常信息 
     */  
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)  
            throws Exception {  
        if (publicKey == null) {  
            throw new Exception("解密公钥为空, 请设置");  
        }  
        Cipher cipher = null;  
        try {  
            // 使用默认RSA  
            cipher = Cipher.getInstance("RSA");  
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());  
            cipher.init(Cipher.DECRYPT_MODE, publicKey);  
            byte[] output = cipher.doFinal(cipherData);  
            return output;  
        } catch (NoSuchAlgorithmException e) {  
            throw new Exception("无此解密算法");  
        } catch (NoSuchPaddingException e) {  
            e.printStackTrace();  
            return null;  
        } catch (InvalidKeyException e) {  
            throw new Exception("解密公钥非法,请检查");  
        } catch (IllegalBlockSizeException e) {  
            throw new Exception("密文长度非法");  
        } catch (BadPaddingException e) {  
            throw new Exception("密文数据已损坏");  
        }  
    }  
    
    /** 
     * 字节数据转十六进制字符串 
     *  
     * @param data 
     *            输入数据 
     * @return 十六进制内容 
     */  
    public static String byteArrayToString(byte[] data) {  
        StringBuilder stringBuilder = new StringBuilder();  
        for (int i = 0; i < data.length; i++) {  
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移  
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);  
            // 取出字节的低四位 作为索引得到相应的十六进制标识符  
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);  
            if (i < data.length - 1) {  
                stringBuilder.append(' ');  
            }  
        }  
        return stringBuilder.toString();  
    }  
    
  
    
    public static void main1(String[] args) throws Exception
    {
    /*用标准的RSA加密库对敏感信息进行加密,选择RSA_PKCS1_OAEP_PADDING填充模式
        (eg:Java的填充方式要选 " RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING")
        4、 得到进行rsa加密并转base64之后的密文*/
    System.out.println("--------------公钥加密私钥解密过程-------------------");  
        String plainText="ihep_公钥加密私钥解密";  
        String filepath ="";
        //公钥加密过程  
        byte[] cipherData=RSAUtil.encrypt(RSAUtil.loadPublicKeyByStr(RSAUtil.loadPublicKeyByFile(filepath)),plainText.getBytes());  
        String cipher=Base64.encode(cipherData);  
        //私钥解密过程  
        byte[] res=RSAUtil.decrypt(RSAUtil.loadPrivateKeyByStr(RSAUtil.loadPrivateKeyByFile(filepath)), Base64.decode(cipher));  
        String restr=new String(res);  
        System.out.println("原文:"+plainText);  
        System.out.println("加密:"+cipher);  
        System.out.println("解密:"+restr);  
        System.out.println();  
          
        System.out.println("--------------私钥加密公钥解密过程-------------------");  
        plainText="ihep_私钥加密公钥解密";  
        //私钥加密过程  
        cipherData=RSAUtil.encrypt(RSAUtil.loadPrivateKeyByStr(RSAUtil.loadPrivateKeyByFile(filepath)),plainText.getBytes());  
        cipher=Base64.encode(cipherData);  
        //公钥解密过程  
        res=RSAUtil.decrypt(RSAUtil.loadPublicKeyByStr(RSAUtil.loadPublicKeyByFile(filepath)), Base64.decode(cipher));  
        restr=new String(res);  
        System.out.println("原文:"+plainText);  
        System.out.println("加密:"+cipher);  
        System.out.println("解密:"+restr);  
        System.out.println();  
          
        System.out.println("---------------私钥签名过程------------------");  
        String content="ihep_这是用于签名的原始数据";  
        String signstr=RSASignature.sign(content,RSAUtil.loadPrivateKeyByFile(filepath));  
        System.out.println("签名原串:"+content);  
        System.out.println("签名串:"+signstr);  
        System.out.println();  
          
        System.out.println("---------------公钥校验签名------------------");  
        System.out.println("签名原串:"+content);  
        System.out.println("签名串:"+signstr);  
          
        System.out.println("验签结果:"+RSASignature.doCheck(content, signstr, RSAUtil.loadPublicKeyByFile(filepath)));  
        System.out.println();  
     
          
    }  
    //新版
    
    
    public static void main(String[] args) throws Exception {  
        // TODO Auto-generated method stub  
        PrivateKey pri=getPriKey("/Users/cqx/bh_pkcs8_rsa_private_key_2048.pem","RSA");  
        PublicKey pub=getPubKey("/Users/cqx/rsa_public_key_2048.pem","RSA");  
        System.out.println("hahhahah11");  
        String str="我是需要传递的字符串";  
        byte[] estr=encrypt(str.getBytes(),pub,2048, 11,"RSA/ECB/PKCS1Padding");  
        System.out.println(new String(estr));  
        System.out.println("hahhahah12");  
        byte[] dstr=decrypt(estr, pri, 2048, 11, "RSA/ECB/PKCS1Padding");  
        System.out.println(new String(dstr));  
          
    }  
    
    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);  
            System.out.println("hahhah2!");  
            privateKey = getPrivateKey(inputStream,keyAlgorithm);  
            System.out.println("hahhah3!");  
        } catch (Exception e) {  
            System.out.println("加载私钥出错!");  
        } finally {  
            if (inputStream != null){  
                try {  
                    inputStream.close();  
                }catch (Exception e){  
                    System.out.println("加载私钥,关闭流时出错!");  
                }  
            }  
        }  
        return privateKey;  
    }  
    public static PublicKey getPubKey(String publicKeyPath,String keyAlgorithm){  
        PublicKey publicKey = null;  
        InputStream inputStream = null;  
        try 
        {
        System.out.println("getPubkey 1......");
              
            inputStream = new FileInputStream(publicKeyPath);  
            System.out.println("getPubkey 2......");
               
            publicKey = getPublicKey(inputStream,keyAlgorithm);  
            System.out.println("getPubkey 3......");
              
        } catch (Exception e) {  
            
            e.printStackTrace();//EAD PUBLIC KEY ERROR
            System.out.println("加载公钥出错!");  
        } finally {  
            if (inputStream != null){  
                try {  
                    inputStream.close();  
                }catch (Exception e){  
                    System.out.println("加载公钥,关闭流时出错!");  
                }  
            }  
        }  
        return publicKey;  
    }  
    public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws Exception {  
        try 
        {
        System.out.println("b1.........");
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
            System.out.println("b2.........");
            StringBuilder sb = new StringBuilder();  
            String readLine = null;
            System.out.println("b3.........");
            while ((readLine = br.readLine()) != null) {  
                if (readLine.charAt(0) == '-') {  
                    continue;  
                } else {  
                    sb.append(readLine);  
                    sb.append('\r');  
                }  
            }  
            System.out.println("b4.........");
            X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(decodeBase64(sb.toString()));  
            System.out.println("b5.........");
            KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);
            System.out.println("b6.........");
            //下行出错  java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: DerInputStream.getLength(): lengthTag=127, too big.
            PublicKey publicKey = keyFactory.generatePublic(pubX509);  
            System.out.println("b7.........");
            return publicKey;  
        } catch (Exception e) {  
        e.printStackTrace();
        System.out.println("b8.........");
            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');  
                    }  
                }  
                System.out.println("hahhah4!"+decodeBase64(sb.toString()));  
                PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decodeBase64(sb.toString()));  
                System.out.println("hahhah5!");  
                KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);  
                System.out.println("hahhah6!");  
                PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);  
                System.out.println("hahhah7!");  
                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;    
        }    
  
}


第四步:


                String s1 = "";
String url = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
 
String encBankAcctNo = ""; //加密的银行账号
String encBankAcctName = ""; //加密的银行账户名
 
String keyfile = "/usr/local/cert/ps8.pem"; //读取PKCS8密钥文件
                PublicKey pub=RSAUtil.getPubKey(keyfile,"RSA");  
                String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
byte[] estr=RSAUtil.encrypt(bankAcctNo.getBytes(),pub,2048, 11,rsa);   //对银行账号进行加密
encBankAcctNo =Base64.encode(estr);//并转为base64格式
                estr=RSAUtil.encrypt(bankAcctName.getBytes("UTF-8"),pub,2048, 11,rsa);  
encBankAcctName = Base64.encode(estr); //对银行账户名加密并转为base64


                SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
parameters.put("mch_id", "微信支付商户号");//商户号
parameters.put("partner_trade_no", partnerTradeNo);//结算单号,比如日结的汇总单的rowId,测试随便赋值一个
parameters.put("nonce_str",StringUtil.getUUID());//随机字符串
parameters.put("enc_bank_no",encBankAcctNo); //加密的银行账号并Base64转码
parameters.put("enc_true_name",encBankAcctName); //加密的银行账户名并Base64转码
parameters.put("bank_code",bankCode); //银行编号
parameters.put("amount",String.valueOf(payCoin));//支付金额以分为单位
parameters.put("desc",payDesc);//以分为单位
parameters.put("account_type", "1");//微信文档的参数表格没写这个参数,但xml示例中写了,去掉这个参数好像调用出现签名错误,必须加上,但含义不明确
parameters.put("bank_note", "招商银行北京大运村支行");




String sign = CommonUtil.createSign("UTF-8", acctEnt.getAccountId(),parameters);//  我个人产品的微信签名工具,这个不存在问题
parameters.put("sign", sign);//设置签名
xml = CommonUtil.getRequestXml(parameters);//我个人产品的微信xml打包工具,生成xml串。
System.out.println("xml:::");
System.out.println(xml);
String xml1 = RedBagUtil.httpsRequest(url,"POST",xml,acctEnt.getAccountId(),acctEnt.getPartnerId());//个人产品的向微信提交xml调用的工具。


                最后返回的是:
                <xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[支付失败]]></return_msg><result_code><![CDATA[FAIL]]></result_code><err_code><![CDATA[PARAM_ERROR]]></err_code><err_code_des><![CDATA[参数错误:未输入省份或城市信息]]></err_code_des><nonce_str><![CDATA[45eeaf49882e4d40b72112c748f84fa3]]></nonce_str><mch_id><![CDATA[1486000000]]></mch_id><partner_trade_no><![CDATA[7ea298da4450439c96190d9f9614a770]]></partner_trade_no><amount>10000</amount></xml>


      失败的原因是RSA调用存在问题,还是真的是缺少省份或城市信息啊?微信参数中没有城市参数。请教下接口调通的朋友,你们的接口参数传了哪些,是不是我的漏了,还是我找的RSA算法有问题?按理说,如果RSA加密参数有问题,微信是不能正常解析出正确的银行卡号和账户名的,会报卡号和账户名错误的问题。
       



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值