.net中的混合密码系统实现。错误指定密钥不是此算法的有效大小

时间:2017-02-07 10:16:07

标签: c# cryptography encryption-symmetric hybrid encryption-asymmetric

我正在尝试实现https://en.wikipedia.org/wiki/Hybrid_cryptosystem

中提到的混合密码系统

目前我实施了以下算法

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;
        }

但是获取错误指定密钥不是此算法的有效大小。在加密对称密钥时

1 个答案:

答案 0 :(得分:1)

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

您可能需要考虑使用已实现混合加密的特定库(PGP,CMS或其中一种专有协议)。您的解决方案可能会最终运行,但是安全的。