home *** CD-ROM | disk | FTP | other *** search
/ PC Pro 2005 June (DVD) / DPPRO0605DVD.iso / dotNETSDK / SETUP.EXE / netfxsd1.cab / FL_PublicKey_vb________.3643236F_FC70_11D3_A536_0090278A1BB8 < prev    next >
Encoding:
Text File  |  2002-05-01  |  7.1 KB  |  195 lines

  1. '=====================================================================
  2. '  File:      PublicKey.vb
  3. '
  4. '  Summary:   Demonstrates public key cryptography using the .NET
  5. '             Framework implementation of RSA. 
  6. '
  7. '---------------------------------------------------------------------
  8. '  This file is part of the Microsoft .NET Framework SDK Code Samples.
  9. '
  10. '  Copyright (C) Microsoft Corporation.  All rights reserved.
  11. '
  12. 'This source code is intended only as a supplement to Microsoft
  13. 'Development Tools and/or on-line documentation.  See these other
  14. 'materials for detailed information regarding Microsoft code samples.
  15. '
  16. 'THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
  17. 'KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  18. 'IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  19. 'PARTICULAR PURPOSE.
  20. '=====================================================================
  21.  
  22. Imports System
  23. Imports System.Security.Cryptography
  24. Imports System.IO
  25. Imports System.Text
  26.  
  27.  
  28. Module PublicKey
  29.    Sub Main()
  30.     ' Instantiate 3 People for example. See the Person class below
  31.     Dim alice As New Person("Alice")
  32.     Dim bob As New Person("Bob")
  33.     Dim steve As New Person("Steve")
  34.     
  35.     ' Messages that will exchanged. See CipherMessage class below
  36.     Dim aliceMessage As CipherMessage
  37.     Dim bobMessage As CipherMessage
  38.     Dim steveMessage As CipherMessage
  39.     
  40.     ' Example of encrypting/decrypting your own message
  41.     Console.WriteLine("Encrypting/Decrypting Your Own Message")
  42.     Console.WriteLine("-----------------------------------------")
  43.     
  44.     ' Alice encrypts a message using her own public key
  45.     aliceMessage = alice.EncryptMessage("Alice wrote this message")
  46.     ' then using her private key can decrypt the message
  47.     alice.DecryptMessage(aliceMessage)
  48.     ' Example of Exchanging Keys and Messages
  49.     Console.WriteLine()
  50.     Console.WriteLine("Exchanging Keys and Messages")
  51.     Console.WriteLine("-----------------------------------------")
  52.     
  53.     ' Alice Sends a copy of her public key to Bob and Steve
  54.     bob.GetPublicKey(alice)
  55.     steve.GetPublicKey(alice)
  56.     
  57.     ' Bob and Steve both encrypt messages to send to Alice
  58.     bobMessage = bob.EncryptMessage("Hi Alice! - Bob.")
  59.     steveMessage = steve.EncryptMessage("How are you? - Steve")
  60.     
  61.     ' Alice can decrypt and read both messages
  62.     alice.DecryptMessage(bobMessage)
  63.     alice.DecryptMessage(steveMessage)
  64.     
  65.     Console.WriteLine()
  66.     Console.WriteLine("Private Key required to read the messages")
  67.     Console.WriteLine("-----------------------------------------")
  68.     
  69.     ' Steve cannot read the message that Bob encrypted
  70.     steve.DecryptMessage(bobMessage)
  71.     ' Not even Bob can use the Message he encrypted for Alice.
  72.     ' The RSA private key is required to decrypt the RS2 key used
  73.     ' in the decryption.
  74.     bob.DecryptMessage(bobMessage)
  75.   End Sub 'Main 
  76.  
  77.   Class CipherMessage
  78.     Public cipherBytes() As Byte ' RC2 encrypted message text
  79.     Public rc2Key() As Byte ' RSA encrypted rc2 key
  80.     Public rc2IV() As Byte ' RC2 initialization vector
  81.   End Class 'CipherMessage
  82.   
  83.   Class Person
  84.     Private rsa As RSACryptoServiceProvider
  85.     Private rc2 As RC2CryptoServiceProvider
  86.     Private name As String
  87.     
  88.     ' Maximum key size for the RC2 algorithm
  89.     Private keySize As Integer = 128
  90.     
  91.     
  92.     ' Person constructor
  93.     Public Sub New(p_Name As String)
  94.       rsa = New RSACryptoServiceProvider()
  95.       rc2 = New RC2CryptoServiceProvider()
  96.       rc2.KeySize = keySize
  97.       name = p_Name
  98.     End Sub 'New
  99.     
  100.     
  101.     ' Used to send the rsa public key parameters
  102.     Public Function SendPublicKey() As RSAParameters
  103.       Dim result As New RSAParameters()
  104.       Try
  105.         result = rsa.ExportParameters(False)
  106.       Catch e As CryptographicException
  107.         Console.WriteLine(e.Message)
  108.       End Try
  109.       Return result
  110.     End Function 'SendPublicKey
  111.     
  112.     ' Used to import the rsa public key parameters
  113.     Public Sub GetPublicKey(receiver As Person)
  114.       Try
  115.         rsa.ImportParameters(receiver.SendPublicKey())
  116.       Catch e As CryptographicException
  117.         Console.WriteLine(e.Message)
  118.       End Try
  119.     End Sub 'GetPublicKey
  120.     
  121.     
  122.     Public Function EncryptMessage([text] As String) As CipherMessage
  123.       ' Convert string to a byte array
  124.       Dim message As New CipherMessage()
  125.       Dim plainBytes As Byte() = Encoding.Unicode.GetBytes([text].ToCharArray())
  126.       
  127.       ' A new key and iv are generated for every message
  128.       rc2.GenerateKey()
  129.       rc2.GenerateIV()
  130.       
  131.       ' The rc2 initialization doesnt need to be encrypted, but will
  132.       ' be used in conjunction with the key to decrypt the message.
  133.       message.rc2IV = rc2.IV
  134.       Try
  135.         ' Encrypt the RC2 key using RSA encryption
  136.         message.rc2Key = rsa.Encrypt(rc2.Key, False)
  137.       Catch e As CryptographicException
  138.         ' The High Encryption Pack is required to run this  sample
  139.         ' because we are using a 128-bit key. See the readme for
  140.         ' additional information.
  141.         Console.WriteLine(("Encryption Failed. Ensure that the" + " High Encryption Pack is installed."))
  142.         Console.WriteLine(("Error Message: " + e.Message))
  143.         Environment.Exit(0)
  144.       End Try
  145.       ' Encrypt the Text Message using RC2 (Symmetric algorithm)
  146.       Dim sse As ICryptoTransform = rc2.CreateEncryptor()
  147.       Dim ms As New MemoryStream()
  148.       Dim cs As New CryptoStream(ms, sse, CryptoStreamMode.Write)
  149.       Try
  150.         cs.Write(plainBytes, 0, plainBytes.Length)
  151.         cs.FlushFinalBlock()
  152.         message.cipherBytes = ms.ToArray()
  153.       Catch e As Exception
  154.         Console.WriteLine(e.Message)
  155.       Finally
  156.         ms.Close()
  157.         cs.Close()
  158.       End Try
  159.       Return message
  160.     End Function 'EncryptMessage
  161.     
  162.     Public Sub DecryptMessage(message As CipherMessage)
  163.       ' Get the RC2 Key and Initialization Vector
  164.       rc2.IV = message.rc2IV
  165.       Try
  166.         ' Try decrypting the rc2 key
  167.         rc2.Key = rsa.Decrypt(message.rc2Key, False)
  168.       Catch e As CryptographicException
  169.         Console.WriteLine(("Decryption Failed: " + e.Message))
  170.         Return
  171.       End Try
  172.       
  173.       Dim ssd As ICryptoTransform = rc2.CreateDecryptor()
  174.       ' Put the encrypted message in a memorystream
  175.       Dim ms As New MemoryStream(message.cipherBytes)
  176.       ' the CryptoStream will read cipher text from the MemoryStream
  177.       Dim cs As New CryptoStream(ms, ssd, CryptoStreamMode.Read)
  178.       Dim initialText() As Byte = New [Byte](message.cipherBytes.Length) {}
  179.       
  180.       Try
  181.         ' Decrypt the message and store in byte array
  182.         cs.Read(initialText, 0, initialText.Length)
  183.       Catch e As Exception
  184.         Console.WriteLine(e.Message)
  185.       Finally
  186.         ms.Close()
  187.         cs.Close()
  188.       End Try 
  189.       
  190.       ' Display the message received
  191.       Console.WriteLine((name + " received the following message:"))
  192.       Console.WriteLine(("  " &  Encoding.Unicode.GetString(initialText)))
  193.     End Sub 'DecryptMessage 
  194.   End Class 'Person 
  195. End Module 'PublicKey