Why RSA encryption can return different results wi

2019-02-19 01:25发布

I using:

  • c#: RSACryptoServiceProvider
  • JAVA: KeyFactory.getInstance("RSA")+Cipher

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 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# Key Recieve:

// 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.

Thank you.

标签: c# java rsa
4条回答
淡お忘
2楼-- · 2019-02-19 01:53

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.

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.

查看更多
疯言疯语
3楼-- · 2019-02-19 01:58

RSA Encription mustn't return diffferent values with simular keys - its standardized algorithm. Check your keys.

查看更多
爷的心禁止访问
4楼-- · 2019-02-19 01:59

i hope this is helpful , in C# lough code

            byte[] rsaExp = rsaParameters.Exponent.ToByteArray();
            byte[] Modulus = rsaParameters.Modulus.ToByteArray();

            // Microsoft RSAParameters modulo wants leading zero's removed so create new array with leading zero's removed
            int Pos = 0;
            for (int i = 0; i < Modulus.Length; i++)
            {
                if (Modulus[i] == 0)
                {
                    Pos++;
                }
                else
                {
                    break;
                }
            }
            byte[] rsaMod = new byte[Modulus.Length - Pos];
            Array.Copy(Modulus, Pos, rsaMod, 0, Modulus.Length - Pos);
查看更多
不美不萌又怎样
5楼-- · 2019-02-19 02:16

RSA Parameters contains more parameters than modulus and exponent if i remember correctly. You need fully initialized rsa parameters to get the encryption correct (in .net).

Moreover, your private and private key is not even set in .net

查看更多
登录 后发表回答