Create and use an RC2 object to encrypt and decrypt data in memory. : RC2 « Security « VB.Net Tutorial

Home
VB.Net Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statements
5.Date Time
6.Class Module
7.Development
8.Collections
9.Generics
10.Attributes
11.Event
12.LINQ
13.Stream File
14.GUI
15.GUI Applications
16.Windows Presentation Foundation
17.2D Graphics
18.I18N Internationlization
19.Reflection
20.Regular Expressions
21.Security
22.Socket Network
23.Thread
24.Windows
25.XML
26.Database ADO.net
27.Design Patterns
VB.Net
VB.Net by API
VB.Net Tutorial » Security » RC2 
21.6.2.Create and use an RC2 object to encrypt and decrypt data in memory.
Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Module RC2PSample

    Sub Main()
        Try
            Dim RC2alg As RC2 = RC2.Create("RC2")
            Dim sData As String = "this is a test."
            Dim Data As Byte() = EncryptTextToMemory(sData, RC2alg.Key, RC2alg.IV)
            Dim Final As String = DecryptTextFromMemory(Data, RC2alg.Key, RC2alg.IV)
            Console.WriteLine(Final)
        Catch As Exception
            Console.WriteLine(e.Message)
        End Try
    End Sub
    Function EncryptTextToMemory(ByVal Data As String, ByVal Key() As Byte, ByVal IV() As ByteAs Byte()
        Try
            Dim mStream As New MemoryStream
            Dim RC2alg As RC2 = RC2.Create
            Dim cStream As New CryptoStream(mStream,RC2alg.CreateEncryptor(Key, IV),CryptoStreamMode.Write)
            Dim toEncrypt As Byte() = New ASCIIEncoding().GetBytes(Data)
            cStream.Write(toEncrypt, 0, toEncrypt.Length)
            cStream.FlushFinalBlock()
            Dim ret As Byte() = mStream.ToArray()
            cStream.Close()
            mStream.Close()
            Return ret
        Catch As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
    Function DecryptTextFromMemory(ByVal Data() As Byte, ByVal Key() As Byte, ByVal IV() As ByteAs String
        Try
            Dim msDecrypt As New MemoryStream(Data)
            Dim RC2alg As RC2 = RC2.Create
            Dim csDecrypt As New CryptoStream(msDecrypt,RC2alg.CreateDecryptor(Key, IV),CryptoStreamMode.Read)
            Dim fromEncrypt(Data.LengthAs Byte
            csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)
            Return New ASCIIEncoding().GetString(fromEncrypt)
        Catch As CryptographicException
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message)
            Return Nothing
        End Try
    End Function
End Module
21.6.RC2
21.6.1.Create and use an RC2 object to encrypt and decrypt data in a file.
21.6.2.Create and use an RC2 object to encrypt and decrypt data in memory.
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.