如何在Java中验证公钥和私钥对 [英] How to validate a public and private key pair in Java

查看:132
本文介绍了如何在Java中验证公钥和私钥对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以使用RSA算法在给定的私钥(例如某些* .key文件与特定的公钥匹配)是否通过RSA算法在Java中进行验证?

Is there a way to validate in java if the given private key, say certain *.key file matches with the certain public key, to a certain .pub file using RSA algorithm?

推荐答案

您可以验证密钥对是否匹配

You can verify if a key pair matches by

  • 创建挑战(足够长的随机字节序列)
  • 签署带有私钥
  • 的挑战使用公钥
  • 验证签名
  • creating a challenge (random byte sequence of sufficient length)
  • signing the challenge with the private key
  • verifying the signature using the public key

这给您足够高的置信度(几乎可以确定),如果签名验证正常,则密钥对可以匹配,而绝对可以确定密钥对不匹配.

This gives you a sufficiently high confidence (almost certainity) that a key pair matches if the signature verification is ok, and an absolute certainity that a key pair does not match otherwise.

示例代码:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);

KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

// create a challenge
byte[] challenge = new byte[10000];
ThreadLocalRandom.current().nextBytes(challenge);

// sign using the private key
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(privateKey);
sig.update(challenge);
byte[] signature = sig.sign();

// verify signature using the public key
sig.initVerify(publicKey);
sig.update(challenge);

boolean keyPairMatches = sig.verify(signature);

这篇关于如何在Java中验证公钥和私钥对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆