java.security.*篇(1) RSA 加密与解密demo

本文详细介绍了Java中RSA算法的KeyPairGenerator、KeyPair、公钥加密和私钥解密的使用,通过实例演示了如何生成公钥私钥对,并展示了如何利用公钥加密、私钥解密的实际应用场景和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下一篇介绍《java.security.*篇(2) RSA签名与校验demo》 

涉及类:KeyPairGenerator KeyPair SAPrivateKey RSAPublicKey X509EncodedKeySpec X509EncodedKeySpec PKCS8EncodedKeySpec Cipher

rsa 公钥加密,私钥解密常用使用场景
 1.客户端-服务端通讯发送消息,客户端消息公钥加密,服务端私钥解密
 2.机密文件加密存储,服务端解密在线显示
 3.机密数据库数据内容加密存储,服务端解密显示
 4.文章关键页加密,付费后服务端解密查看等等

rsa 公钥加密私钥解密demo

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

公钥加密私钥解密测试方法

    private static final String ALGORITHM_NAME = "RSA";
    public static final String CHARSET = "UTF-8";

 /**
     * @description: demos of jdk8 java.security KeyPairGenerator KeyPair
     * RSAPrivateKey RSAPublicKey X509EncodedKeySpec X509EncodedKeySpec PKCS8EncodedKeySpec Cipher
     * ras public_key encode and private_key decode  用ras 公钥加密 私钥解密
     */
    @Test
    public void testPublicEncryptAndPrivateDecrypt() throws Exception {

        String originMessage = "需要加密的字符串";
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        // 初始化生成器大小
        keyPairGenerator.initialize(1024);

        // 生成密钥对
        KeyPair keyPair =  keyPairGenerator.generateKeyPair();

        // 获取私钥
        PrivateKey privateKey = keyPair.getPrivate();

        // 获取公钥
        PublicKey publicKey = keyPair.getPublic();

        // 公钥字符串
        String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());

        // 私钥字符串
        String privateKeyStr =Base64.encodeBase64URLSafeString(privateKey.getEncoded());


        System.out.println("public key str is:"+ publicKeyStr);
        System.out.println("private key str is:"+ privateKeyStr);

        // 加密后bytes
        byte[] encryptedBytes = publicKeyEncrypt(originMessage,publicKeyStr);

        // 解密后bytes
        byte[] decryptedBytes = privateKeydecrypt(encryptedBytes,privateKeyStr);

        //输出加密后字符串
        System.out.println("public encrypted str:"+ new String(encryptedBytes));

        //输出解密后内容
        System.out.println("private decrypted str:"+ new String(decryptedBytes,CHARSET));


    }

公钥加密方法

 /**
     * @description public key encrypt
     * 公钥加密:实际情况一般是私钥和公钥是提前生成好的,我们需要读取配置文件或者输入值获取公钥私钥字符串去加密解密,因为传入参数需要是字符串,
     * privateKey publicKey 对象进行后续操作
     **/
    public byte[] publicKeyEncrypt(String message ,String publicKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {

        // 初始化rsa密钥factory
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_NAME);

        // 根据公钥字符串初始化X509的keySpec对象
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyStr));

        // 根据keySpec初始化rsa公钥,以及Cipher密码器
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
        Cipher cipher =Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,rsaPublicKey);

        // 返回加密后的内容
        return cipher.doFinal(message.getBytes(CHARSET));
    }

私钥解密方法 

/**
     * @description private key decrypt
     * 私钥解密:实际情况一般是私钥和公钥是提前生成好的,我们需要读取配置文件或者输入值获取公钥私钥字符串去加密解密,因为传入参数需要是字符串,
     * privateKey publicKey 对象进行后续操作
     **/
    public byte[] privateKeydecrypt(byte[] encryptBytes ,String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException {

        // 初始化rsa密钥factory
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_NAME);

        // 根据私钥初始化PKCS8的keySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyStr));

        // 根据keySpec初始化rsa私钥,以及Cipher密码器
        RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher =Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE,privateKey);

        // 返回解密后的内容
        return cipher.doFinal(encryptBytes);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

峡谷电光马仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值