为什么RSACryptoServiceProvider.Encrypt()输出不是稳定? [英] Why is RSACryptoServiceProvider.Encrypt() output not stable?
问题描述
直到今天,我生活在IM pression,使用RSA RSA加密是确定性的。毕竟,应该如何签名验证工作,如果它是不是?
Until today I was living under the impression that RSA encryption using RSA is deterministic. After all, how should signature verification work if it wasn't?
要我的大惊喜,.NETs 的RSACryptoServiceProvider
并没有一个稳定的输出加密使用相同的密钥相同的一组字节时:
To my big suprise, .NETs RSACryptoServiceProvider
does not have a stable output when encrypting the same set of bytes with the same keys:
[Fact]
public void Learning()
{
const int keySize = 1024;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(keySize);
var bytes = GenerateRandomDataWithLength( 36 );
for (int i = 0; i < 4; i++)
Assert.Equal( rsa.Encrypt( bytes, false ), rsa.Encrypt( bytes, false ) );
}
byte[] GenerateRandomDataWithLength( int length )
{
Random r = new Random();
byte[] data = new byte[length];
r.NextBytes( data );
return data;
}
我已经通过 PKCS规格脱脂和我明白RSA背后的数学,所以我真的不知道为什么我观察输出不稳定。
I have skimmed through the PKCS Specification and I do understand the math behind RSA, so I really wonder why I am observing the output to be unstable.
Mono的RSA实现有稳定的输出。 加密
的输出不稳定,不影响解密,这是非常可能的,并产生预期的数据。
Mono's RSA implementation has a stable output. The unstable output of Encrypt
does not affect decryption, which is well possible and yields the expected data.
推荐答案
RSA加密是纯粹的数学所以它会给你同样的结果每次。然而调用加密
在.NET中不是简单地做RSA加密。
RSA encryption is pure mathematic so it will give you the same result everytime. However calling Encrypt
in .NET is not simply doing RSA encryption.
为什么?的PKCS#1填充(默认情况下,当您使用假
在加密
)会尽加密结果不同,因为它包含随机数据(用于填充的目的)。
Why ? The PKCS#1 padding (default when you use false
in Encrypt
) will make every encrypted result different because it includes random data (for padding purpose).
单有同一行为(至少在我的系统,见注释)。但是,如果您使用的是 EncryptValue
,其中单声道支持,但.NET不(CryptoAPI的限制),然后点击没有填充将完成和加密的结果每次将是相同的。
Mono has the same behavior (at least on my system, see note). However if you are using EncryptValue
, which Mono supports but .NET does not (CryptoAPI limitation), then no padding will be done and the encrypted result will be identical each time.
注意:如果您有不同的结果,请填写在 http://bugzilla.xamarin.com ,包括你正在使用的版本号。
Note: If you have different results please fill a bug report on http://bugzilla.xamarin.com and include the version number you are using.
这篇关于为什么RSACryptoServiceProvider.Encrypt()输出不是稳定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!