Java中从私钥获取公钥
我记得很久以前用 OpenSSL 做过这个,但我想知道它是否可能以及如何实现,我从未在 java 上使用过密码学。
I remember do this long time ago with OpenSSL, but I want to know if it's possible and how, I've never used Cryptography on java.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设我们正在谈论 RSA 私钥和公钥。然后,如果您使用 PEM 格式文件,那么首先需要将文件中的私钥读取到 PrivateKey 对象中:
其中 File2String 类似于:
现在您可以使用如下代码生成相应的 PublicKey:
...
学分:如何通过提供 RSA 公钥私钥?
The assumption is that we are talking about RSA private and Public keys. Then, if you are working from a PEM format file, then first you need to read the private key from the file into a PrivateKey object:
where File2String is something like:
Now you can generate the corresponding PublicKey with code like this:
...
Credits: How to get a RSA PublicKey by giving a PrivateKey?
请确保Eli Rosencruft的答案基本正确,但模数和公共指数的顺序不正确!这是正确的说法:
Please make sure that Eli Rosencruft answer is basically correct, but the order of the modulus and the public exponent are incorrect! This is the correct statement:
您不能直接从另一个密钥生成另一个密钥。这在数学上是不可能的。如果您有一个包含公钥和私钥的密钥 blob,则可以相对轻松地提取其中任何一个。
编辑,2017:很多年了,后来对加密有了更好的理解,现在我很清楚这个答案并不正确。
引用维基百科:
公共模数 n 可以计算为 p × q。原始私钥中唯一缺少的是 e,但该值通常选择为 65537,如果没有,您仍然可以根据 d 和 λ(n) 计算 e。
然而,许多私钥存储格式实际上包含公共模数 n 以及其他组件,因此您可以直接提取值。
编辑,2018:仍然对此投反对票,这是正确的!我留下这个答案是为了让人们知道我最初为什么错了,并提醒自己以后不要再犯错。
You cannot generate either key directly from the other. It is mathematically impossible. If you had a key blob that contained both the public and private keys, you could extract either one of them with relative ease.
EDIT, 2017: Many years and a much better understanding of crypto later, and it's now clear to me that this answer isn't really correct.
To quote Wikipedia:
The public modulus n can be computed as p × q. The only thing missing from a raw private key is e, but this value is usually selected as 65537, and if not you can still compute e from d and λ(n).
However, many private key storage formats actually contain the public modulus n alongside the other components, so you can just do a direct extraction of the values.
EDIT, 2018: Still getting downvotes for this, and rightly so! I'm leaving this answer up so people can see why I was originally wrong, and to remind myself not to be wrong in future.