Java字符串使用RSA加密及解密

RSA 是一种非对称加密算法,使用公钥加密、私钥解密。

目录

1.创建一个专门的类存放加密解密的方法,方便后期调用。

2.调用加密

3.解密

4. 我们的需求是将加密的字符返回给前端 再让前端传进来,和redis中的相对比较看是否一致

一致继续往下走,不一致直接return

4.1  存到redis中 并返回

4.2存redis中拿到并和传进来的比较


1.创建一个专门的类存放加密解密的方法,方便后期调用。
//创建的一个新类,方便调用
public class EncryptionMethod {
    private static final String ALGORITHM = "RSA";
    private static KeyPair keyPair = null;
//静态初始化块(static block),用于在类加载时生成一对 RSA 密钥(公钥和私钥)
    static{
        KeyPairGenerator keyPairGenerator = null;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        keyPairGenerator.initialize(2048);
        keyPair = keyPairGenerator.generateKeyPair();
    }
    // 生成 RSA 密钥对
    public static KeyPair generateRSAKeyPair() throws Exception {
        // 生成 RSA 密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(2048); // 密钥长度(推荐 2048 或更高)
        return keyPairGenerator.generateKeyPair();
    }
    // 加密
    public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    // 解密
    public static String decrypt(String encryptedText, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }
    // 加密
    public static String encrypt(String plainText) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }
    // 解密
    public static String decrypt(String encryptedText) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }
}
2.调用加密
//这里是随机生成6位数字进行加密 
String randStr= RandomUtil.randomString(BASE_CHECK_CODES,6);
 String right = EncryptionMethod.encrypt(randStr);
3.解密
//直接调用
redis_jiemi = EncryptionMethod.decrypt(redis_value);
4. 我们的需求是将加密的字符返回给前端 再让前端传进来,和redis中的相对比较看是否一致
一致继续往下走,不一致直接return
4.1  存到redis中 并返回
  
 Result result1 = new Result<>();
        Map map = new HashMap<>();
//redis的 key
        String redisKey = CommonConstantNumber.CACHE_REDIS_KEY_YZM_DEC;
        String randStr= RandomUtil.randomString(BASE_CHECK_CODES,6);
        String right = EncryptionMethod.encrypt(randStr);
        redisUtil.set(redisKey,right, 600);
        map.put("yzmdec",right);
        result1.setResult(map);
        result1.setCode(200);
        result1.setMessage("验证成功");
        return result1;
4.2存redis中拿到并和传进来的比较
             //从redis中取到的
            String redisKey = CommonConstantNumber.CACHE_REDIS_KEY_YZM_DEC;
            String redis_value= redisUtil.get(redisKey).toString();
            if(null==redis_value) {
                return Result.error("短信验证码失效!");
            }
            //传进来的加密验证码
            String encrypt = json.getString("yzmdec");
            //解密
            String decrypt_jiemi = null;
            try {
                decrypt_jiemi = EncryptionMethod.decrypt(encrypt);
            } catch (Exception e) {
    //         throw new RuntimeException(e);
                return Result.error("传入的字符有误");
            }
            String redis_jiemi = null;
            try {
                redis_jiemi = EncryptionMethod.decrypt(redis_value);
            } catch (Exception e) {
                return Result.error("验证码失效");
            }
            if(redis_jiemi.equals(decrypt_jiemi)){
                 System.out.println("解密后的字符一致");
            }else {
             System.out.println("解密后的字符不一致");
              return Result.error("验证失效");
             }

       成功没有快车道,幸福没有高速路。所有的成功,都来自不倦地努力和奔跑,所有的幸福都来自平凡的奋斗和坚持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值