Click here to Skip to main content
6,595,444 members and growing! (20,730 online)
Email Password   helpLost your password?
General Programming » Cryptography & Security » Encryption     Intermediate

Encryption/Decryption with .NET

By Frank Fang

A .NET SymmetricAlgorithm security class wrapper for in memory encryption/decryption with a private key
C#, Windows, .NET 1.0, ASP.NET, Dev
Posted:14 Mar 2002
Views:255,693
Bookmarked:69 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
33 votes for this article.
Popularity: 4.63 Rating: 3.05 out of 5
7 votes, 26.9%
1
2 votes, 7.7%
2
3 votes, 11.5%
3
5 votes, 19.2%
4
9 votes, 34.6%
5

Introduction

Encryption and Decryption

The System.Security.Cryptographic namespace within the Microsoft .NET Framework provides a variety of tools to aid in encryption and decryption. The CryptoStream class is used here to demonstrate the encryption and decryption with System.Security.Cryptographic.SymmetricAlgorithm, such as DESCryptoServiceProvider, RC2CryptoServiceProvider, and RijndaelManaged classes.

I have searched the Internet for some samples and all I found were based on the Microsoft sample code in KB Article Q307010 which basically uses input/output files as source and destination. I would like to have the encryption and decryption done in memory without having to specify source and destination files, so that I could use the code on a web server or so.

If you have any questions, please email to: fangfrank@hotmail.com

Frank Fang

Source Code

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace FangHome_Crypto
{
    /// <summary>

    /// SymmCrypto is a wrapper of System.Security.Cryptography.SymmetricAlgorithm classes

    /// and simplifies the interface. It supports customized SymmetricAlgorithm as well.

    /// </summary>

    public class SymmCrypto
    {
        /// <remarks>

        /// Supported .Net intrinsic SymmetricAlgorithm classes.

        /// </remarks>

        public enum SymmProvEnum : int
        {
            DES, RC2, Rijndael
        }

        private SymmetricAlgorithm mobjCryptoService;

        /// <remarks>

        /// Constructor for using an intrinsic .Net SymmetricAlgorithm class.

        /// </remarks>

        public SymmCrypto(SymmProvEnum NetSelected)
        {
            switch (NetSelected)
            {
                case SymmProvEnum.DES:
                    mobjCryptoService = new DESCryptoServiceProvider();
                    break;
                case SymmProvEnum.RC2:
                    mobjCryptoService = new RC2CryptoServiceProvider();
                    break;
                case SymmProvEnum.Rijndael:
                    mobjCryptoService = new RijndaelManaged();
                    break;
            }
        }

        /// <remarks>

        /// Constructor for using a customized SymmetricAlgorithm class.

        /// </remarks>

        public SymmCrypto(SymmetricAlgorithm ServiceProvider)
        {
            mobjCryptoService = ServiceProvider;
        }

        /// <remarks>

        /// Depending on the legal key size limitations of a specific CryptoService provider

        /// and length of the private key provided, padding the secret key with space character

        /// to meet the legal size of the algorithm.

        /// </remarks>

        private byte[] GetLegalKey(string Key)
        {
            string sTemp;
            if (mobjCryptoService.LegalKeySizes.Length > 0)
            {
                int lessSize = 0, moreSize = mobjCryptoService.LegalKeySizes[0].MinSize;
                // key sizes are in bits

                while (Key.Length * 8 > moreSize)
                {
                    lessSize = moreSize;
                    moreSize += mobjCryptoService.LegalKeySizes[0].SkipSize;
                }
                sTemp = Key.PadRight(moreSize / 8, ' ');
            }
            else
                sTemp = Key;

            // convert the secret key to byte array

            return ASCIIEncoding.ASCII.GetBytes(sTemp);
        }

        public string Encrypting(string Source, string Key)
        {
            byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source);
            // create a MemoryStream so that the process can be done without I/O files

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            byte[] bytKey = GetLegalKey(Key);

            // set the private key

            mobjCryptoService.Key = bytKey;
            mobjCryptoService.IV = bytKey;

            // create an Encryptor from the Provider Service instance

            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();

            // create Crypto Stream that transforms a stream using the encryption

            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);

            // write out encrypted content into MemoryStream

            cs.Write(bytIn, 0, bytIn.Length);
            cs.FlushFinalBlock();
            
            // get the output and trim the '\0' bytes

            byte[] bytOut = ms.GetBuffer();
            int i = 0;
            for (i = 0; i < bytOut.Length; i++)
                if (bytOut[i] == 0)
                    break;
                    
            // convert into Base64 so that the result can be used in xml

            return System.Convert.ToBase64String(bytOut, 0, i);
        }

        public string Decrypting(string Source, string Key)
        {
            // convert from Base64 to binary

            byte[] bytIn = System.Convert.FromBase64String(Source);
            // create a MemoryStream with the input

            System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);

            byte[] bytKey = GetLegalKey(Key);

            // set the private key

            mobjCryptoService.Key = bytKey;
            mobjCryptoService.IV = bytKey;

            // create a Decryptor from the Provider Service instance

            ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
 
            // create Crypto Stream that transforms a stream using the decryption

            CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);

            // read out the result from the Crypto Stream

            System.IO.StreamReader sr = new System.IO.StreamReader( cs );
            return sr.ReadToEnd();
        }
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Frank Fang


Member

Occupation: Web Developer
Location: United States United States

Other popular Cryptography & Security articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 58 (Total in Forum: 58) (Refresh)FirstPrevNext
GeneralMy vote of 1 PinmemberTyler Xie9:55 19 Dec '08  
GeneralPhrase I LOVE COFFEE! throws and error PinmemberDave Sopko9:23 2 Aug '07  
GeneralRe: Phrase I LOVE COFFEE! throws and error Pinmemberblackjack21500:46 17 Jul '08  
GeneralRe: Phrase I LOVE COFFEE! throws and error PinmemberBruce Burge6:57 22 Apr '09  
QuestionInvalid Length PinmemberNaeem Hassan2:10 25 Jan '07  
AnswerRe: Invalid Length Pinmembersweemeng.koh14:19 23 Sep '07  
AnswerRe: Invalid Length PinmemberbluebeetleRCC6:27 15 Aug '08  
AnswerRe: Invalid Length Pinmembernathan224055:24 29 May '09  
GeneralBase64Strings Pinmemberlyn_s_scott11:33 26 May '05  
GeneralRe: Base64Strings Pinmemberdlwiii8:26 22 Aug '08  
GeneralInvalid Length PinsussAnonymous17:58 16 Aug '04  
GeneralRe: Invalid Length Pinmembervipinjosea19:17 2 Aug '05  
GeneralInvalid lenth PinsussK.Vetter0:18 15 Jul '04  
GeneralRe: Invalid lenth PinsussAnonymous0:30 10 Sep '04  
GeneralRe: Invalid lenth PinsussAnonymous7:58 3 Jan '05  
GeneralRe: Invalid lenth PinmemberJohn Storer II3:31 5 Jul '06  
GeneralRe: Invalid lenth Pinmembershuchi agarwal4:14 28 Jul '06  
GeneralThe bug in encryption found... PinmemberNikolai Serdiuk0:32 26 Feb '04  
GeneralRe: The bug in encryption found... PinsussAnonymous13:43 31 May '04  
GeneralRe: The bug in encryption found... PinmemberNikolai Serdiuk22:34 31 May '04  
GeneralRe: The bug in encryption found... PinmemberNikolai Serdiuk22:56 31 May '04  
GeneralRe: The bug in encryption found... PinmemberNikolai Serdiuk22:47 31 May '04  
GeneralPolar Crypto Light... Pinmembermikasa12:07 8 Jan '04  
GeneralBest? PinsupporterKluch20:34 15 Dec '03  
GeneralDES, Rijndael work, RC2 doesn't Pinmembercoulsong7:32 29 Oct '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Mar 2002
Editor: James T. Johnson
Copyright 2002 by Frank Fang
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project