RSA非对称加密工具

183 阅读1分钟

使用Hutool的RSAUtil实现的非对称加密工具

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.security.KeyPair;

public class RsaUtils {
    public final static KeyPair PAIR = SecureUtil.generateKeyPair("RSA");

    /**
     * 获取公钥
     * @return
     */
    public static String getPublicKey(){
        return Base64.encode(PAIR.getPublic().getEncoded());
    }

    /**
     * 加密
     * @param msg
     * @return
     */
    public static String encrypt(String msg){
        RSA rsa = new RSA(PAIR.getPrivate(), PAIR.getPublic());
        byte[] encrypt = rsa.encrypt(msg.getBytes(), KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    /**
     * 指定公钥加密
     * @param msg
     * @return
     */
    public static String encrypt(String msg,String publicKey){
        byte[] decode = Base64.decode(publicKey);
        RSA rsa = new RSA(null,decode);
        byte[] encrypt = rsa.encrypt(msg.getBytes(), KeyType.PublicKey);
        return Base64.encode(encrypt);
    }

    /**
     * 私钥解码
     * @return
     */
    public static String decrypt(String encode){
        RSA rsa = new RSA(PAIR.getPrivate(),null);
        byte[] decode = Base64.decode(encode);
        byte[] decrypt = rsa.decrypt(decode, KeyType.PrivateKey);
        return new String(decrypt);
    }

}