加密在JavaScript中不会解密在C# [英] Encrypt in JavaScript will not decrypt in C#

查看:185
本文介绍了加密在JavaScript中不会解密在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在JavaScript中使用RSA加密,然后在C#中解密。在JavaScript中我使用的库jsencrypt。在
C#我使用API​​bouncy城​​堡。当我做同样的语言内的加密/解密一切正常。当我解密时,我得到
正确的文本。当我尝试解密在C#什么是加密的JavaScript我得到什么关闭。
我确定两个键之间的键是相同的。
代码示例如下。

I am trying to use RSA encryption in JavaScript and then decrypt it in C#. In JavaScript I am using the library jsencrypt. In C# I using the API "bouncy castle". When I do the encryption/decryption within the same language everything works. I get back the correct text when I decrypt it. When I try to decrypt in C# what was encrypted in JavaScript I get nothing close. I am sure the keys are the same between the two. An example of the code is below. Any help on how to solve this would be greatly appreciated.

JavaScript

JavaScript

//using jsencrypt.min.js

var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());

取我从JavaScript加密获得的值,并在C#中使用encyp p>

take the value I get from JavaScript "encrypted" and use it in C# for "encyp"

    AsymmetricCipherKeyPair KeyParameterPrivate;
        byte[] cipheredBytes = Convert.FromBase64String(encyp);


        string privateKeyFileName = @"C:\private.pem";
        using (var fileStream2 = File.OpenText(privateKeyFileName))
        {
            PemReader pemReader2 = new Org.BouncyCastle.OpenSsl.PemReader(fileStream2);
            KeyParameterPrivate = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)pemReader2.ReadObject();
        }
        IAsymmetricBlockCipher cipher2 = new Org.BouncyCastle.Crypto.Engines.RsaEngine();
        RsaKeyParameters privateKey2 = (RsaKeyParameters)KeyParameterPrivate.Private;
        //cipher.Init(false, publicKey4);
        cipher2.Init(false, privateKey2);
        byte[] deciphered = cipher2.ProcessBlock(cipheredBytes, 0, cipheredBytes.Length);
        string decipheredText = utf8enc.GetString(deciphered);


推荐答案

告诉我它是否适合你。 >

Tell me if it works for you.

public string Decrypt(RSACryptoServiceProvider provider, string toDecrypt)
{
    var input = Convert.FromBase64String(toDecrypt);
    IEnumerable<byte> output = new List<byte>();
    for (var i = 0; i < input.Length; i = i + Length)
    {
        var length = Math.Max(input.Length - i, 128);
        var block = new byte[length];
        Buffer.BlockCopy(input, i, block, 0, length);
        var chunk = provider.Decrypt(block, false);
        output = output.Concat(chunk);
    }
    return Encoding.UTF8.GetString(output.ToArray());
}

这篇关于加密在JavaScript中不会解密在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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