本文记录使用java生成公钥私钥,将公钥私钥转换成字符串,验证公钥私钥是否匹配。

验证公钥私钥是否匹配的思想:使用公钥对字符串进行加密,再使用私钥进行解密,若解密生成的字符串与原字符串一致,则说明公钥私钥匹配。

引入第三方依赖bouncycastle:

        <dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.68</version></dependency>

实现代码:

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
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;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;import org.bouncycastle.jce.provider.BouncyCastleProvider;import java.util.Base64;
import java.util.Random;/*** 该类用于生成公钥私钥,并且验证公钥私钥是否匹配* 使用方法:* 1.生成公钥私钥: 使用new RSAEncrypt()创建对象,之后调用get方法即可获取生成的公钥私钥(字符串)* 2.验证公钥私钥是否匹配: 调用静态方法verifyPublicAndPrivateKey(),传入公钥私钥字符串,返回boolean判断是否匹配*/
public class RSAEncrypt {private RSAPrivateKey privateKey;private RSAPublicKey publicKey;public RSAEncrypt() {genKeyPair();}/*** 获取私钥字符串** @return 当前的私钥字符串*/public String getPrivateKeyStr() {KeyFactory keyFactory = null;String privateKeyStr = null;try {//将私钥对象转换为字符串keyFactory = KeyFactory.getInstance("RSA");PKCS8EncodedKeySpec keySpec = keyFactory.getKeySpec(privateKey, PKCS8EncodedKeySpec.class);byte[] buffer = keySpec.getEncoded();privateKeyStr = Base64.getEncoder().encodeToString(buffer);} catch (NoSuchAlgorithmException e) {System.err.println("无此算法");} catch (InvalidKeySpecException e) {System.err.println("私钥非法");}return privateKeyStr;}/*** 获取公钥字符串** @return 当前的公钥字符串*/public String getPublicKeyStr() {KeyFactory keyFactory = null;String publicKeyStr = null;try {//将公钥对象转换为字符串keyFactory = KeyFactory.getInstance("RSA");X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class);byte[] buffer = keySpec.getEncoded();publicKeyStr = Base64.getEncoder().encodeToString(buffer);} catch (NoSuchAlgorithmException e) {System.err.println("无此算法");} catch (InvalidKeySpecException e) {System.err.println("公钥非法");}return publicKeyStr;}/*** 随机生成公钥-私钥*/private void genKeyPair() {KeyPairGenerator keyPairGen = null;try {keyPairGen = KeyPairGenerator.getInstance("RSA");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}keyPairGen.initialize(1024, new SecureRandom());KeyPair keyPair = keyPairGen.generateKeyPair();this.privateKey = (RSAPrivateKey) keyPair.getPrivate();this.publicKey = (RSAPublicKey) keyPair.getPublic();}/*** @param publicKeyStr  公钥* @param privateKeyStr 私钥* @return boolean值判断是否匹配*/public static boolean verifyPublicAndPrivateKey(String publicKeyStr, String privateKeyStr) {RSAPublicKey publicKeyToVerify = null;RSAPrivateKey privateKeyToVerify = null;try {publicKeyToVerify = loadPublicKey(publicKeyStr);} catch (Exception e) {System.err.println("加载公钥失败-公钥非法");return false;}try {privateKeyToVerify = loadPrivateKey(privateKeyStr);} catch (Exception e) {System.err.println("加载私钥失败-私钥非法");return false;}if (publicKeyToVerify == null || privateKeyToVerify == null) {return false;}//生成随机数字符串用于验证公钥私钥是否匹配Random seed = new Random();int randomNum = seed.nextInt(1000) + 1;String randomStr = String.valueOf(randomNum);byte[] cipher = null;byte[] plainText = null;try {cipher = encrypt(publicKeyToVerify, randomStr.getBytes());plainText = decrypt(privateKeyToVerify, cipher);} catch (Exception e) {e.printStackTrace();return false;}String plainStr = new String(plainText);return plainStr.equals(randomStr);}/*** 从字符串中加载公钥** @param publicKeyStr 公钥数据字符串* @throws Exception 加载公钥时产生的异常*/private static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {RSAPublicKey loadedPublicKey = null;try {byte[] buffer = Base64.getDecoder().decode(publicKeyStr);KeyFactory keyFactory = KeyFactory.getInstance("RSA");X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);loadedPublicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);} catch (NoSuchAlgorithmException e) {throw new Exception(e);} catch (InvalidKeySpecException e) {throw new Exception(e);} catch (NullPointerException e) {throw new Exception(e);}return loadedPublicKey;}/*** 从字符串中加载私钥** @param privateKeyStr 私钥数据字符串* @throws Exception 加载私钥时产生的异常*/private static RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {RSAPrivateKey loadedPrivateKey = null;try {byte[] buffer = Base64.getDecoder().decode(privateKeyStr);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);KeyFactory keyFactory = KeyFactory.getInstance("RSA");loadedPrivateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);} catch (NoSuchAlgorithmException e) {throw new Exception("无此算法");} catch (InvalidKeySpecException e) {throw new Exception("私钥非法");} catch (NullPointerException e) {throw new Exception("私钥数据为空");}return loadedPrivateKey;}/*** 加密过程** @param publicKey     公钥* @param plainTextData 明文数据* @return 加密后的数据* @throws Exception 加密过程中的异常信息*/private static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {if (publicKey == null) {throw new Exception("加密公钥为空, 请设置");}Cipher cipher = null;try {cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] output = cipher.doFinal(plainTextData);return output;} catch (NoSuchAlgorithmException e) {throw new Exception("无此加密算法");} catch (NoSuchPaddingException e) {e.printStackTrace();return null;} catch (InvalidKeyException e) {throw new Exception("加密公钥非法,请检查");} catch (IllegalBlockSizeException e) {throw new Exception("明文长度非法");} catch (BadPaddingException e) {throw new Exception("明文数据已损坏");}}/*** 解密过程** @param privateKey 私钥* @param cipherData 密文数据* @return 明文* @throws Exception 解密过程中的异常信息*/private static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {if (privateKey == null) {throw new Exception("解密私钥为空, 请设置");}Cipher cipher = null;try {cipher = Cipher.getInstance("RSA", new BouncyCastleProvider());cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] output = cipher.doFinal(cipherData);return output;} catch (NoSuchAlgorithmException e) {throw new Exception("无此解密算法");} catch (NoSuchPaddingException e) {e.printStackTrace();return null;} catch (InvalidKeyException e) {throw new Exception("解密私钥非法,请检查");} catch (IllegalBlockSizeException e) {throw new Exception("密文长度非法");} catch (BadPaddingException e) {throw new Exception("密文数据已损坏");}}public static void main(String[] args) {RSAEncrypt rsaEncrypt = new RSAEncrypt();System.out.println("公钥:" + rsaEncrypt.getPublicKeyStr());System.out.println("私钥:" + rsaEncrypt.getPrivateKeyStr());boolean res = RSAEncrypt.verifyPublicAndPrivateKey(rsaEncrypt.getPublicKeyStr(), rsaEncrypt.getPrivateKeyStr());System.out.println("是否匹配:" + res);}
}

运行结果:

参考文章:Java中使用OpenSSL生成的RSA公私钥进行数据加解密

java验证公钥私钥是否匹配及公钥私钥与字符串相互转换相关推荐

  1. java base64转bitmap,如何将Bitmap位图与base64字符串相互转换

    先引用delphi自带的单元 uses EncdDecd; 然后就可以使用下面二个函数了: ///将Bitmap位图转化为base64字符串 function BitmapToString(img:T ...

  2. c rsa java私钥_RSA,JAVA私钥加密,C#公钥解密

    做这个东西在坑里爬了3天才爬出来,记录下供园友参考.C#程序员一枚,项目需要和Java做数据交互,对方甩了段密文和一个CER证书给我,然后我要对其密文进行解密. RSA 非对称加密,对方用私钥加密,我 ...

  3. java中使用openssl生成的rsa公私钥进行数据加解密_使用openssl生成RSA公钥和私钥对...

    在ubuntu上要使用openssl的话需要先进行安装,命令如下: sudo apt-get install openssl 安装完成就可以使用openssl了. 首先需要进入openssl的交互界面 ...

  4. 使用OpenSSL加密,使用Java解密,使​​用OpenSSL RSA公钥

    抽象 在2017年,我撰写了一个由三部分组成的系列文章,内容涉及选择最佳的哈希和加密算法. 在对该系列进行研究时,我学到了很多有关哈希和加密的知识. 我学到的最重要的事情是,尽管我必须对如何使用最安全 ...

  5. 分享一个RSA加解密工具类,公钥加密私钥解密、私钥加密公钥解密、私钥签名公钥验签、生成公钥私钥

    测试: public static void main(String[] args) {try {//生成公钥私钥Map<String, Object> map = RSAUtil.ini ...

  6. RSA-公钥加密,私钥解密 、私钥加密,公钥解密、私钥加签,公钥验签

    https://blog.csdn.net/qq_31289187/article/details/85234044 一.案例内容: RSA 公钥加密,私钥解密:     RSA 私钥加密,公钥解密: ...

  7. 公钥(Public Key)与私钥(Private Key)

    公钥(Public Key)与私钥(Private Key) 公钥(Public Key)与私钥(Private Key)是通过一种算法得到的一个密钥对(即一个公钥和一个私钥),公钥是密钥对中公开的部 ...

  8. 公钥 私钥_区块链中私钥、公钥和钱包地址三者关系

    在昨天Pi首页更新过内容中,Wes spencer提到了钱包等一系列的问题,那么小编就带大家再来回顾一下数字货币钱包的起源!一.加密数字货币钱包的概念及原理加密货币钱包是指,可以用来存储,发送和接收多 ...

  9. xshell怎么连接服务器公钥_配置xshell生成公钥和私钥,使用密钥认证方式登录服务器...

    ssh登录提供两种认证方式:口令(密码)认证方式和密钥认证方式.其中口令(密码)认证方式是我们最常用的一种,这里介绍密钥认证方式登录到linux/unix的方法. 使用密钥登录分为3步: 1.生成密钥 ...

最新文章

  1. fedora17 的 rc.local
  2. Java基础学习总结(13)——流IO
  3. php验证 js验证邮箱格式,js和php邮箱地址验证的实现方法
  4. 使用 Spring Boot CLI 运行第一个Spring boot程序
  5. 导弹拦截(洛谷-P1020)
  6. CVPR2021—SurFree:一个快速的无代替模型的黑盒攻击
  7. matlab地址结构与转换,matlab数据类型和转换
  8. 丢弃Git中的本地提交
  9. 以一种标准的办法,获取工作目录
  10. C++primer 6.7节练习
  11. android键盘表情流畅切换实现
  12. js拆字分图程序 _拆分字帖_使用方法
  13. 【转】我是一个INFP者
  14. [搞笑图片] 搞笑图片
  15. js 调用TSC打印机
  16. 机器学习算法——概率类模型评估指标4(校准可靠性曲线及预测概率直方图)
  17. 合同变换为什么是一个行变换再跟一个相应的列变换?
  18. ABAP总结之二,BDC完整版
  19. dspace安装及应用
  20. with recursive用法

热门文章

  1. 剑指 Offer 22(链表4).链表中的倒数第k个结点
  2. idea卡顿且报错:UI was frozen for xxxxx ms问题解决
  3. JPA复合主键的使用
  4. Android Studio Emulator模拟器闪退解决方法
  5. 推荐一个免费电子书下载网站
  6. 307 Temporary Redirect 解决办法
  7. Python 的Int的最大值是多少?
  8. C语言进阶——深度剖析数据在内存中的存储
  9. 极客战记计算机科学2村庄守卫,「网易官方」极客战记(codecombat)攻略-森林-村庄守卫-village-warder...
  10. python聊天表情包_如何通过Python用表情包自动回复微信拍一拍?