[JAVA] RSA非对称加密 & BCript加密校验 & 生成随机密码 工具类

import cn.hutool.crypto.digest.BCrypt;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class PasswordUtil {

    private PasswordUtil() {
    }

    private static final String CHARSET = "UTF-8";

    private static final String KEY_ALGORITHM = "RSA";

    private static final String PUBLIC_KEY = "公钥";

    private static final String PRIVATE_KEY = "私钥";

    public static void main(String[] args) {
        String pwd = "P@ss1234";
        try {
            String encryptStr = publicEncrypt(pwd, getPublicKey());
            System.out.println(encryptStr);

            String decryptStr = privateDecrypt(encryptStr, getPrivateKey());
            System.out.println(decryptStr);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }


    /**
     * TODO
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @return 加密后字符串
     */
    public static String publicEncrypt(String data, RSAPublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeBase64URLSafeString(
                    rsaSplitCode(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
        } catch (Exception e) {
            throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * TODO
     *
     * @param data       加密串
     * @param privateKey 私钥
     * @return String 解密后字符串
     */
    public static String privateDecrypt(String data, RSAPrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return new String(rsaSplitCode(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
        } catch (Exception e) {
            throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
        }
    }

    /**
     * 加密密码
     *
     * @param password 明文密码
     * @return 加密密码
     */
    public static String encodePassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt());
    }

    /**
     * 校验密码
     *
     * @param password       明文密码
     * @param encodePassword 加密密码
     * @return true/false
     */
    public static boolean match(String password, String encodePassword) {
        return BCrypt.checkpw(password, encodePassword);
    }

    /**
     * TODO
     *
     * @param len 密码长度
     * @return 随机密码
     */
    public static String generatePassword(int len) {
        if (len < 3) {
            throw new IllegalArgumentException("字符串长度不能小于3");
        }

        //数组,用于存放随机字符
        char[] chArr = new char[len];
        //为了保证必须包含数字、大小写字母
        chArr[0] = (char) ('0' + StdRandom.uniform(0, 10));
        chArr[1] = (char) ('A' + StdRandom.uniform(0, 26));
        chArr[2] = (char) ('a' + StdRandom.uniform(0, 26));
        chArr[3] = (char) ('~' + StdRandom.uniform(0, 26));

        char[] codes =
                {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                        'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
                        'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                        'y', 'z', '~', '!', '@', '#', '$', '%', '^', '&',
                        '*', '(', ')', '\\', ']', '[', '{', '}', ';', '\'',
                        ':', '\"', '<', '>', ',', '.', '/', '?', '.', '+',
                        '-'};

        //charArr[3..len-1]随机生成codes中的字符
        for (int i = 3; i < len; i++) {
            chArr[i] = codes[StdRandom.uniform(0, codes.length)];
        }

        //将数组chArr随机排序
        for (int i = 0; i < len; i++) {
            int r = i + StdRandom.uniform(len - i);
            char temp = chArr[i];
            chArr[i] = chArr[r];
            chArr[r] = temp;
        }

        return new String(chArr) + "@";
    }

    public static String rsaDecrypt(String pwd) {
        try {
            return privateDecrypt(pwd, getPrivateKey());
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static RSAPublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(PUBLIC_KEY));
        return (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
    }

    public static RSAPrivateKey getPrivateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(PRIVATE_KEY));
        return (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
    }

    private static byte[] rsaSplitCode(Cipher cipher, int mode, byte[] data, int keySize) {
        int maxBlock;
        if (mode == Cipher.DECRYPT_MODE) {
            maxBlock = keySize / 8;
        } else {
            maxBlock = keySize / 8 - 11;
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] buff;
        int i = 0;
        try {
            while (data.length > offSet) {
                if (data.length - offSet > maxBlock) {
                    buff = cipher.doFinal(data, offSet, maxBlock);
                } else {
                    buff = cipher.doFinal(data, offSet, data.length - offSet);
                }
                out.write(buff, 0, buff.length);
                i++;
                offSet = i * maxBlock;
            }
        } catch (Exception e) {
            throw new RuntimeException("加解密阀值为[" + maxBlock + "]的数据时发生异常", e);
        }
        byte[] resultData = out.toByteArray();
        IOUtils.closeQuietly(out);
        return resultData;
    }

}

import java.util.Random;

public final class StdRandom {

    private static Random random;
    
    private static long seed;

    static {
        seed = System.currentTimeMillis();
        random = new Random(seed);
    }

    private StdRandom() {}

    /**
     * 设置种子值
     * @param s 随机数生成器的种子值
     */
    public static void setSeed(long s){
        seed = s;
        random = new Random(seed);
    }

    /**
     * 获取种子值
     * @return long 随机数生成器的种子值
     */
    public static long getSeed(){
        return seed;
    }

    /**
     * 随机返回0到1之间的实数 [0,1)
     * @return double 随机数
     */
    public static double uniform(){
        return random.nextDouble();
    }

    /**
     * 随机返回0到N-1之间的整数 [0,N)
     * @param N 上限
     * @return int 随机数
     */
    public static int uniform(int N){
        return random.nextInt(N);
    }

    /**
     * 随机返回0到1之间的实数 [0,1)
     * @return double 随机数
     */
    public static double random(){
        return uniform();
    }

    /**
     * 随机返回a到b-1之间的整数 [a,b)
     * @param a 下限
     * @param b 上限
     * @return int 随机数
     */
    public static int uniform(int a,int b){
        return a + uniform(b - a);
    }

    /**
     * 随机返回a到b之间的实数
     * @param a 下限
     * @param b 上限
     * @return double 随机数
     */
    public static double uniform(double a,double b){
        return a + uniform() * (b - a);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值