从 Java 中的已知参数创建 RSA 密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2023549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating RSA keys from known parameters in Java
提问by meleager
I'm working on implementing Bing Cashback. In order to verify an incoming request from Bing as valid they provide a signature. The signature is a 160-bit SHA-1 hash of the url encrypted using RSA.
我正在努力实施 Bing Cashback。为了验证来自 Bing 的传入请求是否有效,他们提供了一个签名。签名是使用 RSA 加密的 url 的 160 位 SHA-1 哈希。
Microsoft provides the RSA "public key", modulus and exponent, with which I'm supposed to decrypt the hash.
微软提供了 RSA“公钥”、模数和指数,我应该用它来解密哈希。
Is there a way to create the Java key objects needed to decrypt the hash as Microsoft says?
有没有办法像微软所说的那样创建解密哈希所需的 Java 密钥对象?
Everything I can find creates RSA key pairs automatically since that's how RSA is supposed to work. I'd really like to use the Java objects if at all possible since that's obviously more reliable than a hand coded solution.
我能找到的所有东西都会自动创建 RSA 密钥对,因为 RSA 应该是这样工作的。如果可能的话,我真的很想使用 Java 对象,因为这显然比手动编码的解决方案更可靠。
The example code they've provided is in .NET and uses a .NET library function to verify the hash. Specifically RSACryptoServiceProvider.VerifyHash()
他们提供的示例代码在 .NET 中,并使用 .NET 库函数来验证哈希。特别是 RSACryptoServiceProvider.VerifyHash()
回答by erickson
RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory factory = KeyFactory.getInstance("RSA");
PublicKey pub = factory.generatePublic(spec);
Signature verifier = Signature.getInstance("SHA1withRSA");
verifier.initVerify(pub);
verifier.update(url.getBytes("UTF-8")); // Or whatever interface specifies.
boolean okay = verifier.verify(signature);
回答by Seva Alekseyev
Use java.security.spec.RSAPublicKeySpec. It can construct a key from exponent and modulus. Then use java.security.KeyFactory.generatePublic() with key spec as a parameter.
使用 java.security.spec.RSAPublicKeySpec。它可以从指数和模数构造一个键。然后使用带有密钥规范的 java.security.KeyFactory.generatePublic() 作为参数。
回答by Jason Nichols
Something like this should do the trick:
像这样的事情应该可以解决问题:
private PublicKey convertPublicKey(String publicKey) throws Exception{
PublicKey pub = null;
byte[] pubKey = Hex.decodeHex(publicKey.toCharArray());
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
pub = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
return pub;
}
This assumes the Public key is given as a hex string, and you'll need the Apache Commons Codec library
这假设公钥以十六进制字符串形式给出,并且您将需要Apache Commons Codec 库
If you have the key in a different format, try the KeyFactoryfor more information.
如果您有不同格式的密钥,请尝试使用KeyFactory以获取更多信息。

