加密算法RSA

一、获取公钥和私钥

   public static Map<String,String> createRsaKey() {
        Map<String,String> result = new HashMap<>();
        try{
            //获得对象 KeyPairGenerator 参数 RSA 1024个字节
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            //通过对象 KeyPairGenerator 获取对象KeyPair
            KeyPair keyPair = keyPairGen.generateKeyPair();

            JcaPKCS8Generator gen1 = new JcaPKCS8Generator(keyPair.getPrivate(), null);
            PemObject obj1 = gen1.generate();
            StringWriter sw1 = new StringWriter();
            try (JcaPEMWriter pw = new JcaPEMWriter(sw1)) {
                pw.writeObject(obj1);
            }
            String pkcs8Key1 = sw1.toString();

            //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

            //公私钥对象存入map中
            String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
            String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());

            result.put("publicKeyStr",publicKeyStr);
            result.put("privateKeyStr",privateKeyStr);
            result.put("pkcs8PriKeyStr",pkcs8Key1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

二、使用私钥签名、公钥验签

        私钥签名

/**    
  * 私钥签名
  * @param data 待签名的数据
  * @param privateKey 私钥
  * @return 数字签名
  * @throws Exception 抛出异常
  */
 public static String sign(String data, String privateKey) throws Exception {
     byte[] keyBytes = Base64.getDecoder().decode(privateKey);
     PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
     KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
     PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
     Signature signature = Signature.getInstance("MD5withRSA");
     signature.initSign(privateK);
     signature.update(data.getBytes(Charset.forName("utf-8")));
     return Base64.getEncoder().encodeToString(signature.sign());
 }

公钥验签

   /**
     * 公钥验签
     * @param data 原始数据
     * @param publicKey 公钥
     * @param sign 签名
     * @return 验签结果 true:验签成功 false:验签失败
     * @throws Exception 抛出异常
     */
    public static boolean verify(String data, String publicKey, String sign) {
        boolean result = false;

        try{
            byte[] keyBytes = Base64.getDecoder().decode(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(publicK);
            signature.update(data.getBytes(Charset.forName("utf-8")));
            result = signature.verify(Base64.getDecoder().decode(sign));
        }catch (Exception e){
            e.printStackTrace();
        }

        return result;
    }

三、公钥加密、私钥解密

公钥加密

   /**
     * 公钥加密
     * @param str 待加密数据
     * @param publicKey 公钥
     * @return 加密数据
     * @throws Exception 异常抛出
     */
    public static String encrypt(String str, String publicKey) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        final byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        final int len = bytes.length;//字符串长度
        int offset = 0;//偏移量
        int i = 0;//所分的段数
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();

        while (len > offset) {
            byte[] cache;
            if (len - offset > 117) {
                cache = cipher.doFinal(bytes, offset, 117);
            } else {
                cache = cipher.doFinal(bytes, offset, len - offset);
            }
            bos.write(cache);
            i++;
            offset = 117 * i;
        }
        bos.close();

        return Base64.getEncoder().encodeToString(bos.toByteArray());
    }

私钥解密

   /**
     * 私钥解密
     * @param str 密文数据
     * @param privateKey 私钥
     * @return 明文数据
     * @throws Exception 抛出异常
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.getDecoder().decode(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        final int len = inputByte.length;//密文
        int offset = 0;//偏移量
        int i = 0;//段数
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (len - offset > 0) {
            byte[] cache;
            if (len - offset > 128) {
                cache = cipher.doFinal(inputByte, offset, 128);
            } else {
                cache = cipher.doFinal(inputByte, offset, len - offset);
            }
            bos.write(cache);
            i++;
            offset = 128 * i;
        }
        bos.close();

        return new String(bos.toByteArray());
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值