Beware of Encoding Types when saving to a File

I learned something today... I was doing some Encryption of strings using DPAPI and converting them to a Base64 string and everything worked fine when I was encrypting and decrypting. However, when I saved the Base64 string to a file, then re-read the data and tried to decrypt the data, it would not work. It took me quite awhile to figure out what was going on.

I realized that when saving text using the WriteAllText method on the File class, you need to specify the Encoding type. For example:

File.WriteAllText(C:\Temp\Test.txt, "This is some text", System.Text.Encoding.UTF8)

Now the above example uses just plain text, but when you are using doing encryption and decryption and you are translating a string to an array of bytes, you use one of the encoding mechanisms to do the conversion. For example:

bytArray = Encoding.UTF8.GetBytes(strValue)

So in this case if you use UTF encoding to translate a string into an array of bytes prior to doing the encryption, you need to make sure that you store these characters to a file using the same encoding mechanism.

I hope this helps someone else, so you won't have to go through the same agony I did!


Past Blog Content

Blog Archive

1 Comment

Comments have been disabled for this content.