Simple String Encryption

There is one neat little Data Protection API (DPAPI) built in since Windows 2000, and we can access it using .NET through ProtectedData class from System.Security.Cryptography namespace.

To use ProtectedData, first we need to add System.Security.Cryptography reference to our project. With 2 obvious and simple method Protect and Unprotect, which clearly stated is to encrypt and decrypt. It’s dealing with bytes, so converting from bytes and to bytes is needed.

Here’s the code example:
[cc lang=”vbnet” escaped=”true”]
‘ Create a simple byte array containing data to be encrypted.
Dim secret As Byte() = {0, 1, 2, 3, 4, 1, 2, 3, 4}

‘Encrypt and convert to string for display purpose Console.WriteLine(Text.Encoding.Default.GetString(ProtectedData.Protect(Text.Encoding.Default.GetBytes(stringToEncrypt), secret, DataProtectionScope.CurrentUser)))

‘Convert encrypted string to bytes, decrypted and converts back to string
Console.WriteLine(Text.Encoding.Default.GetString(ProtectedData.Unprotect(Text.Encoding.Default.GetBytes(data), secret, DataProtectionScope.CurrentUser)))


Cool and easy 😀


Leave a Reply

Your email address will not be published. Required fields are marked *