RSA

RSA工具类:

main方法生成公私钥


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
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;


@Slf4j
@Component
public class RsaGenerator {

    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private static final String RSA = "RSA";
    private static final int KEY_SIZE = 2048;
    private static final int ENCRYPT_MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11;
    private static final int DECRYPT_MAX_ENCRYPT_BLOCK = KEY_SIZE / 8;

    @Value("${rsa.public-key}")
    private String publicKey;
   
    @Value("${rsa.private-key}")
    private String privateKey;

    /**
     * 随机生成密钥对
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA);
        // 初始化密钥对生成器
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 公钥-私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        String publicKeyString = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyString = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        log.info("公钥:" + publicKeyString);
        log.info("私钥:" + privateKeyString);
    }

    /**
     * RSA公钥加密
     *
     * @param message 加密字符串
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public String encrypt(String message) throws Exception {
        //base64编码的公钥,    用base64处理下主要是将字符串内的不可见字符转换成可见字符,防止不同机器处理错误
        byte[] decoded = Base64.getDecoder().decode(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        // 标识
        int offSet = 0;
        byte[] cache;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] source = message.getBytes();
        int length = source.length;
        while (true) {
            int sub = length - offSet;
            if (sub > ENCRYPT_MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(source, offSet, ENCRYPT_MAX_ENCRYPT_BLOCK);
                offSet += ENCRYPT_MAX_ENCRYPT_BLOCK;
            } else if (sub != 0) {
                cache = cipher.doFinal(source, offSet, sub);
                offSet = length;
            } else {
                break;
            }
            out.write(cache, 0, cache.length);
        }
        out.close();
        return Base64.getEncoder().encodeToString(out.toByteArray());
    }

    /**
     * RSA私钥解密
     *
     * @param sign 待解密字符串
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public String decrypt(String sign) throws Exception {
        //base64编码的私钥
        byte[] decoded = Base64.getDecoder().decode(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        // 标识
        int offSet = 0;
        byte[] cache;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        //64位解码加密后的字符串
        byte[] signByte = Base64.getDecoder().decode(sign.getBytes());
        int length = signByte.length;
        while (true) {
            int sub = length - offSet;
            if (sub > DECRYPT_MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(signByte, offSet, DECRYPT_MAX_ENCRYPT_BLOCK);
                offSet += DECRYPT_MAX_ENCRYPT_BLOCK;
            } else if (sub != 0) {
                cache = cipher.doFinal(signByte, offSet, sub);
                offSet = length;
            } else {
                break;
            }
            out.write(cache, 0, cache.length);
        }
        out.close();
        return new String(out.toByteArray());
    }

    public static void main(String[] args) throws Exception {
        genKeyPair();
    }

}


使用过程:



文/程忠 浏览次数:0次   2023-12-14 14:33:17

相关阅读


评论:
点击刷新

↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑