Click here to Skip to main content
16,011,949 members
Articles / Programming Languages / C#
Article

Encryption/Decryption with .NET

Rate me:
Please Sign up or sign in to vote.
1.21/5 (12 votes)
23 Jun 20021 min read 89K   2.1K   26   6
Encryption/Decryption with .NET

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.

After I posted the original code, I found some interesting things about .NET System.Security.Cryptographic.SymmetricAlgorithm classes that they are not able to handle characters which are special to Url. (Don't know why). Therefore, I modified the source code to make it work. I have received a lot of emails regarding "Bad Data" exceptions, when some special characters are contained in the data or key. I emailed my updated code back, but haven't updated the code posted here. Looks like I have to update the code here as well.

For any questions, please contact me at: fangfrank@hotmail.com and I would be happy to answer them a.s.a.p.

Revision History

26 Jun 2002 - Initial Revision

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralVB Code decrypted strings Pin
Anonymous29-Oct-02 19:08
Anonymous29-Oct-02 19:08 
GeneralRe: VB Code decrypted strings Pin
Anonymous24-Jun-03 23:18
Anonymous24-Jun-03 23:18 
GeneralVB Code that Actually Works Pin
JeromeH25-Oct-02 13:07
JeromeH25-Oct-02 13:07 
After many hours of battling with others sample code and sifting through countless message board posts I believe I have managed to come up with a fairly functional and stable encryption and decryption class that utilises multiple encryption methods.

The code is shown below and a sample call would look something like
Dim Crypto As New Crypto(Crypto.Providers.DES)
Dim Encrypted as string = Crypto.Encrypt("Test String", "Keystring")
Dim Decrypted as string = Crypto.Decrypt(Encrypted , "Keystring")


Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

'SymmCrypto is a wrapper of System.Security.Cryptography.SymmetricAlgorithm classes
'and simplifies the interface. It supports customized SymmetricAlgorithm as well.
'Original Code from Frank Fang
'Revised by Jerom Howard to remove Bad Data errors, create seperate CryptoIV and
'use the maximum legal keysize for each encryption algorithm

Public Class Crypto
'256 Bit IV Key that is truncated when a smaller keys are required
Private bytIV() As Byte = _
{12, 241, 10, 21, 90, 74, 11, 39, 9, 91, 45, 78, 189, 211, 133, 62, 121, 22, 101, 34, 90, 74, 121, 39, 93, 9, 45, 78, 1, 211, 33, 162}

'Supported .Net intrinsic SymmetricAlgorithm classes.
Public Enum Providers
DES
RC2
Rijndael
End Enum

Private _CryptoService As SymmetricAlgorithm

'Constructor for using an intrinsic .Net SymmetricAlgorithm class.
Public Sub New(ByVal NetSelected As Providers)
Select Case NetSelected
Case Providers.DES
_CryptoService = New DESCryptoServiceProvider()
Case Providers.RC2
_CryptoService = New RC2CryptoServiceProvider()
Case Providers.Rijndael
_CryptoService = New RijndaelManaged()
End Select
End Sub

'Constructor for using a customized SymmetricAlgorithm class.
Public Sub New(ByVal ServiceProvider As SymmetricAlgorithm)
_CryptoService = ServiceProvider
End Sub

'Depending on the legal key size limitations of a specific CryptoService provider
'and length of the private key provided, padding the secret key with a character
'or triming it to meet the legal size of the algorithm.
Private Function GetLegalKey(ByVal Key As String) As Byte()
'key sizes are in bits
Dim sTemp As String
If (_CryptoService.LegalKeySizes.Length > 0) Then
Dim maxSize As Integer = _CryptoService.LegalKeySizes(0).MaxSize
If Key.Length * 8 > maxSize Then
sTemp = Key.Substring(0, (maxSize / 8))
ReDim Preserve bytIV((maxSize / 8) - 1)
Else
Dim moreSize As Integer = _CryptoService.LegalKeySizes(0).MinSize
Do While (Key.Length * 8 > moreSize)
moreSize += _CryptoService.LegalKeySizes(0).SkipSize
Loop
ReDim Preserve bytIV(moreSize / 8)
sTemp = Key.PadRight(moreSize / 8, "X")
End If
Else
sTemp = Key
ReDim Preserve bytIV(Key.Length)
End If

'convert the secret key to byte array
Return ASCIIEncoding.ASCII.GetBytes(sTemp)
End Function

Public Function Encrypt(ByVal Source As String, ByVal Key As String) As String
Dim bytIn As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.HttpUtility.UrlEncode(Source))
Dim ms As MemoryStream = New MemoryStream()

'set the keys
_CryptoService.Key = GetLegalKey(Key)
_CryptoService.IV = bytIV

'create an Encryptor from the Provider Service instance
Dim encrypto As ICryptoTransform = _CryptoService.CreateEncryptor()

'create Crypto Stream that transforms a stream using the encryption
Dim cs As CryptoStream = New CryptoStream(ms, encrypto, CryptoStreamMode.Write)

'write out encrypted content into MemoryStream
cs.Write(bytIn, 0, bytIn.Length)
cs.FlushFinalBlock()
cs.Close()
Dim bytOut() As Byte = ms.ToArray()
ms.Close()

Return Convert.ToBase64String(bytOut) 'convert into Base64 so that the result can be used in xml
End Function

Public Function Decrypt(ByVal Source As String, ByVal Key As String) As String
'convert from Base64 to binary
Dim bytIn As Byte() = System.Convert.FromBase64String(Source)
Dim ms As MemoryStream = New MemoryStream(bytIn)

Dim bytKey() As Byte = GetLegalKey(Key)
Dim bytTemp(bytIn.Length) As Byte

'set the private key
_CryptoService.Key = bytKey
_CryptoService.IV = bytIV

'create a Decryptor from the Provider Service instance
Dim encrypto As ICryptoTransform = _CryptoService.CreateDecryptor()

'create Crypto Stream that transforms a stream using the decryption
Dim cs As CryptoStream = New CryptoStream(ms, encrypto, CryptoStreamMode.Read)
Try
'read out the result from the Crypto Stream
cs.Read(bytTemp, 0, bytTemp.Length)

cs.FlushFinalBlock()
ms.Close()
cs.Close()
Catch
End Try
Return System.Web.HttpUtility.UrlDecode(Encoding.ASCII.GetString(bytTemp))
End Function

End Class
GeneralError Pin
Anonymous30-Sep-02 5:16
Anonymous30-Sep-02 5:16 
GeneralYou should net set the key and the IV to the same value Pin
1-Jul-02 3:59
suss1-Jul-02 3:59 
Generalreg. kEY Pin
Anonymous22-Jul-03 1:30
Anonymous22-Jul-03 1:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.