简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM