I have a legacy application which uses OpenSSL to encrypt a string using DES3
.
These are the parameters that are set for OpenSSL:
OpenSSL enc -des3 -nosalt -a -A -iv 1234567890123456 -K 1234567890123456...48
The key is a string of 48 digits and the iv is a substring of the first 16 digits of this key.
Now, I am trying to replicate this functionality with C#'s System.Cryptography
library and without the use of OpenSSL if possible.
My goal is not to have to use OpenSSL and have the encryption done in native C# code.
Here is what I have got so far:
public string Encrypt(string toEncrypt, bool useHashing)
{
var _key = "48...digits...";
byte[] keyArray;
var toEncryptArray = Encoding.UTF8.GetBytes(toEncrypt);
if (useHashing)
{
var hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(_key));
hashmd5.Clear();
}
else
{
keyArray = Encoding.UTF8.GetBytes(_key);
}
var tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
// Is this even the correct cipher mode?
tdes.Mode = CipherMode.CBC;
// Should the PaddingMode be None?
tdes.Padding = PaddingMode.PKCS7;
// THIS is the line where I am currently stuck on:
tdes.IV = Encoding.UTF8.GetBytes(_key.Substring(0, 16));
var cTransform = tdes.CreateEncryptor();
var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
As written as comments in the code, I am not quite sure if I am using the correct cipher, maybe even the padding mode is incorrect and my iv has a length of 16 bytes
but only 8 bytes
are expected.
Also, I did try my luck already with or without hashing the key/iv.
Is it even possible to convert the above mentioned OpenSSL logic into plain C#?