RSA签名验签

Posted L先森

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了RSA签名验签相关的知识,希望对你有一定的参考价值。

import android.util.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * Author:JsonLu
 * DateTime:2016/6/23 19:50
 * Email:[email protected]
 * Desc:RSA签名验签工具类
 **/
public class RSAUtil {
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    //私钥 PKCS8格式
    private static final String SUMPAY_PAYMENT_PRIVATE_KEY = "";
    private static final String SUMPAY_PAYMENT_SERVER_PUBLIC_KEY = "";

    /**
     * RSA签名
     *
     * @param content       待签名数据
     * @param input_charset 编码格式
     * @return 签名值
     */
    public static String sign(String content, String input_charset) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(SUMPAY_PAYMENT_PRIVATE_KEY, Base64.DEFAULT));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(content.getBytes(input_charset));
            byte[] signed = signature.sign();
            return Base64.encodeToString(signed, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * RSA验签名检查
     *
     * @param content       待签名数据
     * @param sign          签名值
     * @param input_charset 编码格式
     * @return 布尔值
     */
    public static boolean verify(String content, String sign, String input_charset) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(SUMPAY_PAYMENT_SERVER_PUBLIC_KEY, Base64.DEFAULT);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
            signature.initVerify(pubKey);
            signature.update(content.getBytes(input_charset));
            boolean bverify = signature.verify(Base64.decode(sign, Base64.DEFAULT));
            return bverify;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

 

以上是关于RSA签名验签的主要内容,如果未能解决你的问题,请参考以下文章

iOS小技能:RSA签名验签加密解密的原理

iOS小技能:RSA签名验签加密解密的原理

RSA签名验签

java rsa 签名,验签

RSA后台签名前台验签的应用(前台采用jsrsasign库)

Java实现RSA 加密解密签名验签的工具类复制粘贴直接用