RSA最全公钥私钥加密解密

package com.test;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;

@Slf4j
public class RsaUtil {


    public static void main(String[] args) throws Exception {
        String plainText = "{name:张三}";


        // 生成密钥对
        KeyPair keyPair = generateKeyPair();

        // 获取公钥和私钥
        //PublicKey publicKey = keyPair.getPublic();
        //PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = getPublicKey("");
        PrivateKey privateKey = getPrivateKey("");


        // 使用公钥加密
        /*byte[] encryptedBytes = encrypt(plainText, publicKey);
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted Text: " + encryptedText);*/

        // 使用私钥解密
       /* byte[] decryptedBytes = decrypt(encryptedBytes, privateKey);
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted Text: " + decryptedText);*/

        // 使用公钥加密
        String s = encrypt117(plainText, publicKey);
        // 使用私钥解密
        decrypt117(s, privateKey);

        // 使用私钥加密
        String s1 = encrypt117_(plainText, privateKey);
        // 使用公钥解密
        decrypt117_(s1, publicKey);

        // 使用私钥签名
        byte[] signatureBytes = sign(plainText, privateKey);
        String signatureText = Base64.getEncoder().encodeToString(signatureBytes);
        System.out.println("Signature: " + signatureText);

        // 使用公钥验证签名
        boolean isVerified = verify(plainText, signatureBytes, publicKey);
        System.out.println("Signature Verified: " + isVerified);
    }

    public static KeyPair generateKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 密钥长度为2048位
        return keyPairGenerator.generateKeyPair();
    }

    public static byte[] encrypt(String plainText, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(plainText.getBytes());
    }

    public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encryptedBytes);
    }

    public static byte[] sign(String plainText, PrivateKey privateKey) throws Exception {
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey);
        signature.update(plainText.getBytes());
        return signature.sign();
    }

    public static boolean verify(String plainText, byte[] signatureBytes, PublicKey publicKey) throws Exception {
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(publicKey);
        signature.update(plainText.getBytes());
        return signature.verify(signatureBytes);
    }


    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = decryptBASE64(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = decryptBASE64(key);
        // 修复异常:java.security.InvalidKeyException: IOException : algid parse error, not a sequence
        //Security.addProvider(new BouncyCastleProvider());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }
    public static byte[] decryptBASE64(String key) {
        return Base64.getMimeDecoder().decode(key);
    }


    //私钥加密
    public static String encrypt117_(String str, PrivateKey privateKey) throws Exception {
        //log.info("|RSA公钥加密前的数据|str:{}|publicKey:{}", str, publicKey);
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        //当长度过长的时候,需要分割后加密 117个字节
        byte[] resultBytes = getMaxResultEncrypt(str, cipher);

        String outStr = Base64.getEncoder().encodeToString(resultBytes);
        log.info("|私钥加密后的数据|outStr:{}", outStr);
        return outStr;
    }

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt117(String str, PublicKey publicKey) throws Exception {
        //log.info("|RSA公钥加密前的数据|str:{}|publicKey:{}", str, publicKey);
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        //当长度过长的时候,需要分割后加密 117个字节
        byte[] resultBytes = getMaxResultEncrypt(str, cipher);

        String outStr = Base64.getEncoder().encodeToString(resultBytes);
        log.info("|公钥加密后的数据|outStr:{}", outStr);
        return outStr;
    }

    private static byte[] getMaxResultEncrypt(String str, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
        byte[] inputArray = str.getBytes();
        int inputLength = inputArray.length;
        //log.info("|加密字节数|inputLength:{}", inputLength);
        // 最大加密字节数,超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 117;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

    //公钥解密
    public static String decrypt117_(String str, PublicKey publicKey) throws Exception {
        //log.info("|RSA私钥解密前的数据|str:{}|privateKey:{}", str, privateKey);
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
//        String outStr = new String(cipher.doFinal(inputByte));
        //当长度过长的时候,需要分割后解密 128个字节
        String outStr = new String(getMaxResultDecrypt(str, cipher));
        log.info("|RSA公钥解密后的数据|outStr:{}", outStr);
        return outStr;
    }


    /**
     * RSA私钥解密
     *
     * @param str        加密字符串
     * @param privateKey 私钥
     * @return 铭文
     * @throws Exception 解密过程中的异常信息
     */
    public static String decrypt117(String str, PrivateKey privateKey) throws Exception {
        //log.info("|RSA私钥解密前的数据|str:{}|privateKey:{}", str, privateKey);
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
//        String outStr = new String(cipher.doFinal(inputByte));
        //当长度过长的时候,需要分割后解密 128个字节
        String outStr = new String(getMaxResultDecrypt(str, cipher));
        log.info("|RSA私钥解密后的数据|outStr:{}", outStr);
        return outStr;
    }

    private static byte[] getMaxResultDecrypt(String str, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte[] inputArray = Base64.getMimeDecoder().decode(str.getBytes("UTF-8"));
        int inputLength = inputArray.length;
        //log.info("|解密字节数|inputLength:{}", inputLength);
        // 最大解密字节数,超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 128;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值