VB.NET How to encrypt and decrypt a string (password) using Rijndael cipher.

The Rijndael algorithm is part of AES (Advanced encryption standard) which is approved by US government as enough secure way of protecting data.

The .NET offers pretty easy way for encrypting and decrypting data using Rijndael cipher:

Dim cryptography As New System.Security.Cryptography.RijndaelManaged
Dim ms As New MemoryStream()
Dim cs As New CryptoStream(ms, _
cryptography.CreateEncryptor(ASCIIEncoding.ASCII.GetBytes("[16 bytes ascii string]"), _
ASCIIEncoding.ASCII.GetBytes([16 bytes ascii string])), CryptoStreamMode.Write)
Dim sw As New StreamWriter(cs)
Dim encryptedString As String = _
Convert.ToBase64String(ms.GetBuffer(), 0, CType(ms.Length, Integer))

The example encrypts inputString using for private key and salt two 16 bytes ascii strings. The private key and salt can be predefined as byte arrays . The result is 128 bit encrypted string stored in encryptedString.

Dim cryptography As New System.Security.Cryptography.RijndaelManaged
Dim buf As Byte() = Convert.FromBase64String(encryptedString.Trim())
Dim ms As New MemoryStream(buf)
ms.Position = 0
Dim cs As New CryptoStream(ms, _
cryptography.CreateDecryptor(ASCIIEncoding.ASCII.GetBytes("[16 bytes ascii string]"), _
ASCIIEncoding.ASCII.GetBytes("[16 bytes ascii string]")), _
Dim sr As New StreamReader(cs)
Dim decryptedString As String = sr.ReadToEnd()

The encrypted string is decrypted using the same private key and salt as in the encrytpion in and it is stored in
decryptedString finally.