Hybrid cryptosystem implementation in .net. Error Specified key is not a valid size for this algorithm

旧时模样 提交于 2019-11-28 11:55:39

问题


I am trying to implement hybrid cryptosystem as mentioned in 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


回答1:


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.

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.



来源:https://stackoverflow.com/questions/42087158/hybrid-cryptosystem-implementation-in-net-error-specified-key-is-not-a-valid-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!