Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

javascript - RSA Encryption and Decryption successed in JS, but Decryption fails in C#

For security, I encrypted some data, such as username, passwords, and emails in the browser by jsencrypt which is a A Javascript library to perform OpenSSL RSA Encryption, Decryption. And then I decrypt the cipher data using RSACryptoServiceProvider by C#. The public key, and private key are generated by c#:

<RSAKeyValue><Modulus>wDIL9/5eXYZB1J6yOQSJTvczV6dv7/mF3X9p+86kWCArYQmNih/Y+ktOboAjo2UyC8np5Y81yF8G/qAdSrreIwdTtZyAFlgpij2Oovmqpg4/mzL7VS6Sj/4y34+GKRczTjDjxuqTmD4F/lLNhqAwPP2RBbDvCCfmNgnNlkVNOLM=</Modulus><Exponent>AQAB</Exponent><P>wzw0EayQYOMdp6x+OQYryHEmHEu5TY+ZUU6ECOc7zL8EITM9Wm8B7nBgnYZuciJ2Wo+/4+s7E42qEJgyGifznw==</P><Q>/AOmiZxyWeexlilyxxfBjKgr+4wPLSHzbG4vUeY2wngWLTvT/CydZ9vFSXW6jMRVO3Zx8pjyI1bd4uVxZNTCbQ==</Q><DP>IuJY82eADK/IFrOtggbmP9Rn2Np267Li1DJRST3342emF0COj+AR2kbeHIduqJobx6azxMe9MIs5femT2jSVRQ==</DP><DQ>88n8Qsbq//nYmzDBbcOXYqAU3CRjUf+z4cK9V/biJkHRAjUMHrhyFNRPB38x1Zbf9MPh+xLlujYAM8xNY4NGCQ==</DQ><InverseQ>SCvWAH0faRW6h8+ZAJ25kUXsgM0JYY3SoGr7RPkoqpfHyl/41wPth4vvJqLZLnOvX/ip8SEaAE3X9W2z52rIkA==</InverseQ><D>JNJx0JV/ZtOuERpGcv4XgHWD9KszmvpnV0Rt/bxdaDThmrnF0EzBuVJsOGd8bHWa3P9WPJDvcPAj2uy6L/MVU7MHetIEx1FDMPiFXjO9bjaqyx7T9MURuxnCij2flfj/rMEaMx+iRqG+zWP6vMGF3KBFzMjv5/p8o+nKb2znR+E=</D></RSAKeyValue>

In most cases, this process successed. But about one in 100, the RSACryptoServiceProvider will raise an Exception:

System.Security.Cryptography.CryptographicException: Bad Data。

The error seems to appear randomly.

The following is some examples that jsencrypt can encrypt and decrypt, but c# failed to decrypt. The first two element of each array are the source and decrypted data by jsencrypt. The Last element of each array are the encrypted data which c# failed to decrypt.

[
  [
    "75190ba768c49c96adc7e6b048f1e856db8cf6444ce54249d3b2d24a0f480122",
    "75190ba768c49c96adc7e6b048f1e856db8cf6444ce54249d3b2d24a0f480122",
    "gOEY8LP5bYd5UTs+b5xl0MvCijsHJ+jD3hX2ewAibyhYzguB9RAn+pNHpyj0VbC2G9D62oeq2Hdu7YUlSEkEiskeqq9xBKc/xWo+21uc+ArRDdfMSDvHy6iT/KaIQY5LDAZBhv+EHGywkLOhoNSfGrHgyCMKodrIcjJKtv1TDw=="
  ],
  [
    "11b6a03043123d54b6da3f75b9e502ee5db177fbabfe168b19c46f3bebfbfd5c",
    "11b6a03043123d54b6da3f75b9e502ee5db177fbabfe168b19c46f3bebfbfd5c",
    "yX9VGY+4d4TCgE7T8hzyVZcddJPHZzsFsqEM4De1ghlC2wGIK/cKNucVzLgBeJ/VUkR0mhQbqVoWD8eLKfyXM2A1JONN5BgFFQsyOc2oCtZLzbDFk99JYM+7duoejRqM+oDFmKt4aujEYYo4Rcwch+0AfMi3gysHHfmuI/Ry4A=="
  ],
  [
    "12b5fe831e1d5718d06331d0eef2c5f3099f35cb6bcc8fdc5f9aa77df37a6419",
    "12b5fe831e1d5718d06331d0eef2c5f3099f35cb6bcc8fdc5f9aa77df37a6419",
    "IL9nOt4yq4vh2HsCACbCAyJwqMff8/t3AMRbGIYGMjP2SOtZFDeQleOsCYiLtk94lrGLpH2/Ic7KlvgkgtK0u+elbTfkiiSU6pBPiIJE424iNW6sYzCYN/i+gPHnKje9NcDt6BVaWrouDCDbDTtKZsh042iDWSsCRRD0qijdsA=="
  ],
  [
    "918aaf6fcc2fe520f26225335bb1212ac8a6ddf03d01d00c92d189ed2e0ad728",
    "918aaf6fcc2fe520f26225335bb1212ac8a6ddf03d01d00c92d189ed2e0ad728",
    "gA2Bwk7oOw8EvPcbPAF96zxbhK7knhFgEQLgbPU/as1CKfIQz4okci4FKzNx3XrkDNJ0zTcV6T8M2VHo6uCVD160y5BLfragMw5+SVMCRN+3A8Zl01TjYglFF5eChdtY9XDQ9VjSgcqKiHQT2q0lzx9M4Z71ZTtAY03MLAmnxA=="
  ],
  [
    "c72c74a99fd1b207e6532cca34a14a647325bfcfbf47a731378928a526072809",
    "c72c74a99fd1b207e6532cca34a14a647325bfcfbf47a731378928a526072809",
    "SfOl2od01PtPhPdB1ZegkG/ALcDSTyGxcgZMChrCc7HOpYN4o7rD8QeiV2kpi1UUU+F7e+p8V4EAxKdnQbiUXtnboeYY7S+up63AXhYWKDOCNIJLiLv55WQOrgj7OddW4eN6XMFe9OoAcjYLFV+ySgnEDinBoRs+FylAKqJdOQ=="
  ],
  [
    "77b8033daa528892c1282acd2492dbdb363365305c2cd428a29427620474f5a0",
    "77b8033daa528892c1282acd2492dbdb363365305c2cd428a29427620474f5a0",
    "sCloK1zYZlY4/cNEUF4kIBWavWarJk4pn3+302+zWXkaaKqVrWCtGvw9XWOSZ//XvkJHMcwuuNROs/6bUKGsgha+gKnzFSIt7yO+OaP5iBAJd7zCtYiRg5PGkzd9K6aC1MvEflIoi8J8qaziklXh2wKYnQBLumbdxe/xww7QMg=="
  ],
  [
    "d8d35d3eebe25de025844d249f2664d4de4df061d09520d3f04cccf556b766ec",
    "d8d35d3eebe25de025844d249f2664d4de4df061d09520d3f04cccf556b766ec",
    "vBHNc+3gazNDkHJfT76A99+kwy2w7/ZKTBzDN6dkYfdzR+IhRPR2IPI8vhOYW4tGlEdF+dGEFG2F6MJcAWNeVGMqWpD9g1aWqYa4cs1h3EExz9MuikpBkTJ3negm8UArJ4Dhrsa4V0m2cuvmFnBZ29w1Dfe3B9yyIJkxlIIqZQ=="
  ]
]

The following is the c# code sample to decrypt data:

public byte[] Decrypt(byte[] bytes)
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(PrivateParameters);
                return rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
            }
        }

The following is the js code sample to encrypt data:

<input id="pubkey" type="hidden" value="@Model.pubkey" />
<input id="prikey" type="hidden" value="@Model.prikey" />
<script type="text/javascript" src="/scripts/crypto/crypto-js.min.js"></script>
<script type="text/javascript" src="/scripts/crypto/jsencrypt.min.js"></script>
<div id="vue-app">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12" v-for="c in cipher">
                {{ c }}
            </div>
        </div>        
    </div>
</div>
<script>
    $(function(){
        var pubkey = $("#pubkey").val();
        var prikey = $("#prikey").val();
        window.encryptor = new JSEncrypt();
        encryptor.setPublicKey(pubkey);       
        window.decryptor = new JSEncrypt();
        decryptor.setPrivateKey(prikey);
        function task(){
            var src = CryptoJS.SHA256(Math.uuid()).toString();                
            var cipher = encryptor.encrypt(src);
            var plain = decryptor.decrypt(cipher)
            var args = { src: src, cipher: cipher, plain: plain  }
            $.post("/api/test/view/rsa", args, function(msg){
                if(msg.error){
                    app.cipher.push([args.cipher==msg.message,args]);
                }
                else{
                    console.log(args)
                }
            });
            setTimeout(task, 1);
        }
        task();
    });
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your javascript encryption is producing results that do not conform to the RSAES-PKCS1-V1_5-ENCRYPT specification.

Your modulus is a 1024-bit number (128 bytes). Therefore the output of all encrypted messages will be 128 bytes.

https://www.rfc-editor.org/rfc/rfc3447#section-7.2.1:

c. Convert the ciphertext representative c to a ciphertext C of length k octets (see Section 4.1):

C = I2OSP (c, k).

("of length k", not "of length up to k").

The third values that you've presented all end with ==, which means that the number of bytes mod 3 is 1. But 128 mod 3 is 2. Therefore the output here is not a legal output of I2OSP(c, 128).

The javascript library you are using is leaving off the leading zeros. So to fix this in .NET you would do

public byte[] Decrypt(byte[] bytes)
{
    using (var rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportParameters(PrivateParameters);

        // Correct the error in the JS encryptor.
        if (bytes.Length < rsa.KeySize / 8)
        {
            byte[] tmp = new byte[rsa.KeySize / 8];
            Buffer.BlockCopy(bytes, 0, tmp, tmp.Length - bytes.Length, bytes.Length);
            bytes = tmp;
        }

        return rsa.Decrypt(bytes, RSAEncryptionPadding.Pkcs1);
    }
}

Note that I didn't say + 1, because given the observed behavior of the javascript library, if the encryption produced a value which should have started with 00 00 it will leave off both of them.

And filing a bug with the library owner seems good :).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...