RSA 数据加密解密

 下述代码中:PUBLIC_KEY 和 PRIVATE_KEY 可自己生成后替换即可。

package com.bing.security.util;



import org.apache.commons.codec.binary.Hex;

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

/**
 * @package:com.bing.security.util
 * @des: 数据加密解密工具类
 * @autor :Ryan Wang
 * @createTime: 2018/2/9-11:29
 */
public class SecurityUtil {

    /**
     * 对数据加密生成16进制字符串
     * @param data 要处理的字符串
     */
    public static String encryptDataAsHex(String data) {
        byte[] bytes = encryptData(data);
        return Hex.encodeHexString(bytes).toUpperCase();
    }

    /**
     * 对数据加密并进行Base64转码
     * @param data 要处理的字符串
     */
    public static String encryptDataAsEncode(String data) {
        byte[] bytes = encryptData(data);
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 将16进制的字符串进行解密
     * @param data
     */
    public static String decryptDataFromHex(String data) {
        if (data == null) {
            return "";
        }
        byte[] encryptData = hexStringToBytes(data);
        return new String(decryptData(encryptData));
    }

    /**
     * 将base64编码的字符串进行解密
     * @param data
     */
    public static String decryptDataFromEncode(String data) {
        if (data == null) {
            return "";
        }
        byte[] encryptData = Base64.getDecoder().decode(data);
        return new String(decryptData(encryptData));
    }

    private static byte[] decryptData(byte[] encryptData) {
        ByteArrayOutputStream outputStream = null;
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey());
            int length = encryptData.length;
            int offset = 0;
            int i = 0;
            byte[] cache;
            outputStream = new ByteArrayOutputStream();
            while (length - offset > 0) {
                /*最大解密字节长度*/
                Integer MAX_DECRYPT_BLOCK = 128;
                if (length - offset > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptData, offset, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptData, offset, length - offset);
                }
                outputStream.write(cache, 0, cache.length);
                offset = (++i) * MAX_DECRYPT_BLOCK;
            }
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputStream != null ? outputStream.toByteArray() : new byte[0];
    }

    private static byte[] encryptData(String data) {
        if (data == null) {
            return new byte[0];
        }
        ByteArrayOutputStream outputStream;
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
            int length = data.getBytes().length;
            int offset = 0;
            int i = 0;
            byte[] cache;
            outputStream = new ByteArrayOutputStream();
            while (length - offset > 0) {
                /*最大加密字节长度*/
                Integer MAX_ENCRYPT_BLOCK = 117;
                if (length - offset > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data.getBytes(), offset, length - offset);
                }
                outputStream.write(cache, 0, cache.length);
                offset = (++i) * MAX_ENCRYPT_BLOCK;
            }
            outputStream.close();
        } catch (Exception e) {
            return new byte[0];
        }
        return outputStream.toByteArray();
    }

    /**
     * 将16进制的字符串转为byte[]
     * @param hexString
     */
    private static byte[] hexStringToBytes(String hexString) {
        if (hexString == null) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] bytes = new byte[length];
        for (int i =0;i<length;i++) {
            int pos = i * 2;
            bytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return bytes;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 获取RSA public key
     */
    private static PublicKey getPublicKey() throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(Constant.PUBLIC_KEY_STR));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * 获取RSA private key
     */
    private static PrivateKey getPrivateKey() throws Exception {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(Constant.PRIVATE_KEY_STR));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }
}

 

转载于:https://my.oschina.net/firstbing/blog/1627822

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值