将C#RSACryptoServiceProvider代码转换为Java [英] Translating C# RSACryptoServiceProvider code to Java

查看:184
本文介绍了将C#RSACryptoServiceProvider代码转换为Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 我们需要为项目相关目的加密字符串,并为供应商提供以下代码。 string EncryptString(string StringToEncrypt)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
串的xmlString = LT; RSAKeyValue><模量> qqoWhMwGrrEBRr92VYud3j + iIEm7652Fs20HvNckH3tRDJIL465TLy7Cil8VYxJre69zwny1aUAPYItybg5pSbSORmP + hMp6Jhs + mg3qRPvHfNIl23zynb4kAi4Mx / yEkGwsa6L946lZKY8f9UjDkLJY7yXevMML1LT + H / a0a38 = LT; /模量><指数> AQAB< /指数>< P> 20PwC7nSsfrfA9pzwSOnRYdbhOYivFSuERxvXHvNjCll5XdmFYYp1d2evXcXbyj3E1k8azce1avQ9njH85NMNQ = = LT; / P>< Q> x0G0lWcQ13NDhEcWbA7R2W5LPUmRqcjQXo8qFIaHk7LZ7ps9fAk / kOxaCR6hvfczgut1xSpXv6rnQ5IGvxaHYw ==< / Q>< DP> lyybF2qSEvYVxvFZt8MeM / jkJ5gIQPLdZJzHRutwx39PastMjfCHbZW0OYsflBuZZjSzTHSfhNBGbXjO22gmNQ ==< / DP>< DQ> NJVLYa4MTL83Tx4vdZ7HlFi99FOI5ESBcKLZWQdTmg + 14XkIVcZfBxDIheWWi3pEFsWqk7ij5Ynlc / iCXUVFvw ==< / DQ> < InverseQ> X5Aw9YSQLSfTSXEykTt7QZe6SUA0QwGph3mUae6A2SaSTmIZTcmSUsJwhL7PLNZKbMKSWXfWoemj0EVUpZbZ3Q ==< / InverseQ>< d取代; jQL4lEUYCGNMUK6GEezIRgiB5vfFg8ql3DjsOcXxnOmBcEeD913kcYnLSBWEUFW55Xp0xW / RXOOHURgnNnRF3Ty5UR73jPN3 / 8QgMSxV8OXFo3 + QvX + KHNHzf2cjKQDVObJTKxHsHKy + L2qjfULA4e + 1cSDNn5zIln2ov51Ou3E = LT; / d取代;< / RSAKeyValue>中;
provider.FromXmlString(xmlString);
return Convert.ToBase64String(provider.Encrypt(Encoding.ASCII.GetBytes(StringToEncrypt),false));
}

但是,我需要修改或翻译成JAVA。我已经为同样的目的写了下面的方法。

  public static String EncryptString(String strToBeEncrypted)throws NoSuchAlgorithmException,InvalidKeySpecException,NoSuchPaddingException, InvalidKeyException将,UnsupportedEncodingException,IllegalBlockSizeException,BadPaddingException 
{
字符串modulusString = qqoWhMwGrrEBRr92VYud3j + iIEm7652Fs20HvNckH3tRDJIL465TLy7Cil8VYxJre69zwny1aUAPYItybg5pSbSORmP + hMp6Jhs + mg3qRPvHfNIl23zynb4kAi4Mx / yEkGwsa6L946lZKY8f9UjDkLJY7yXevMML1LT + H / a0a38 =;
String publicExponentString =AQAB;
byte [] modulusBytes = Base64.decodeBase64(modulusString);
byte [] exponentBytes = Base64.decodeBase64(publicExponentString);
BigInteger modulus = new BigInteger(1,modulusBytes);
BigInteger publicExponent = new BigInteger(1,exponentBytes);
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus,publicExponent);
KeyFactory fact = KeyFactory.getInstance(RSA);
PublicKey pubKey = fact.generatePublic(rsaPubKey);
密码密码= Cipher.getInstance(RSA / ECB / PKCS1PADDING);
cipher.init(Cipher.ENCRYPT_MODE,pubKey);
byte [] plainBytes = strToBeEncrypted.getBytes(US-ASCII);
byte [] cipherData = cipher.doFinal(plainBytes);
String encryptedStringBase64 = Base64.encodeBase64String(cipherData);

return encryptedStringBase64;
}

但示例结果不符。



的字符串是 4111111111111111 和加密的结果应该是:




PfU31ai9dSwWX4Im19TlikfO9JetkJbUE + btuvpBuNHTnnfrt4XdM4PmGA19z8rF + lPUC / kcOEXciUSxFrAPyuRJHifIDqWFbbJvPhatbf269BXUiAW31UBX3X5bBOqNWjh4LDitYY0BtarlTU4xzOFyb7vLpLJe9aHGWhzs6q0 =


Cxp5AIzTHEkrU6YWwYo5yYvpED2qg9IC / 0CT + tRgDZi9fJb8LAk + E1l9ljEt7MFQ2KB / exo4NYwijnBKYPeLStXyfVO1Bj6S76zMeKygAlCtDukq1UhJaJKaCXY94wi9Kel09VTmj + VByIYvAGUFqZGaK1CyLnd8QXMcdcWi3sA =



解决方案

每个加密算法需要被随机化以提供语义安全性。否则,攻击者可能会注意到您再次发送相同的消息,只需通过观察密文。在对称密码中,该属性通过随机IV来实现。在RSA中,这是通过随机填充(PKCS#1 v1.5类型2和PKCS#1 v2.x OAEP是随机的)实现的。



您可以检查是否通过使用相同的密钥和明文再次运行加密,并将密文与先前的密文进行比较,对填充进行随机化。如果密文在执行之间的C#或Java中发生变化,那么您将无法通过查看密文来判断加密是否兼容。



检查这一点的方式是加密某种语言,然后在另一种语言中进行解密。为了完全兼容,您还应该尝试其他方式。



看看你的代码,两者看起来都相当,因为 false 作为第二个参数传递到 RSACryptoServiceProvider#加密使用PKCS#1 v1.5填充和 Cipher.getInstance(RSA / ECB / PKCS1PADDING)请求相同的填充。输入/输出编码也似乎相当。所以,是的,这段代码将是等价的。






PKCS#1 v1.5填充现在不应该被使用,因为它容易受到Bleichenbacher攻击(参考)的攻击。您应该使用OAEP进行加密和PSS进行签名,这被认为是安全的。 C#和Java都支持OAEP,但是使用的默认哈希函数可能会有差异(hash和MGF1)。


I need to encrypt String for project related purpose and was given the below code for the same by vendor.

public static string EncryptString(string StringToEncrypt)
{
    RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
    string xmlString = "<RSAKeyValue><Modulus>qqoWhMwGrrEBRr92VYud3j+iIEm7652Fs20HvNckH3tRDJIL465TLy7Cil8VYxJre69zwny1aUAPYItybg5pSbSORmP+hMp6Jhs+mg3qRPvHfNIl23zynb4kAi4Mx/yEkGwsa6L946lZKY8f9UjDkLJY7yXevMML1LT+h/a0a38=</Modulus><Exponent>AQAB</Exponent><P>20PwC7nSsfrfA9pzwSOnRYdbhOYivFSuERxvXHvNjCll5XdmFYYp1d2evXcXbyj3E1k8azce1avQ9njH85NMNQ==</P><Q>x0G0lWcQ13NDhEcWbA7R2W5LPUmRqcjQXo8qFIaHk7LZ7ps9fAk/kOxaCR6hvfczgut1xSpXv6rnQ5IGvxaHYw==</Q><DP>lyybF2qSEvYVxvFZt8MeM/jkJ5gIQPLdZJzHRutwx39PastMjfCHbZW0OYsflBuZZjSzTHSfhNBGbXjO22gmNQ==</DP><DQ>NJVLYa4MTL83Tx4vdZ7HlFi99FOI5ESBcKLZWQdTmg+14XkIVcZfBxDIheWWi3pEFsWqk7ij5Ynlc/iCXUVFvw==</DQ><InverseQ>X5Aw9YSQLSfTSXEykTt7QZe6SUA0QwGph3mUae6A2SaSTmIZTcmSUsJwhL7PLNZKbMKSWXfWoemj0EVUpZbZ3Q==</InverseQ><D>jQL4lEUYCGNMUK6GEezIRgiB5vfFg8ql3DjsOcXxnOmBcEeD913kcYnLSBWEUFW55Xp0xW/RXOOHURgnNnRF3Ty5UR73jPN3/8QgMSxV8OXFo3+QvX+KHNHzf2cjKQDVObJTKxHsHKy+L2qjfULA4e+1cSDNn5zIln2ov51Ou3E=</D></RSAKeyValue>";
    provider.FromXmlString(xmlString);
    return Convert.ToBase64String(provider.Encrypt(Encoding.ASCII.GetBytes(StringToEncrypt), false));
}

However I need to modify or translate it to JAVA. I have wrote the below method for the same purpose.

public static String EncryptString(String strToBeEncrypted) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException
{
    String modulusString = "qqoWhMwGrrEBRr92VYud3j+iIEm7652Fs20HvNckH3tRDJIL465TLy7Cil8VYxJre69zwny1aUAPYItybg5pSbSORmP+hMp6Jhs+mg3qRPvHfNIl23zynb4kAi4Mx/yEkGwsa6L946lZKY8f9UjDkLJY7yXevMML1LT+h/a0a38=";
    String publicExponentString = "AQAB";
    byte[] modulusBytes = Base64.decodeBase64(modulusString);
    byte[] exponentBytes = Base64.decodeBase64(publicExponentString);
    BigInteger modulus = new BigInteger(1, modulusBytes);
    BigInteger publicExponent = new BigInteger(1, exponentBytes);
    RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, publicExponent);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    PublicKey pubKey = fact.generatePublic(rsaPubKey);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] plainBytes = strToBeEncrypted.getBytes("US-ASCII");
    byte[] cipherData = cipher.doFinal(plainBytes);
    String encryptedStringBase64 = Base64.encodeBase64String(cipherData);

    return encryptedStringBase64;
}

But the sample results do not match.

String is "4111111111111111" and encrypted result should be:

PfU31ai9dSwWX4Im19TlikfO9JetkJbUE+btuvpBuNHTnnfrt4XdM4PmGA19z8rF+lPUC/kcOEXciUSxFrAPyuRJHifIDqWFbbJvPhatbf269BXUiAW31UBX3X5bBOqNWjh4LDitYY0BtarlTU4xzOFyb7vLpLJe9aHGWhzs6q0=

But the result from Java code is

Cxp5AIzTHEkrU6YWwYo5yYvpED2qg9IC/0ct+tRgDZi9fJb8LAk+E1l9ljEt7MFQ2KB/exo4NYwijnBKYPeLStXyfVO1Bj6S76zMeKygAlCtDukq1UhJaJKaCXY94wi9Kel09VTmj+VByIYvAGUFqZGaK1CyLnd8QXMcdcWi3sA=

解决方案

Every encryption algorithm needs to be randomized in order to provide semantic security. Otherwise, an attacker might notice that you've sent the same message again, just by observing ciphertexts. In symmetric ciphers, this property is achieved by a random IV. In RSA, this is achieved by a randomized padding (PKCS#1 v1.5 type 2 and PKCS#1 v2.x OAEP are randomized).

You can check whether the padding is randomized by running the encryption again with the same key and plaintext, and comparing the ciphertexts to previous ciphertexts. If the ciphertexts change in either C# or Java between executions, then you will not be able to tell whether the encryption is compatible, just by looking at the ciphertexts.

The proper way to check this, would be to encrypt something in one language and then decrypt in the other. For full compatibility, you should also try it the other way around.

Looking at your code, both seem equivalent, because false is passed as the second parameter into RSACryptoServiceProvider#Encrypt to use PKCS#1 v1.5 padding, and Cipher.getInstance("RSA/ECB/PKCS1PADDING") requests the same padding. The input/output encodings also seem equivalent. So, yes this code will be equivalent.


PKCS#1 v1.5 padding should not be used nowadays, because it is vulnerable against a Bleichenbacher attack (reference). You should use OAEP for encryption and PSS for signing, which are considered secure. C# and Java both support OAEP, but there may be differences in the default hash functions that are used (hash and MGF1).

这篇关于将C#RSACryptoServiceProvider代码转换为Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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