工具类-RSA加密

1.线上加密-解密网址

 https://www.bejson.com/enc/rsa/

2.JAVA后端代码

 

package com.cn.lze.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: sunlf16202
 * @date: 2021/6/16 10:53
 */
@Component
public class RSATools {

    Logger logger = LoggerFactory.getLogger(RSATools.class);
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 公钥-测试环境
     */
    private static final String TEST_PUBLIC_KEY = "";
     /*
     * 私钥-测试环境
     */
    private static final String TEST_PRIVATE_KEY = "";

    /**
     * 获取密钥对
     *
     * @return 密钥对
     */
    public Map<String,Object> getKeyPair() {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(1024);
            KeyPair keyPair = generator.generateKeyPair();
            String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
            String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
            map.put("privateKey",privateKey);
            map.put("publicKey",publicKey);
        }catch (Exception e){
            logger.error("获取RSA公私钥失败",e);
        }
        return map ;
    }


    /**
     * RSA加密
     * @param data      待加密数据
     * @param publicKey 公钥
     * @return
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        return new String(Base64.encodeBase64String(encryptedData));
    }

    /**
     * RSA解密
     *
     * @param data       待解密数据
     * @param privateKey 私钥
     * @return
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * APP端获取密码串,RSA解密
     */
    public static String decryptByPrivateKey(String loginPwd, String RSAPrivateKey) throws Exception {
        PrivateKey privateKey  = RSATools.getPrivateKey(RSAPrivateKey);
        String phone = RSATools.decrypt(loginPwd, privateKey);
        return phone;
    }


   public static void main(String[] args) {
        try {
            Map<String,Object> map = new RSATools().getKeyPair();
            // RSA加密
            String data = "111111";
            String encryptData = encrypt(data, getPublicKey(map.get("publicKey").toString()));
            System.out.println("加密后内容:" + encryptData);
            // RSA解密
            String decryptData = decrypt(encryptData, getPrivateKey(map.get("privateKey").toString()));
            System.out.println("解密后内容:" + decryptData);
        }catch (Exception e){
            e.printStackTrace();
        }
        // Map<String,Object> map = new RSATools().getKeyPair();
        // System.out.println(map.get("privateKey"));
        // System.out.println("   ------------    --------- ------- ");
        // System.out.println(map.get("publicKey"));

       // System.out.println(DigestUtils.md5DigestAsHex("123456".getBytes()));

    }

}

 

posted @ 2022-06-23 17:55  繁华纤尽依然保持初心  阅读(494)  评论(0)    收藏  举报