java rsa加密

生成公钥和私钥

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(1024);
KeyPair keyPair = generator.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

// base64编码的公私钥字符串 主要为了存储和还原
// base64编码的的私钥字符串 
System.out.println(new String(Base64.encodeBase64(privateKey.getEncoded())));
// base64编码的公钥字符串
System.out.println(new String(Base64.encodeBase64(publicKey.getEncoded())));

 

使用公钥加密 使用私钥解密(或者使用私钥加密  公钥解密)

// 使用公钥加密
byte[] obj = "你好".getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] enbs = cipher.doFinal(obj);


// 使用私钥解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] debs = cipher.doFinal(enbs);

根据私钥的modules 和 privateExponent 还原私钥

// 一个密钥对 公钥和私钥的modules是一摸一样的
BigInteger bigM = new BigInteger("私钥的modules");
BigInteger bigPriE = new BigInteger("私钥的privateExponent");
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(bigM, bigPriE);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

根据公钥的modules 和 publicExponent 还原公钥

BigInteger bigM = new BigInteger("公钥的modules");
BigInteger bigPubE = new BigInteger("公钥的publicExponent");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigM, bigPubE);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);

 base64编码公私钥字符串还原公私钥

 /**
     * 从base64编码的私钥字符串还原出私钥
     *
     * @param base64EncodePrivateKey base64编码的私钥
     */
    public RSAPrivateKey getPrivateKey(String base64EncodePrivateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] bytes = Base64.decodeBase64(base64EncodePrivateKey);
        // Only RSAPrivate(Crt)KeySpec and PKCS8EncodedKeySpec supported for RSA private keys
        // 私钥仅支持 RSAPrivate(Crt)KeySpec 和 PKCS8EncodedKeySpec
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
    }

    /**
     * 从base64编码的公钥字符串还原出公钥
     * @param base64EncodePublicKey base64编码的公钥
     */
    public RSAPublicKey getPublicKey(String base64EncodePublicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] bytes = Base64.decodeBase64(base64EncodePublicKey);
        // Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys
        // 公钥仅支持 RSAPublicKeySpec 和 X509EncodedKeySpec
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }

 

posted @ 2022-05-23 14:10  荣超  阅读(176)  评论(0)    收藏  举报