My main method works without errors, but the decrypted message is incorrect. I am pretty sure that I am coding incorrectly, but I cannot solve the problem. Any help would be greatly appreciated.
This is my first post, so if I inadvertently violated a rule or did not adhere to a recommendation, please let me know.
static void Main(string[] args)
{
string unencryptedString = "cat";
string encryptedString;
string decryptedString;
string password = "password";
System.Console.WriteLine("Unencrypted String: " + unencryptedString);
System.Console.WriteLine("Password: " + password);
encryptedString = StandardEncryptor.Encrypt(unencryptedString, password);
System.Console.WriteLine("Encrypted String: " + encryptedString);
decryptedString = StandardEncryptor.Decrypt(encryptedString, password);
System.Console.WriteLine("Decrypted String: " + decryptedString);
System.Console.ReadLine();
}
public static string Encrypt(string message, string password)
{
byte[] messageBytes = ASCIIEncoding.ASCII.GetBytes(message);
byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(password);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, passwordBytes);
CryptoStreamMode mode = CryptoStreamMode.Write;
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(messageBytes, 0, messageBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] encryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
string encryptedMessage = Convert.ToBase64String(encryptedMessageBytes);
return encryptedMessage;
}
public static string Decrypt(string encryptedMessage, string password)
{
byte[] encryptedMessageBytes = Convert.FromBase64String(encryptedMessage);
byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(password);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, passwordBytes);
CryptoStreamMode mode = CryptoStreamMode.Write;
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] decryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);
string message = Convert.ToBase64String(decryptedMessageBytes);
return message;
}
source
share