RSA Java Demo

简介

  • 主要参考Oracle官方文档

资料列表

入门示例

  • 需要的包
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
  • 一个方法看懂
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException,
            InvalidKeyException, SignatureException, UnsupportedEncodingException {
        // 生成秘钥
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.initialize(2048, random);
        KeyPair pair = keyGen.generateKeyPair();

        PrivateKey priv = pair.getPrivate();
        PublicKey pub = pair.getPublic();

        String privStr = Base64.getEncoder().encodeToString(priv.getEncoded());
        String pubStr = Base64.getEncoder().encodeToString(pub.getEncoded());

        // 字符串转秘钥对象
        PrivateKey privKey = getPrivateKey(privStr);
        PublicKey pubKey = getPublicKey(pubStr);

        String plaintext = "私钥签名测试";
        // 私钥签名
        Signature rsaPrivSig = Signature.getInstance("SHA1withRSA");
        rsaPrivSig.initSign(privKey);
        rsaPrivSig.update(plaintext.getBytes("UTF-8"));
        byte[] privSign = rsaPrivSig.sign();
        String privSignStr = Base64.getEncoder().encodeToString(privSign);

        // 公钥验签
        Signature rsaPubSig = Signature.getInstance("SHA1withRSA");
        rsaPubSig.initVerify(pubKey);
        rsaPubSig.update(plaintext.getBytes("UTF-8"));
        boolean verifies = rsaPubSig.verify(Base64.getDecoder().decode(privSignStr));
        System.out.println("signature verifies: " + verifies);
    }

简单工具类

  • RsaUtil
public class RsaUtil {

    /**
     * 生成RSA秘钥对
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static RsaPair generate() throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        keyGen.initialize(2048, random);
        KeyPair pair = keyGen.generateKeyPair();

        PrivateKey priv = pair.getPrivate();
        PublicKey pub = pair.getPublic();

        String privStr = Base64.getEncoder().encodeToString(priv.getEncoded());
        String pubStr = Base64.getEncoder().encodeToString(pub.getEncoded());
        return new RsaPair(privStr, pubStr);
    }

    /**
     * 使用私钥签名
     * @param privStr 私钥字符串
     * @param plaintext 需要签名的字符串
     * @return 私钥签名
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws SignatureException
     */
    public static String sign(String privStr, String plaintext) throws InvalidKeySpecException,
            NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
        PrivateKey privKey = getPrivateKey(privStr);
        Signature rsaPrivSig = Signature.getInstance("SHA1withRSA");
        rsaPrivSig.initSign(privKey);
        rsaPrivSig.update(plaintext.getBytes("UTF-8"));
        byte[] privSign = rsaPrivSig.sign();
        return Base64.getEncoder().encodeToString(privSign);
    }

    /**
     * 验签
     * @param pubStr 公钥字符串
     * @param privSignStr 私钥签名字符串
     * @param plaintext
     * @return true:成功
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws SignatureException
     */
    public static boolean verify(String pubStr, String privSignStr, String plaintext) throws InvalidKeySpecException,
            NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, SignatureException {
        PublicKey pubKey = getPublicKey(pubStr);
        Signature rsaPubSig = Signature.getInstance("SHA1withRSA");
        rsaPubSig.initVerify(pubKey);
        rsaPubSig.update(plaintext.getBytes("UTF-8"));
        return rsaPubSig.verify(Base64.getDecoder().decode(privSignStr));
    }

    /**
     * 获取私钥
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static PrivateKey getPrivateKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encKey = Base64.getDecoder().decode((key.getBytes()));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private static PublicKey getPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encKey = Base64.getDecoder().decode((key.getBytes()));
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encKey);
        return keyFactory.generatePublic(keySpec);
    }
}
  • RsaPair
/**
 * Rsa秘钥对
 */
public class RsaPair {

    /**
     * 私钥
     */
    private String privSt;

    /**
     * 公钥
     */
    private String pubStr;

    public RsaPair(String privSt, String pubStr) {
        this.privSt = privSt;
        this.pubStr = pubStr;
    }
    // TODO get方法
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值