本文介绍了相当于Java .NET的RSACryptoServiceProvider与SHA-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的数据签名code在C#

I have the following data signing code in 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());

和我想重现相同的code在Java中(安卓):

and I want reproduce the same code in 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)。加密是不一样的签名生成。不同的填充机制之一。

Use Signature.getInstance("SHA1withRSA"). Encryption is not the same as signature generation. Different padding mechanisms for one.

更新由阿夫欣

完整的解决方案:

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) {

}

这篇关于相当于Java .NET的RSACryptoServiceProvider与SHA-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:39