Symmetrically Encrypt Any Data

Problem

You need to symmetrically encrypt data that isn’t stream-based, such as a series of variables.

Solution

Write these variables to a MemoryStream, and wrap this with a CryptoStream.

Discussion

All symmetric encryption is stream-based. If you need to convert data that’s stored in ordinary variables such as integers and strings, you must write this data to an in-memory stream.

The following Console application demonstrates this approach.

Public Module EncryptionTest Public Sub Main() ' Declare the data. Dim Name As String = "Joe Tester" Dim Age As Integer = 28 ' Create the in-memory stream. Dim ms As New System.IO.MemoryStream() ' Create the cryptographic object. Dim Rijndael As New RijndaelManaged() ' Write and encrypt ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.