Saturday, June 04, 2005

How To Encrypt A Variable

Something that has been bothered me for years is how to store data in memory, but in a secure way so that nobody can use a program like ArtMoney to search for it in memory and change the value. This would be important for transmitting secure data across the net or storing the health data of a video game character if you rally didn't want anybody to change it.

So I created this test app:

Image Hosted by

It takes an Integer and stores it in memory by using two methods. The first just stores the number normally and the second stores it via a secure method.

This method isn't as robust as I probably would have liked and I don't fully understand how it is generating the encryption key, and this is the first time I have worked with data streams which is probably why I have had a little trouble, but it works.

In the declerative space:

Private ms As New System.IO.MemoryStream 'memory stream in memmory
Private Rijndael As New Security.Cryptography.RijndaelManaged() 'encryption class for doing the encrypting and decrypting
Private cs As New Security.Cryptography.CryptoStream(ms, Rijndael.CreateEncryptor(), Security.Cryptography.CryptoStreamMode.Write) 'links the data stream and the cryptography transformer
Private w As New System.IO.BinaryWriter(cs) 'writes the data as binary witch is needed for use with the the strwam

Then to store a varible:

w.Write(passedVal) 'writes passedval as binary to ms and uses Rijndael to encrypt the stream
cs.FlushFinalBlock() 'clears the write buffer apparently
ms.Position = 0 'sets the index back to the start of the stream, this is probably so you can write multiple bits of deta in the same stream

To access the varible:

cs = New Security.Cryptography.CryptoStream(ms, Rijndael.CreateDecryptor(), Security.Cryptography.CryptoStreamMode.Read)
Dim r As New System.IO.BinaryReader(cs)
Return r.ReadInt32 'should be r.readint32 for integers and r.ReadString for strings

And to give credit, I got the basic code from Matthew MacDonald's Visual Basic.Net Programmers Cookbook (ISBN 073561931X).