gpt4 book ai didi

c# - 具有 SHA-1 的 .NET RSACryptoServiceProvider 的 Java 等价物

转载 作者:塔克拉玛干 更新时间:2023-11-02 18:50:51 25 4
gpt4 key购买 nike

我在 C# 中有以下数据签名代码

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

string PrivateKeyText = "<RSAKeyValue><Modulus>....</D></RSAKeyValue>";

rsa.FromXmlString(PrivateKeyText);

string data = "my data";

byte[] SignedByteData = rsa.SignData(Encoding.UTF8.GetBytes(data), new SHA1CryptoServiceProvider());

我想在 Java (Android) 中重现相同的代码:

String modulusElem = "...";
String expElem = "...";

byte[] expBytes = Base64.decode(expElem, Base64.DEFAULT);
byte[] modulusBytes = Base64.decode(modulusElem, Base64.DEFAULT);

BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, expBytes);

try {
KeyFactory factory = KeyFactory.getInstance("RSA");

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");

String data = "my data";

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hashedData = md.digest(data.getBytes("UTF-8"));

RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modulus, exponent);

PublicKey publicKey = factory.generatePublic(pubSpec);

cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] SignedByteData = cipher.doFinal(hashedData);

} catch (Exception e){

}

但我得到不匹配的输出字节数组。我哪里错了,Cipher.getInstance(...) 中应该使用什么转换?

最佳答案

使用 Signature.getInstance("SHA1withRSA") .加密与签名生成不同。不同的填充机制。


Afshin 更新

完整的解决方案。注意私有(private)指数的使用,即 <D> ,而不是公众<Exponent>

String modulusElem = "...";
String dElem = "...";

byte[] modulusBytes = Base64.decode(modulusElem, Base64.DEFAULT);
byte[] dBytes = Base64.decode(dElem, Base64.DEFAULT);

BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger d = new BigInteger(1, dBytes);

String data = "my data";

try {
Signature signature = Signature.getInstance("SHA1withRSA");

KeyFactory factory = KeyFactory.getInstance("RSA");

RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(modulus, d);

PrivateKey privateKey = factory.generatePrivate(privateKeySpec);

signature.initSign(privateKey);

signature.update(data.getBytes("UTF-8"));

byte[] SignedByteData = signature.sign();

} catch(Exception e) {
e.printStackTrace();
}

关于c# - 具有 SHA-1 的 .NET RSACryptoServiceProvider 的 Java 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21377510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com