Java--RSA非对称加密的实现(使用java.security.KeyPair)

文章目录

        • 前言
        • 实现步骤
        • 测试结果

前言
  • 非对称加密是指使用不同的两个密钥进行加密和解密的一种加密算法,调用方用使用服务方提供的公钥进行加密,服务方使用自己的私钥进行解密。RSA算法是目前使用最广泛的公钥密码算法。
  • Java提供了KeyPairGenerator类要生成公钥和私钥密钥对(KeyPair),本文将提供两个接口,模拟公钥加密字符串和私钥解密字符串的过程。
实现步骤
  1. 创建RsaService,该类提供以下方法:

    genKeyPair(): 初始化密钥对,并将生成的密钥对存入Redis
    getPublicKey()/getPrivateKey(): 提供获取公钥和私钥的方法
    encrypt(String password)/decrypt(String password): 提供加密和解密的方法,供其他类调用

    @Service
    public class RsaService { 
        @Autowired
        private RedisOperation redisOperation;
        /**
        * 初始化随机生成密钥对
        */
        @PostConstruct
        public void genKeyPair() throws NoSuchAlgorithmException {
            // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            // 初始化密钥对生成器,密钥大小为96-1024位
            // 这里的常量为:public static final int INT_FOUR_KB = 4096;
            keyPairGen.initialize(MagicNum.INT_FOUR_KB, new SecureRandom());
            // 生成一个密钥对,保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            //私钥
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            //公钥
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
    
            /**
             * 公钥与私钥
             */
            String publicKey = new String(Base64.encodeBase64(rsaPublicKey.getEncoded()));
            String privateKey = new String(Base64.encodeBase64((rsaPrivateKey.getEncoded())));
            /**
             * 存入Redis
             */
            redisOperation.set(RedisKeyConstant.SYSTEM_RAS_PUBLIC,publicKey);
            redisOperation.set(RedisKeyConstant.SYSTEM_RAS_PRIVATE,privateKey);
        }
    
        /**
         * 解密方法
         *
         * @param password -
         * @return ProcessException 自定义异常类
         */
        public String decrypt(String password) {
            try {
                return RsaUtil.decrypt(password, getPrivateKey());
            } catch (Exception e) {
                e.printStackTrace();
                throw new ProcessException(CommonConstants.ENUM_PROCESSING_EXCEPTION,"RSA解密异常");
            }
        }
    
        /**
         * 加密方法
         *
         * @param password -
         * @return -
         * @exception ProcessException 自定义异常类
         */
        public String encrypt(String password) {
            try {
                return RsaUtil.encrypt(password, getPublicKey());
            } catch (Exception e) {
                throw new ProcessException(CommonConstants.ENUM_PROCESSING_EXCEPTION,"RSA加密异常");
            }
        }
    
        /**
         * 获取公钥
         */
        public String getPublicKey() {
            return redisOperation.get(RedisKeyConstant.SYSTEM_RAS_PUBLIC);
        }
    
        /**
         * 获取私钥
         */
        public String getPrivateKey() {
            return redisOperation.get(RedisKeyConstant.SYSTEM_RAS_PRIVATE);
        }
    }
    
  2. RsaUtil工具类,提供Base编码和解码
    public final class RsaUtil {
    
        private static final String RSA = "RSA";
    
        /**
         * RSA公钥加密
         *
         * @param publicKey publicKey
         * @param str       加密字符串
         * @return 密文
         * @throws Exception 加密过程中的异常信息
         */
        public static String encrypt(String str, String publicKey) throws Exception {
            //base64编码的公钥
            byte[] decoded = Base64.decodeBase64(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            //RSA加密
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
        }
    
        /**
         * RSA私钥解密
         *
         * @param privateKey privateKey
         * @param str        加密字符串
         * @return 明文
         */
        public static String decrypt(String str, String privateKey) throws Exception {
            //64位解码加密后的字符串
            byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
            //base64编码的私钥
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey =
                    (RSAPrivateKey) KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded));
            //RSA解密
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            return new String(cipher.doFinal(inputByte));
        }
    }
    
  3. 在Controller层编写接口以便做后面的测试
    @RestController
    @RequestMapping("/part/util")
    public class UtilController {
         @Autowired
         private RsaService rsaService;
        /**
          * 获取公钥
          *
          * @return -
          */
         @ApiOperation("获取公钥")
         @GetMapping("getPublicKey")
         public Result getPublicKey() {
             return Result.ok().data(rsaService.getPublicKey());
         }
    
         /**
          * 获取加密字符串
          *
          * @param key -
          * @return -
          */
         @ApiOperation("获取加密字符串")
         @GetMapping("encrypt/key")
         public Result getText(@RequestParam(value = "key") String key) {
             String encryptKey = rsaService.encrypt(key);
             return Result.ok().data(encryptKey);
         }
    
         /**
          * 获取解密字符串
          *
          * @param encryptKey -
          * @return -
          */
         @ApiOperation("获取解密字符串")
         @GetMapping("decrypt/key")
         public Result getText2(@RequestParam(value = "encryptKey") String encryptKey) {
             String decryptKey = rsaService.decrypt(encryptKey);
             return Result.ok().data(decryptKey);
         }
    }
    
测试结果
  • 获取公钥接口

    在这里插入图片描述

  • 加密接口,输入参数key将与公钥加密,接口返回得到加密后的字符串。

    在这里插入图片描述

  • 解密接口,输入参数为公钥加密后的字符串,接口将返回私钥解密后的结果。
    在这里插入图片描述

  • 30
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
非对称加密算法是一种常用的加密方式,它采用了一对密钥,即公钥和私钥。公钥是公开的,可以任意分发,而私钥则只能由密钥的所有者持有,用于解密加密数据。常见的非对称加密算法包括RSA、DSA、ECC等。 下面是一个使用RSA算法实现非对称加密Java示例代码: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import javax.crypto.Cipher; public class RSAEncryptionExample { public static void main(String[] args) throws Exception { String input = "Hello World!"; KeyPair keyPair = generateRSAKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); byte[] encryptedData = rsaEncrypt(input.getBytes(), publicKey); byte[] decryptedData = rsaDecrypt(encryptedData, privateKey); System.out.println("Original data: " + input); System.out.println("Encrypted data: " + new String(encryptedData)); System.out.println("Decrypted data: " + new String(decryptedData)); } public static KeyPair generateRSAKeyPair() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); // key size KeyPair keyPair = generator.generateKeyPair(); return keyPair; } public static byte[] rsaEncrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedData = cipher.doFinal(data); return encryptedData; } public static byte[] rsaDecrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(data); return decryptedData; } } ``` 这个示例代码中,我们首先生成了一个RSA密钥对,包括公钥和私钥。然后使用公钥对原始数据进行加密,得到加密后的数据。接着使用私钥对加密后的数据进行解密,得到原始数据。 需要注意的是,RSA算法使用的密钥长度越长,安全性就越高,但加解密的速度也越慢。在实际应用中,需要根据实际需求和环境选择合适的密钥长度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

芝麻馅_

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

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

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

打赏作者

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

抵扣说明:

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

余额充值