使用BC进行RSA加密与解密

使用BC进行RSA加密与解密

项目地址

  • encrypt 加密
  • decrypt 解密

常量及静态方法:

/**
 * 加密算法
 */
private static final String ENCRYPT_ALGORITHM = "RSA/None/OAEPWithSHA-256AndMGF1Padding";

static {
    Security.addProvider(new BouncyCastleProvider());
}

1. 使用公钥加密

/**
 * 使用公钥加密
 *
 * @param publicKey 公钥
 * @param data      待加密数据明文
 * @return 密文
 * @throws NoSuchPaddingException    异常
 * @throws NoSuchAlgorithmException  异常
 * @throws NoSuchProviderException   异常
 * @throws InvalidKeyException       异常
 * @throws IllegalBlockSizeException 异常
 * @throws BadPaddingException       异常
 */
public static byte[] encrypt(PublicKey publicKey, byte[] data)
        throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM, BouncyCastleProvider.PROVIDER_NAME);
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return cipher.doFinal(data);
}

2. 使用私钥解密

/**
 * 使用私钥解密
 *
 * @param privateKey 私钥
 * @param cipherData 待解密的密文
 * @return 明文
 * @throws NoSuchPaddingException    异常
 * @throws NoSuchAlgorithmException  异常
 * @throws NoSuchProviderException   异常
 * @throws InvalidKeyException       异常
 * @throws IllegalBlockSizeException 异常
 * @throws BadPaddingException       异常
 */
public static byte[] decrypt(PrivateKey privateKey, byte[] cipherData)
        throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM, BouncyCastleProvider.PROVIDER_NAME);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(cipherData);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值