RSA签名

RSA签名:

 

/**
 * RSA签名
 * @param content    待签名数据
 * @param privateKey 商户私钥
 * @return 签名值
 */
public static String sign(String content, String privateKey) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
        java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");
        signature.initSign(priKey);
        signature.update(content.getBytes("UTF8"));
        byte[] signed = signature.sign();
        return new BASE64Encoder().encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

 

 

RSA签名校验:

  /**

     * RSA验签名检查

     * @param content   待签名数据

     * @param sign      签名值

     * @param publicKey 分配给开发商公钥

     * @return 布尔值

     */

    public static boolean doCheck(String content, String sign, String publicKey) {

        try {

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            byte[] encodedKey = new BASE64Decoder().decodeBuffer(publicKey);

            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");

            signature.initVerify(pubKey);

            signature.update(content.getBytes("UTF8"));

            boolean bverify = signature.verify(new BASE64Decoder().decodeBuffer(sign));

            return bverify;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return false;

    }

posted @ 2018-08-17 10:06  walle1314  阅读(298)  评论(0编辑  收藏  举报