I'm having trouble encrypting/decrypting a simple string using the
System.Security .Cryptography.T ripleDESCryptoS erviceProvider, 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.A SCII.GetBytes(k ey);
TripleDESCrypto ServiceProvider TripleDesProv = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m ict = TripleDesProv.C reateEncryptor( bKey,null);
byte[] bInput = ASCIIEncoding.A SCII.GetBytes(s );
byte[] bOutput = ict.TransformFi nalBlock(bInput ,0,bInput.Lengt h);
System.Console. WriteLine(Syste m.Text.Encoding .ASCII.GetStrin g(bOutput,0,bOu tput.Length));
return Convert.ToBase6 4String(bOutput ,0,bOutput.Leng th);
}
public string Decipher(string ciphertext, string key)
{
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(k ey);
TripleDESCrypto ServiceProvider TripleDesDec = new
TripleDESCrypto ServiceProvider ();
ICryptoTransfor m Decryptor =
TripleDesDec.Cr eateDecryptor(b Key,null);
System.Console. WriteLine(ciphe rtext);
byte[] eInput = Convert.FromBas e64String(ciphe rtext);
System.Console. WriteLine(Syste m.Text.Encoding .ASCII.GetStrin g(eInput,0,eInp ut.Length));
byte[] eOutput =
Decryptor.Trans formFinalBlock( eInput,0,eInput .Length);
return System.Text.Enc oding.ASCII.Get String(eOutput, 0,eOutput.Lengt h);
}
}
string ClearText = "test-text-this-is-text";
string sKey = "mykey";
sKey = sKey.PadRight(1 6,' ');
byte[] bKey = ASCIIEncoding.A SCII.GetBytes(s Key);
TMyCipher ciph = new TMyCipher();
string ciphertext = ciph.Encipher(C learText,sKey);
System.Console. WriteLine(ciphe rtext);
string sFinal = ciph.Decipher(c iphertext,sKey) ;
System.Console. WriteLine("Fina l: " + sFinal);
The result:
G)♠SK|YS
M♀H)←b ↨\
r2xpLw1HKQbTy/zZh9MKTYzIqZtiC Rfc
r2xpLw1HKQbTy/zZh9MKTYzIqZtiC Rfc
G)♠SK|YS
M♀H)←b ↨\
Final: I'|htT<#t-this-is-text