Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Encrypting and Decrypting a String
|
951
Discussion
The CryptoString class contains only static members, except for the private instance
constructor, which prevents anyone from directly creating an object from this class.
This class uses the Rijndael algorithm to encrypt and decrypt a string. This algorithm
is found in the
System.Security.Cryptography.RijndaelManaged class. This algorithm
requires a secret key and an initialization vector; both are
byte arrays. A random
secret key can be generated for you by calling the
GenerateKey method on the
// Convert encrypted string.
string encryptedStr = Convert.ToBase64String(originalBytes);
return (encryptedStr);
}
public static string Decrypt(string encryptedStr)
{
// Unconvert encrypted string.
byte[] encryptedStrAsBytes = Convert.FromBase64String(encryptedStr);
byte[] initialText = new Byte[encryptedStrAsBytes.Length];
using (RijndaelManaged rijndael = new RijndaelManaged( ))
{
using (MemoryStream memStream = new MemoryStream(encryptedStrAsBytes))
{
if (savedKey == null || savedIV == null)
{
throw (new NullReferenceException(
"savedKey and savedIV must be non-null."));
}
// Create decryptor, and stream objects.
using (ICryptoTransform rdTransform =
rijndael.CreateDecryptor((byte[])savedKey.
Clone( ),(byte[])savedIV.Clone( )))
{
using ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata