外部支付-生成通道公钥

更新时间:2024-09-03 16:05

签名算法介绍:

RSA2是在原来SHA1WithRSA签名算法的基础上,新增了支持SHA256WithRSA的签名算法,该算法在摘要算法上比SHA1WithRSA有更强的安全能力,官方建议使用SHA256WithRSA的签名算法,接下来就来讲一下如何使用rsa2进行签名验签与公私钥生成。


生成公钥后,在【支付管理】-【收款配置】,选择相应的场景(比如微信小程序),【外部支付】中需要配置到【通道公钥】中:


生成RSA2公私钥对、加签、验签的方法:

JAVA的方式:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>{latest.version}</version>
</dependency>


生成公私钥对和加签、验签:

    /**
     * 生成公私钥
     */
    public static Map<String, String> generateRSA2Key() {
        Map<String, String> pubPriKey = new HashMap<>();
        KeyPair keyPair = KeyUtil.generateKeyPair(SIGN_TYPE, KEY_SIZE);
        String publicKeyStr =
 Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKeyStr =
 Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
        pubPriKey.put("publicKey", publicKeyStr);
        pubPriKey.put("privateKey", privateKeyStr);
        return pubPriKey;
    }

    /**
     * RSA2签名
     * @param privateKey
     * @param content
     * @return
     */
    public static String sign256(String privateKey, String content) {
        try {
            PKCS8EncodedKeySpec keySpec = new
 PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(privateKey));
            KeyFactory keyFactory =
 KeyFactory.getInstance(SIGN_TYPE);
            PrivateKey priKey = keyFactory.generatePrivate(keySpec);
            Signature signature =
 Signature.getInstance(SignAlgorithm.SHA256withRSA.getValue());
            signature.initSign(priKey);
            signature.update(content.getBytes("UTF-8"));
            byte[] signed = signature.sign();
            return
 org.apache.commons.codec.binary.Base64.encodeBase64String(signed);
        } catch (Exception e) {
            throw new RuntimeException("RSA sign error", e);
        }
    }
    /**
     * RSA2验签
     * @param publicKey
     * @param content
     * @param sign
     * @return
     */
    public static boolean verify256(String publicKey, String content, String sign) {
        try {
            KeyFactory keyFactory =
 KeyFactory.getInstance(SIGN_TYPE);
            byte[] encodedKey =
 org.apache.commons.codec.binary.Base64.decodeBase64(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            Signature signature =
 Signature.getInstance(SignAlgorithm.SHA256withRSA.getValue());
            signature.initVerify(pubKey);
            signature.update(content.getBytes("UTF-8"));
            return
 signature.verify(org.apache.commons.codec.binary.Base64.decodeBase64(sign));
        } catch (Exception e) {
            throw new RuntimeException("RSA verify error", e);
        }
    }


注意:

开放平台支持的签名算法

RSA2(SHA256WithRSA):强制要求RSA密钥的长度至少为2048.

RSA2 加密算法默认生成格式为 PKCS8(Java 适用)

Copyright(C)2023 HFBangFu Inc. All Rights Reserved 皖ICP备12017563号-5
收缩