java对数据进行加密、解密

java对数据进行加密、解密

RSA不对称加密

关于base64可以参考我的上一篇博客: java Base64编码、解码

import org.springframework.util.StringUtils;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author ListJiang
 * @class RSA加密工具类
 * @remark
 * @date 2020/9/14 19:56
 */
public class EncrypRSA {
   

    private static final String PUBLIC = "PUBLIC";
    private static final String PRIVATE = "PRIVATE";


    /**
     * 根据公钥加密
     *
     * @param publicKey      公钥
     * @param cleartextBytes 明文
     */
    public byte[] encrypt(RSAPublicKey publicKey, byte[] cleartextBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
   
        if (publicKey != null) {
   
            //Cipher负责完成加密或解密工作,基于RSA
            Cipher cipher = Cipher.getInstance("RSA");
            //根据公钥,对Cipher对象进行初始化
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] resultBytes = cipher.doFinal(cleartextBytes);
            return resultBytes;
        }
        return null;
    }

    /**
     * 根据公钥加密
     *
     * @param publicKey 公钥
     * @param cleartext 明文
     * @return
     * @throws Exception
     */
    public byte[] encrypt(RSAPublicKey publicKey, String cleartext) throws Exception {
   
        if (publicKey != null) {
   
            return encrypt(publicKey, cleartext.getBytes());
        }
        return null;
    }

    /**
     * 指定加密类型进行加密
     *
     * @param key       密钥
     * @param cleartext 明文
     * @param keyType   加密密钥类型,默认公钥加密
     * @return
     * @throws Exception
     */
    public byte[] encrypt(String key, String cleartext, String keyType) throws Exception {
   
        if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(keyType)) {
   
            switch (keyType) {
   
                case PUBLIC:
                    return encrypt(getPublicKey(key), cleartext.getBytes());
                case PRIVATE:
                    return encrypt
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值