用SecureUtil生成RSA公钥私钥以及加密数据

本文介绍了如何使用Hutool库的RSAUtil类生成和操作RSA密钥对,展示了如何加密和解密字符串,重点在于序列号生成器的实现和私钥/公钥的使用。
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.9</version>
</dependency>
package com.kakarote.admin.common;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import org.apache.commons.codec.binary.Base64;
import java.security.KeyPair;

/**
 * 
 * xxxx CRM注册序列号生成器 
 */

public class RSAUtil {

    private static final String publicKey;
    private static final String privateKey;

    static {
        KeyPair pair = SecureUtil.generateKeyPair("RSA");
        publicKey = new String(Base64.encodeBase64(pair.getPublic().getEncoded()));
        privateKey= new String(Base64.encodeBase64((pair.getPrivate().getEncoded())));
    }

    /**
     *
     * @param str 加密前JSONObject->Str数据
     * @return 返回加密后数据
     */
    public static String encrypt(String str){
        return SecureUtil.rsa(privateKey,publicKey).encryptBcd(str, KeyType.PrivateKey);
    }

    /**
     *
     * @param str 加密后的字符串
     * @return
     */
    public static String decrypt (String str){
        return SecureUtil.rsa((String) null,publicKey).decryptStrFromBcd(str, KeyType.PublicKey);
    }

    public static void main(String[] args) {
        System.out.println("私钥:" + privateKey);
        /**
         * 公钥替换 AdminConst中 userPublicKey
         */
        System.out.println("公钥:" + publicKey);
        /**
         * 只能传入 JSONObject转String格式,具体传什么值不清楚
         * 加密的值为序列号 encryptStr 可以通过注册,总之随便填
         */
        String encryptStr = encrypt("{\"info\":\"admin\"}");

       // String decryptStr = decrypt(encryptStr);

        System.out.println("序列号:" + encryptStr);
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陈增林

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

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

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

打赏作者

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

抵扣说明:

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

余额充值