I'm having trouble encrypting/decrypting a simple string using the
System.Security.Cryptography.TripleDESCryptoServic eProvider, etc...
The encryption works, but the decryption does not properly decrypt
several of the first few characters.
Here's the code:
class TMyCipher
{
public string Encipher(string s, string key)
{
byte[] bKey = ASCIIEncoding.ASCII.GetBytes(key);
TripleDESCryptoServiceProvider TripleDesProv = new
TripleDESCryptoServiceProvider();
ICryptoTransform ict = TripleDesProv.CreateEncryptor(bKey,null);
byte[] bInput = ASCIIEncoding.ASCII.GetBytes(s);
byte[] bOutput = ict.TransformFinalBlock(bInput,0,bInput.Length);
System.Console.WriteLine(System.Text.Encoding.ASCI I.GetString(bOutput,0,bOutput.Length));
return Convert.ToBase64String(bOutput,0,bOutput.Length);
}
public string Decipher(string ciphertext, string key)
{
byte[] bKey = ASCIIEncoding.ASCII.GetBytes(key);
TripleDESCryptoServiceProvider TripleDesDec = new
TripleDESCryptoServiceProvider();
ICryptoTransform Decryptor =
TripleDesDec.CreateDecryptor(bKey,null);
System.Console.WriteLine(ciphertext);
byte[] eInput = Convert.FromBase64String(ciphertext);
System.Console.WriteLine(System.Text.Encoding.ASCI I.GetString(eInput,0,eInput.Length));
byte[] eOutput =
Decryptor.TransformFinalBlock(eInput,0,eInput.Leng th);
return System.Text.Encoding.ASCII.GetString(eOutput,0,eOu tput.Length);
}
}
string ClearText = "test-text-this-is-text";
string sKey = "mykey";
sKey = sKey.PadRight(16,' ');
byte[] bKey = ASCIIEncoding.ASCII.GetBytes(sKey);
TMyCipher ciph = new TMyCipher();
string ciphertext = ciph.Encipher(ClearText,sKey);
System.Console.WriteLine(ciphertext);
string sFinal = ciph.Decipher(ciphertext,sKey);
System.Console.WriteLine("Final: " + sFinal);
The result:
G)♠SK|YS
M♀H)←b ↨\
r2xpLw1HKQbTy/zZh9MKTYzIqZtiCRfc
r2xpLw1HKQbTy/zZh9MKTYzIqZtiCRfc
G)♠SK|YS
M♀H)←b ↨\
Final: I'|htT<#t-this-is-text