java RSA加密解密

该代码实现了一个RSAKeyManager类,用于生成RSA密钥对并存储在Redis缓存中。类中包含加密和解密方法,以及获取公钥和私钥的函数,同时提供了清除缓存的接口。在测试类中展示了如何使用这个管理器进行数据加密和解密。
摘要由CSDN通过智能技术生成
import com.ynart.common.redis.service.RedisService;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

@Component
public class RSAKeyManager {

    private static String CACHE_NAME = "rsaKeys";

    @Autowired
    private RedisService redisService;

    // 生成RSA密钥对并存储到Redis缓存中
    public void generateAndStoreKeys(String uuid) throws NoSuchAlgorithmException {
        CACHE_NAME=uuid;
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        // 将公钥和私钥转换为Base64编码的字符串
        String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());

        // 存储公钥和私钥到Redis缓存
        redisService.setCacheObject(CACHE_NAME + ":publicKey", publicKeyStr);
        redisService.setCacheObject(CACHE_NAME + ":privateKey", privateKeyStr);
    }

    // 从Redis缓存中获取RSA公钥
    public RSAPublicKey getPublicKey() throws NoSuchAlgorithmException {
        String publicKeyStr = redisService.getCacheObject(CACHE_NAME + ":publicKey");
        if (publicKeyStr != null) {
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
            try {
                return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 从Redis缓存中获取RSA私钥
    public RSAPrivateKey getPrivateKey() throws NoSuchAlgorithmException {
        String privateKeyStr = redisService.getCacheObject(CACHE_NAME + ":privateKey");
        if (privateKeyStr != null) {
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
            try {
                return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 清除Redis缓存中的RSA公钥和私钥
    public void clearKeys() {
        redisService.deleteObject(CACHE_NAME + ":publicKey");
        redisService.deleteObject(CACHE_NAME + ":privateKey");
    }
    // 加密数据
    public String encryptData(String data) throws Exception {
        RSAPublicKey publicKey = getPublicKey();
        if (publicKey != null) {
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedData = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedData);
        }
        return null;
    }

    // 解密数据
    public String decryptData(String encryptedData) throws Exception {
        RSAPrivateKey privateKey = getPrivateKey();
        if (privateKey != null) {
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(decryptedData);
        }
        return null;
    }

}

使用:

package com.ynart.auth.utils;

import com.ynart.common.core.domain.R;
import com.ynart.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class test {
    @Autowired
    private RSAKeyManager rsaKeyManager;
    @PostMapping("test")
    public R<?> AppAuth() throws Exception {
    //自定义动态uuid
        rsaKeyManager.generateAndStoreKeys("123456789uuid");
        String a= rsaKeyManager.encryptData("需要加密的数据");
        String b=rsaKeyManager.decryptData(a);
        System.out.println(b);
        return R.ok(0);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值