1. 程式人生 > >微信支付 獲取RSA加密公鑰API JAVA版

微信支付 獲取RSA加密公鑰API JAVA版

UC val XML nonce 其中 final stack tps 下載

近做微信支付 企業付款到銀行卡,其中收款方銀行卡號、收款方用戶名需要獲取RSA加密公鑰API進行加密;本文以windows為例;

微信開發文檔地址:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_7&index=4

openssl下載地址:http://slproweb.com/products/Win32OpenSSL.html

技術分享圖片 

獲取接口:

技術分享圖片

首先要通過接口獲取PKCS#1格式的公鑰,再轉為PKCS#8格式;

獲取PKCS#1格式的公鑰代碼如下:

    // 獲取RSA加密公鑰API地址
    private final static String PUBLIC_KEY_URL = "https://fraud.mch.weixin.qq.com/risk/getpublickey";

    // 證書位置
    private final static String CertPath = "D:/apiclient_cert.p12";
  
    /**
     * 獲取公鑰 PKCS#1
     * 
     * @return
     */
    public static String getPublicKey() {
        SortedMap<String, String> sortedMap = new TreeMap<String, String>();
        sortedMap.put("mch_id", MCH_ID);
        sortedMap.put("nonce_str", RandomNumber.getNonceStr());
        sortedMap.put("sign_type", "MD5");
        sortedMap.put("sign", createSign(sortedMap));
        String requestXML = XMLUtil.getRequestXml(sortedMap);
        String resultXML = CertHttpUtil.postData(PUBLIC_KEY_URL, requestXML, MCH_ID, CertPath);
        return resultXML;
    }

  

生成noceStr:

    /**
     * 生成NonStr 雪花算法
     * 
     * @return
     * @throws Exception
     */
    public static String getNonceStr() {
        Integer workId = Integer.valueOf(1);
        IdWorker idWork = new IdWorker(workId);
        String nonceStr = "";
        try {
            nonceStr =  workId + String.valueOf(idWork.nextId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nonceStr;
    } 

執行getPublicKey方法,得到反饋的XML,其中pub_key是PSCK#1公鑰,將pub_key保存

技術分享圖片

新建個PKCS1.pem, 將上面的pub_key保存

技術分享圖片

技術分享圖片

dos命令進入到openssl的bin目錄下:

技術分享圖片

技術分享圖片

執行PKCS#1轉PKCS#8命令:

openssl rsa -RSAPublicKey_in -in D:\cert\weChatApp\PKCS1.pem -pubout

技術分享圖片

新建個PSCK8文件,將生成的KEY保存

技術分享圖片

技術分享圖片

這樣就完成了 PKCS#1轉PKCS#8 獲取RSA加密公鑰

技術分享圖片

微信支付 獲取RSA加密公鑰API JAVA版