Ok so I have a small program that I built in C# winforms that is basically using security cryptology and I am trying to figure out what I did wrong in the code. It will encrypt the text file fine. However, when I paste the encrypted file in the textbox and hit Decrypt, it does not decrypt the file but encrypts it again.
I am wondering if I did something wrong with the code.
namespace Encrypted
{
class Encryptor
{
public static string IV = "1a1a1a1a1a1a1a1a";
public static string Key = "1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a";
public static string Encrypt (string decrypted)
{
byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(decrypted);
AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
endec.BlockSize = 128;
endec.KeySize = 256;
endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
endec.Padding = PaddingMode.PKCS7;
endec.Mode = CipherMode.CBC;
ICryptoTransform icrypt = endec.CreateEncryptor(endec.Key, endec.IV);
byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
icrypt.Dispose();
return Convert.ToBase64String(enc);
}
public static string Decrypted(string encrypted)
{
byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(encrypted);
AesCryptoServiceProvider endec = new AesCryptoServiceProvider();
endec.BlockSize = 128;
endec.KeySize = 256;
endec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
endec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
endec.Padding = PaddingMode.PKCS7;
endec.Mode = CipherMode.CBC;
ICryptoTransform icrypt = endec.CreateEncryptor(endec.Key, endec.IV);
byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
icrypt.Dispose();
return ASCIIEncoding.ASCII.GetString(enc);
}
}
}
This is the class above and below is the Form1:
namespace Encrypted
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
string dir = textBox1.Text;
Directory.CreateDirectory("data\\" + dir);
var sw = new StreamWriter("data\\" + dir + "data.ls");
string enctxt = Encryptor.Encrypt(textBox1.Text);
sw.WriteLine(enctxt);
sw.Close();
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
string dir = textBox2.Text;
Directory.CreateDirectory("data\\" + dir);
var sw = new StreamWriter("data\\" + dir + "data.ls");
string enctxt = Encryptor.Decrypted(textBox2.Text);
sw.WriteLine(enctxt);
sw.Close();
}
}
In the Decrypt button do I need to use StreamReader or StreamWriter. Once the encrypted file is in the data.ls I copy it and paste it into the text box for decrypt. However is does not decrypt, it only re-encrypts the file. Is there something I am doing wrong?
Decryptedmethod should be callingCreateDecryptor(notCreateEncryptor), correct?Decrypted. You should be encoding usingConvert.FromBase64Stringto gettextbytes.