RSA簽名

RSA簽名:java

 

/**
 * 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;
}spa

 

 

RSA簽名校驗:code

  /**開發

     * RSA驗簽名檢查get

     * @param content   待簽名數據it

     * @param sign      簽名值io

     * @param publicKey 分配給開發商公鑰date

     * @return 布爾值數據

     */static

    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;

    }

相關文章
相關標籤/搜索