Follow @PDSAInc Beware of Encoding Types when saving to a File - Paul Sheriff's Blog for the Real World

Paul Sheriff's Blog for the Real World

This blog is to share my tips and tricks garnered over 25+ years in the IT industry

Paul's Favorites

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!

Paul

Posted: Jan 15 2007, 08:12 PM by psheriff | with 1 comment(s)
Filed under: ,

Comments

preishuber said:

i have made the same expirence with notepad

http://weblogs.asp.net/hpreishuber/archive/2005/08/06/421756.aspx

# January 16, 2007 5:02 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)