为什么RSA加密可以返回用C#和Java不同的结果? [英] Why RSA encryption can return different results with C# and Java?
问题描述
我使用:
- C#的RSACryptoServiceProvider
- JAVA :KeyFactory.getInstance(RSA)+密码
我发送公钥(指数+模量)作为字节数组从Java到C# 。这没关系,有相同的字节。但是,当我尝试了一些数据与Java的一个键和C#加密 - 有不同的结果。
I sending public key (exponent + modulus) as byte array from java to c#. It's ok, there is the same bytes. But when i try to encrypt some data with one key in Java and c# - there is different results.
Java的密钥生成:
Java Key Generation:
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize( Config.CRYPTO_KEY_NUM_BITS );
m_KeyPair = keyGen.genKeyPair();
m_PublicKey = KeyFactory.getInstance("RSA").generatePublic(
newX509EncodedKeySpec(m_KeyPair.getPublic().getEncoded()));
byte[] exponent = m_PublicKey.getPublicExponent().toByteArray();
byte[] modulus = m_PublicKey.getModulus().toByteArray(); // then sending...
C#重点收到:
// Recieved...
m_ExternKey = new RSAParameters();
m_ExternKey.Exponent = exponent;
m_ExternKey.Modulus = modulus;
m_RsaExtern = new RSACryptoServiceProvider();
m_RsaExtern.ImportParameters(m_ExternKey);
byte[] test = m_RsaExtern.Encrypt(bytesToEncrypt, true);
和问题是加密的字节是不同的。
and problem is that encrypted bytes is different.
感谢您。
推荐答案
RSA加密是随机的。对于给定的公开密钥和给定的消息,每次尝试在加密产生字节的独特序列。这是正常的预期;随机字节被注入作为填充阶段的一部分,而不是注入随机字节将导致弱的加密系统。解密时,填充字节的位置和删除,原始邮件恢复毫发无损。
RSA encryption is randomized. For a given public key and a given message, each attempt at encryption yields a distinct sequence of bytes. This is normal and expected; random bytes are injected as part of the padding phase, and not injecting random bytes would result in a weak encryption system. During decryption, the padding bytes are located and removed, and the original message is recovered unscathed.
因此,预计您将获得与Java和C#不同的加密邮件,而且,如果你运行Java或C#代码的两倍。
Hence it is expected that you will get distinct encrypted messages with Java and C#, but also if you run your Java or C# code twice.
这篇关于为什么RSA加密可以返回用C#和Java不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!