企业级RSA加解密

接上一篇企业级AES加解密

废话不多说,直接上代码,复制粘贴即可用

package com.xx.xx.utils;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * 加密工具类
 *
 * @author yuan
 */
public class CipherUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CipherUtil.class);

    protected static final String SECRET_KEY = "sdlfjo234L32fv0o9iNG0LL!!*&1%$#@";

   
    /**
     * 非对称加密
     */
    private static Rsa rsa;

    /**
     * 获取非对称加密算法
     *
     * @return 加密算法
     */
    public static Rsa rsa() {
        if (null == rsa) {
            rsa = new Rsa();
        }
        return rsa;
    }

    

    /**
     * 非对称加密工具类
     */
    public static class Rsa {

        private static final String DEFAULT_CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";

        private static Cipher cipher;

        private static KeyPair keyPair;

        private static PublicKey publicKey;

        private static PrivateKey privateKey;

        private synchronized Cipher cipher() throws NoSuchPaddingException, NoSuchAlgorithmException {
            if (null == cipher) {
                cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            }
            return cipher;
        }

        private synchronized KeyPair keyPair(String key) throws NoSuchAlgorithmException {
            if (null == keyPair) {
                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
                // 指定算法名称,不同的系统上生成的key是相同的。
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                random.setSeed(key.getBytes(StandardCharsets.UTF_8));
                generator.initialize(1024, random);
                keyPair = generator.generateKeyPair();
            }
            return keyPair;
        }

        private synchronized PublicKey publicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
            if (null == publicKey) {
                publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyPair(SECRET_KEY).getPublic().getEncoded()));
            }
            return publicKey;
        }

        private PrivateKey privateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
            if (null == privateKey) {
                privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(keyPair(SECRET_KEY).getPrivate().getEncoded()));
            }
            return privateKey;
        }

        public synchronized String encrypt(String content) {
            try {
                cipher().init(Cipher.ENCRYPT_MODE, publicKey());
                return byte2Base64(cipher.doFinal(content.getBytes()));
            } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException e) {
                LOGGER.error("数据加密失败,stack info=" + ExceptionUtils.getFullStackTrace(e));
                throw new ArithmeticException("数据加密失败");
            }
        }

        public synchronized String decrypt(String content) {
            try {
                cipher().init(Cipher.DECRYPT_MODE, privateKey());
                return new String(cipher.doFinal(base642Byte(content)));
            } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException e) {
                LOGGER.error("数据解密失败,stack info=" + ExceptionUtils.getFullStackTrace(e));
                throw new ArithmeticException("数据解密失败");
            }
        }
    }

    /**
     * 字节数组转Base64编码
     *
     * @param bytes 内容字节码
     * @return base64编码
     */
    public static String byte2Base64(byte[] bytes) {
        return Base64Utils.encodeToUrlSafeString(bytes);
    }

    /**
     * Base64编码转字节数组
     *
     * @param base64Key base64编码
     * @return 字节数组
     */
    public static byte[] base642Byte(String base64Key) {
        return Base64Utils.decodeFromUrlSafeString(base64Key);
    }

    public static void main(String[] args) {
        String content = "D:\\attachment\\file.docx";
        System.out.println("原文=" + content);
        String s1 = CipherUtil.rsa().encrypt(content);
        System.out.println("加密结果=" + s1);
        System.out.println("解密结果=" + CipherUtil.rsa().decrypt(s1));
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员·猿先生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值