RSA/ECB/OAEPWithSHA-256AndMGF1Padding 2048 加解密

maven依赖

       <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.70</version> <!-- 请检查最新版本 -->
        </dependency>

加解密工具类

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * TODO
 *
 * @Author: 
 * @Date: 2024/8/19 13:06
 */
public class SignUtil {
    private static final String CHIPHER = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
    private static final String RSA = "RSA";

    /**
     * 生成公私密钥对
     * @return
     */
    public static KeyPair generateRSAKeyPair() {
        try {
            // 初始化密钥生成器
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
            keyPairGenerator.initialize(2048);
            // 生成密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            return keyPair;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  将明文加密成字节数组
     * @param plainText 明文
     * @param publicKey  公钥
     * @return
     */
    public static byte[] encrypt(String plainText, PublicKey publicKey) {
        try {
            // 加密
            Cipher cipher = Cipher.getInstance(CHIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  将明文加密成字节数组,并将字节数组转换为base64加密字符串
     * @param plainText 明文
     * @param publicKey 公钥
     * @return
     */
    public static String encryptToBase64String(String plainText, PublicKey publicKey) {
        try {
            // 加密
            Cipher cipher = Cipher.getInstance(CHIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] bytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将加密字节数组加密为明文
     * @param cipherText  密文字节数组
     * @param privateKey  私钥
     * @return
     */
    public static String decrypt(byte[] cipherText, PrivateKey privateKey) {
        try {
            // 解密
            Cipher cipher = Cipher.getInstance(CHIPHER);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decrypted = cipher.doFinal(cipherText);
            return new String(decrypted, StandardCharsets.UTF_8);
        }catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }catch (InvalidKeyException e) {
            e.printStackTrace();
        }catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将base64加密的密文 解密 为明文
     * @param base64CipherText  密文字节数组
     * @param privateKey  私钥
     * @return
     */
    public static String decryptFromBase64String(String base64CipherText, PrivateKey privateKey) {
        try {
            byte[] cipherText = Base64.getDecoder().decode(base64CipherText);
            // 解密
            Cipher cipher = Cipher.getInstance(CHIPHER);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decrypted = cipher.doFinal(cipherText);
            return new String(decrypted, StandardCharsets.UTF_8);
        }catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }catch (InvalidKeyException e) {
            e.printStackTrace();
        }catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 公钥转为字符串
     * @param publicKey
     * @return
     */
    public static String publicKeyToString(PublicKey publicKey) {
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }

    /**
     * 私钥转为字符串
     * @param privateKey
     * @return
     */
    public static String privateKeyToString(PrivateKey privateKey) {
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }

    /**
     * 公钥字符串转为公钥对象
     * @param key
     * @return
     */
    public static PublicKey stringToPublicKey(String key) {
        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 私钥字符串转为私钥对象
     * @param key
     * @return
     */
    public static PrivateKey stringToPrivateKey(String key) {
        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            return keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return null;
    }
}

测试代码

 public static void main(String[] args) {
        KeyPair keyPair = generateRSAKeyPair();
        // 公私钥可转换为字符串,方便存储进数据库或者传输
        System.out.println("私钥 " +privateKeyToString(keyPair.getPrivate()));
        System.out.println("公钥 " +publicKeyToString(keyPair.getPublic()));
        // 从数据库或者其他来源获取公私密钥字符串后,可转换成公私密钥对象
        PrivateKey privateKey = stringToPrivateKey(privateKeyToString(keyPair.getPrivate()));
        PublicKey publicKey = stringToPublicKey(publicKeyToString(keyPair.getPublic()));
        // 公钥加密
        byte[] encode = encrypt("hello!", publicKey);
        String msg = Base64.getEncoder().encodeToString(encode);
        System.out.println(msg);
        //私钥解密
        String decode = decrypt(Base64.getDecoder().decode(msg), privateKey);
        System.out.println(decode);
        // 公钥加密为base64字符串
        String s = encryptToBase64String("hello!", publicKey);
        System.out.println(s);
        //私钥解密base64字符串
        String s1 = decryptFromBase64String(s, privateKey);
        System.out.println(s1);
    }

测试效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值