RSA加解密-使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥

说明:

本文使用PKCS8EncodedKeySpec生成私钥,使用X509EncodedKeySpec生成公钥。此外,使用Base64进行解码和编码.

maven依赖:

<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.11</version>
</dependency>

代码:

package org.example.encrypt;


import org.apache.commons.codec.binary.Base64;


import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;


/**
* @description:
* @author:
* @create: 2023-06-14 15:03
**/
public class EncryptionUtil {


    private static final String KEY_ALGORITHM = "RSA";


    private static final String PUBLIC_KEY = "publicKey";


    private static final String PRIVATE_KEY = "privateKey";


    public static void main(String[] args) throws Exception {
        Map<String, String> keyMap = genKey();
        RSAPublicKey publicKey = getPublicKey(keyMap.get(PUBLIC_KEY));
        RSAPrivateKey privateKey = getPrivateKey(keyMap.get(PRIVATE_KEY));
        String info = "明文123456";
        //加密
        byte[] bytes = encrypt(info.getBytes(StandardCharsets.UTF_8), publicKey);
        //解密
        bytes = decrypt(bytes, privateKey);
        String plainText = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("解密:" + plainText);
    }


    /**
     *  返回 Base64 编码后的加密字符串
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String encryptToBase64(byte[] data, RSAPublicKey publicKey) throws Exception {
        return Base64.encodeBase64String(encrypt(data, publicKey));
    }


    /**
     * 加密
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] encrypt(byte[] data, RSAPublicKey publicKey) throws Exception {
        // 构建 RSA 的秘钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 创建RSA的Cipher对象,并提供加密功能
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        // Cipher对象需要初始化
        // ENCRYPT_MODE 加密模式
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        // 得到需要加密后的二进制数据
        return cipher.doFinal(data);
    }


    /**
     * 解密
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, RSAPrivateKey privateKey) throws Exception {
        // 构建 RSA 的秘钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        //数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        // Cipher对象需要初始化
        // DECRYPT_MODE 解密模式
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }


    /**
     * 取的秘钥对
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String, String> genKey() throws NoSuchAlgorithmException {
        Map<String, String> keyMap = new HashMap<String, String>();
        // 实例化秘钥生成器
        KeyPairGenerator keygen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom random = new SecureRandom();
        // random.setSeed(keyInfo.getBytes());
        // 设置秘钥位数,512位已被破解,用1024位,最好用2048位
        keygen.initialize(1024, random);
        // 生成秘钥对
        KeyPair kp = keygen.generateKeyPair();
        // 私钥对象
        RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
        // 公钥对象
        RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
        // 以 Base64 对私钥进行编码
        String privateKeyString = Base64.encodeBase64String(privateKey.getEncoded());
        // 以 Base64 对公钥进行编码
        String publicKeyString = Base64.encodeBase64String(publicKey.getEncoded());
        keyMap.put(PUBLIC_KEY, publicKeyString);
        keyMap.put(PRIVATE_KEY, privateKeyString);
        return keyMap;
    }


    /**
     * 获取RSA公钥
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static RSAPublicKey getPublicKey(String publicKey) throws Exception {
        // 解码公钥字符串,得到公钥的 ASN.1 编码格式
        X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
        // 构建 RSA 的秘钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 利用 RSA 秘钥工厂和 X509EncodedKeySpec 生成公钥
        return (RSAPublicKey) keyFactory.generatePublic(spec);
    }


    /**
     * 获取RSA私钥
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static RSAPrivateKey getPrivateKey(String privateKey) throws Exception {
        // 解码私钥字符串,得到私钥的 ASN.1 编码格式
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        // 构建 RSA 的秘钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 利用 RSA 秘钥工厂和 PKCS8EncodedKeySpec 生成私钥
        return (RSAPrivateKey) keyFactory.generatePrivate(spec);
    }
}

参考:

RSA 秘钥工具类详解_rsa工具类怎么用_wadreamer的博客-CSDN博客

RSA使用X509EncodedKeySpec、PKCS8EncodedKeySpec生成公钥和私钥_Felix.Ma的博客-CSDN博客

PKCS8EncodedKeySpecJava Cryptography Architecture (JCA)中的一种数据格式,它用于存储私钥信息,通常用于Java Secure Socket Layer (JSSE)库中。当你需要在Java中解密一个由PKCS8算法(Private Key Information Syntax)编码的私钥时,会用到这个类。 `PKCS8EncodedKeySpec`的主要作用是封装一个私钥的二进制表示,以便于加密算法使用。以下是如何创建使用`PKCS8EncodedKeySpec`的一个简单示例: ```java import java.security.spec.PKCS8EncodedKeySpec; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; // 假设你有一个从文件或网络获取的Base64编码的私钥字符串 String privateKeyBase64 = "..."; // 你的私钥Base64字符串 // 解码并创建PKCS8EncodedKeySpec对象 byte[] decodedPrivateKey = Base64.getDecoder().decode(privateKeyBase64); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodedPrivateKey); // 使用给定的密码算法(如"PBKDF2WithHmacSHA256")创建SecretKeyFactory char[] password = "..."; // 密码 String algorithm = "PBKDF2WithHmacSHA256"; SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm); // 使用specpassword来生成私钥 Key key = factory.generateSecret(spec); // 现在你可以使用key进行加密解密操作 ``` 请注意,实际使用时,你需要替换上述代码中的密码私钥字符串。在生产环境中,不安全地硬编码密码是不推荐的,通常会使用安全的方式(如环境变量或安全的存储机制)来获取这些信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值