.NET中的混合密码系统实现。错误指定的密钥不是此算法的有效大小 [英] Hybrid cryptosystem implementation in .net. Error Specified key is not a valid size for this algorithm

查看:115
本文介绍了.NET中的混合密码系统实现。错误指定的密钥不是此算法的有效大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现 https://en.wikipedia.org/wiki中提到的混合密码系统/ Hybrid_cryptosystem

此刻我已经实现了以下算法

At the moment I have implemented following algorithm

private void button1_Click(object sender, EventArgs e)
        {
            CspParameters cspParams = new CspParameters { ProviderType = 1 };
            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams);
            string publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
            string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
            string symmericKey = "Kamran12";
            txtEncryptedData.Text = EncryptData(txtInputData.Text, symmericKey);
            string encryptedsymmetrickey = EncryptData(symmericKey, publicKey); //error line
            //string decryptsymmetrickey = encryptedsymmetrickey + privateKey;

            //string decrypteddata = encryptedData + decryptsymmetrickey;

        }

        public string EncryptData(string data, string key)
        {
            string encryptedData = null;

            byte[] buffer = Encoding.UTF8.GetBytes(data);

            DESCryptoServiceProvider desCryptSrvckey = new DESCryptoServiceProvider
            {
                Key = new UTF8Encoding().GetBytes(key)
            };
            desCryptSrvckey.IV = desCryptSrvckey.Key;

            using (MemoryStream stmCipherText = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(stmCipherText, desCryptSrvckey.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(buffer, 0, buffer.Length);
                    cs.FlushFinalBlock();


                    encryptedData = Encoding.UTF8.GetString(stmCipherText.ToArray());
                }
            }
            return encryptedData;
        }

但是出现错误指定的密钥对于该算法不是有效的大小。加密对称密钥时

But getting error Specified key is not a valid size for this algorithm. at the time of encrypting the symmetric key

推荐答案

您正在尝试使用(不安全的)DES算法对RSA公钥进行加密。这总是会失败的, DESCryptoServiceProvider 不接受RSA密钥。为此,您需要一个 RSACryptoServiceProvider

You are trying to encrypt using the (insecure) DES algorithm with an RSA public key. That's always going to fail, DESCryptoServiceProvider doesn't accept RSA keys. You'd need an RSACryptoServiceProvider for that.

您可能要考虑使用已经实现了混合功能的特定库密码术(PGP,CMS或专有协议之一)。解决方案可能最终会运行,但不是是安全的。

You may want to consider using a specific library that already implements hybrid cryptography (PGP, CMS or one of the proprietary protocols). The way you are going at it your solution may run in the end, but it will not be secure.

这篇关于.NET中的混合密码系统实现。错误指定的密钥不是此算法的有效大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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