I have some C# code for encrypting and decrypting using TripleDES. I've reduced it to a minimal example for posting.
using System;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Text;
class TDes
{
static void Main() {
string key = "ABCDEF0123456789";
string iv = "ABCDEF01";
TDes tdes = new TDes(key, iv);
string dataToDecrypt = "x9iWzVc4FfU=";
string decrypted = tdes.Decrypt(dataToDecrypt,key);
Console.WriteLine(decrypted);
string dataToEncrypt = "abcdegf";
string encrypted = tdes.Encrypt(dataToEncrypt, key);
Console.WriteLine(encrypted);
}
public TripleDESCryptoServiceProvider TdesProvider;
public TDes(string Key, string IV)
{
TdesProvider = new TripleDESCryptoServiceProvider();
TdesProvider.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(Key);
TdesProvider.IV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
}
public string Decrypt(string Source, string Key)
{
long lLen;
int nRead, nReadTotal;
byte[] buf = new byte[3];
byte[] decData;
byte[] encData;
System.IO.MemoryStream sin;
System.IO.MemoryStream sout;
CryptoStream decStream;
encData = System.Convert.FromBase64String(Source);
sin = new MemoryStream(encData);
sout = new MemoryStream();
decStream = new CryptoStream(sin,
TdesProvider.CreateDecryptor(),
CryptoStreamMode.Read);
lLen = sin.Length;
nReadTotal = 0;
while (nReadTotal < lLen)
{
nRead = decStream.Read(buf, 0, buf.Length);
if (0 == nRead) break;
sout.Write(buf, 0, nRead);
nReadTotal += nRead;
}
decStream.Close();
decData = sout.ToArray();
ASCIIEncoding ascEnc = new ASCIIEncoding();
return ascEnc.GetString(decData);
}
public string Encrypt(string Source, string Key)
{
long lLen;
int nRead, nReadTotal;
byte[] buf = new byte[3];
byte[] srcData;
byte[] encData;
System.IO.MemoryStream sin;
System.IO.MemoryStream sout;
CryptoStream encStream;
srcData = System.Text.ASCIIEncoding.ASCII.GetBytes(Source);
sin = new MemoryStream();
sin.Write(srcData,0,srcData.Length);
sin.Position = 0;
sout = new MemoryStream();
encStream = new CryptoStream(sout,
TdesProvider.CreateEncryptor(),
CryptoStreamMode.Write);
lLen = sin.Length;
nReadTotal = 0;
while (nReadTotal < lLen)
{
nRead = sin.Read(buf, 0, buf.Length);
encStream.Write(buf, 0, nRead);
nReadTotal += nRead;
}
encStream.Close();
encData = sout.ToArray();
return System.Convert.ToBase64String(encData);
}
}
This works(in the sense that it can decrypt what it encrypts with the same key and iv). However, I have been failing to come up with the equivalent in openssl. Most recent thing I've tried:
echo abcdefg | openssl enc -e -des-ede3-cbc -a -k ABCDEF0123456789 -iv ABCDEF01
U2FsdGVkX1+o9K0itpYTEqGfyMjN8gARTYIDB2ZHg1U=
The C# code produced a VERY different result of x9iWzVc4FfU=
Likewise if I feed x9iWzVc4FfU=
into the inverse openssl command it barfs.
I'm pulling my hair out on this. The c# code is unchangeable. Needs to be openssl as I'm using php.