How to encrypt to a . txt file in Windows Forms C#?

Asked

Viewed 247 times

0

I have a job to do where I need to save data from a list to text files. These figures are for the most part, password, username, idade, nacionalidade and numeroCC. At work you are asked to store in an encrypted form username;password in a text file. The remaining data is stored in standard text files of fixed size.

Explaining further, I will have to create 6 files, 3 of them for encryption with pass and user of each type of user of the program I’m running, with an organizer, several members of the organization, and supporters who use the app to buy tickets, but for that they must be registered. Other files will have a fixed size to store the rest of the data.

How can I do the encryption part?

I’ve tried to do with the following encryption code.

    private static byte[] key = new byte[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    private static byte[] iv = new byte[10] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    public static string encripta(string text)
    {
        SymmetricAlgorithm algorithm = DES.Create();
        ICryptoTransform transform = algorithm.CreateEncryptor(key, iv);
        byte[] inputbuffer = Encoding.UTF8.GetBytes(text);
        byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
        return Convert.ToBase64String(outputBuffer);
    }
  • Why not use MD5?

  • Is it possible to do that? I’ve never worked with it :( I’ll see if I can use it and if I can implement it in the code.

  • Your question is cool, but it’s not clear enough. I recommend editing and explaining the real problem a little better and showing what you’ve tried. So it will go through review and can be reopened.

  • There are more efficient ways to encrypt data, but they use XML. See more How to: Encrypt XML Elements with Symmetric Keys.

1 answer

2


You can do the following function:

Encode

public static string Base64Encode(string plainText) {
  var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  return System.Convert.ToBase64String(plainTextBytes);
}

Decode

public static string Base64Decode(string base64EncodedData) {
  var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

And call the Base64Encode before saving and calling the Base64Decode when reading the data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.