Symmetrically Encrypt a File

Problem

You want to use symmetric encryption to prevent a malicious user from viewing the contents of a file.

Solution

Wrap the FileStream with a CryptoStream that encrypts data as it’s being written to disk (or decrypts it as it’s being read).

Discussion

Symmetric encryption renders data indecipherable using a secret value. To decrypt the data, you need the same secret value (or key) that was used to encrypt the data. For that reason, symmetric encryption is often described as shared secret encryption.

Several classes provide symmetric encryption services in the System.Security.Cryptography namespace. These classes all derive from the base System.Security.SymmetricAlgorithm class, and they work almost identically. The difference ...

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.