java RSA加密解密

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);
    }
}

你可能感兴趣的:(java,spring,spring,boot)