Encryption problem

  • 14 years ago

    i want to encrypt a connection string  using RSA cryptography and but it in text file or ini , then i want to decrypt it back to use it in my application.

    Can anybody help me

    i use this code but i dont know how to fix it to only read encrypted string and decrypt it back

    when i try to read encrypted string and converet it back to arrylist of bytes then decrypted it it always gives bad data error ( i dont know how to convert string to arraylist of  byte)

    -----------------declaration---------------------------

    Imports

    System.Xml

    Imports

    System.IO

    Imports

    System.Threading

    Imports

    System.Runtime.Remoting.Messaging

    Imports

    System.Drawing.Drawing2D

    Imports

    System.Security.Cryptography

    Imports

    System.Text

    Imports

    System.Configuration

    --------------Public variables-----------------

    Dim

    txtCon As String

    Dim txtEnc As Byte()

    Dim TDES As TripleDES

    Dim encType As String

    Shared pubKey, priKey As String

    -------------------code ---------------------------------

    Dim key As String

    Dim arrlis As New ArrayList

    TDES =

    New TripleDES

    Dim maxLimit As Integer = 58

     

    arrlis = TDES.EncryptRSA("hi", "<RSAKeyValue><Modulus>ogeYFtPxvgXiHwRYCFQK9fxlWyZaKaSna2gwKsDUS/OvMdy2aAeyFRNAndc2ERx2u4ZLICTQ9IRowyplQdUczgMPi+c72AwAMNsTxTieTdVbeoHdJD79i0blQ1mVhpztWMp2YSaF4mPfNxp2LwaNjrAsEdXLu/CRKG0bMyXH30U=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>")

     

    For j As Integer = 0 To arrlis.Count - 1

    txtEnc =

    CType(arrlis(j), Byte())

    For i As Integer = 0 To txtEnc.Length - 1

    txtData.AppendText(Chr(txtEnc(i)))

    Next

    Next

    For j As Integer = 0 To arrlis.Count - 1

    txtEnc =

    CType(arrlis(j), Byte())

    txtEnc = TDES.DecryptRSA(txtEnc, "<RSAKeyValue><Modulus>ogeYFtPxvgXiHwRYCFQK9fxlWyZaKaSna2gwKsDUS/OvMdy2aAeyFRNAndc2ERx2u4ZLICTQ9IRowyplQdUczgMPi+c72AwAMNsTxTieTdVbeoHdJD79i0blQ1mVhpztWMp2YSaF4mPfNxp2LwaNjrAsEdXLu/CRKG0bMyXH30U=</Modulus><Exponent>AQAB</Exponent><P>0zYPrtO466kl3HegZ0IGO2y5n039uMeGqFIMn7pYb+MfKJGEGoBuHv80IGwOoWfmRSLqyVC0X9ip2iub88Dqbw==</P><Q>xGOioNcq9wLVSAgT6WCG9ZC8AOTNRG7HYJwqRAcd+HVUXJR4PNFF9BjwShyrwAKcKI/WGkijwgFhritZvo87iw==</Q><DP>zXVhfCfpUxWQBw83sjq/5T62swkjL4SosURfk2GqdezyenxTjZQxi2WmR4PWF50Cm26EBqHDVRlm4Rxa8JtRcQ==</DP><DQ>S5McDlE/E3dfpCyXnQOsa+uara1e4KrQxvjRuwQSIH7mTApGiwDtrpW6Qort/SID/gf8GHlDq3DkqiW8j3yHKQ==</DQ><InverseQ>wfevd36MC1gin9UAtWn21oBsE+aZkVi4RYZlzrdtc5JKk9TI3MYcTaXP/RwK1VZWY6db5/tFOl2PgS+qn5WYKQ==</InverseQ><D>kqd4+0B+j9XXYueVnoQjH56BRs0h0otblZXJ8whxnwVDT0hMOUCt6PFyDOtb3oT62qSknsVz871c7TkUSU/RLx0coAPViYlW1P8aaWrvrN+Y0aZHf15QLZhGYZrMhJZzJklkiLoaqskmRj3CGU/WtyP7lk6BWWEi0B4nmM9IUAk=</D></RSAKeyValue>")

    For ctr As Integer = 0 To (txtEnc.Length - 1)

    txtData.AppendText(Chr(txtEnc(ctr)))

    Next ctr

    Next

    -------------------class used --------------------------------------------------------------------------------

    Imports

    System

    Imports

    System.IO

    Imports

    System.Security.Cryptography

    Imports

    System.Text

    Public

    Class TripleDES

    Shared publicKey As String 'The public key only

    Shared privateKey As String

    Shared xmlKeys As String 'A combination of both the public and private keys

    Dim key3DES() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}

    Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8}

    Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}

    Public Sub New()

    Dim rsa As New RSACryptoServiceProvider

    xmlKeys = rsa.ToXmlString(

    True)

    publicKey = rsa.ToXmlString(

    False)

    End Sub

    Public Sub New(ByVal encType As String)

    Select Case encType

    Case "3DES"

    Case "RSA"

    Case Else

    End Select

    End Sub

    Public Function Encrypt(ByVal plainText As String, ByVal encType As String) As Byte()

    ' Declare a UTF8Encoding object so we may use the GetByte

    ' method to transform the plainText into a Byte array.

    Dim utf8encoder As UTF8Encoding = New UTF8Encoding

    Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)

    ' Create a new DES / TripleDES service provider

    Dim tdesProvider As Object

    Dim cryptoTransform As Object

    Select Case encType

    Case "DES"

    tdesProvider =

    New DESCryptoServiceProvider

    ' The ICryptTransform interface uses the TripleDES

    ' crypt provider along with encryption key and init vector

    ' information

    cryptoTransform = tdesProvider.CreateEncryptor(

    Me.key, Me.iv)

    Case "3DES"

    tdesProvider =

    New TripleDESCryptoServiceProvider

    ' The ICryptTransform interface uses the TripleDES

    ' crypt provider along with encryption key and init vector

    ' information

    cryptoTransform = tdesProvider.CreateEncryptor(

    Me.key3DES, Me.iv)

    End Select

     

     

    ' All cryptographic functions need a stream to output the

    ' encrypted information. Here we declare a memory stream

    ' for this purpose.

    Dim encryptedStream As MemoryStream = New MemoryStream

    Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)

    ' Write the encrypted information to the stream. Flush the information

    ' when done to ensure everything is out of the buffer.

    cryptStream.Write(inputInBytes, 0, inputInBytes.Length)

    cryptStream.FlushFinalBlock()

    encryptedStream.Position = 0

    ' Read the stream back into a Byte array and return it to the calling

    ' method.

    Dim result(encryptedStream.Length - 1) As Byte

    encryptedStream.Read(result, 0, encryptedStream.Length)

    cryptStream.Close()

    Return result

    End Function

    Public Function Decrypt(ByVal inputInBytes() As Byte, ByVal decType As String) As String

    ' UTFEncoding is used to transform the decrypted Byte Array

    ' information back into a string.

    Dim utf8encoder As UTF8Encoding = New UTF8Encoding

    Dim tdesProvider As Object

    Dim cryptoTransform As Object

    Select Case decType

    Case "DES"

    tdesProvider =

    New DESCryptoServiceProvider

    ' As before we must provide the encryption/decryption key along with

    ' the init vector.

    cryptoTransform = tdesProvider.CreateDecryptor(

    Me.key, Me.iv)

    Case "3DES"

    tdesProvider =

    New TripleDESCryptoServiceProvider

    ' As before we must provide the encryption/decryption key along with

    ' the init vector.

    cryptoTransform = tdesProvider.CreateDecryptor(

    Me.key3DES, Me.iv)

    End Select

     

     

     

    ' Provide a memory stream to decrypt information into

    Dim decryptedStream As MemoryStream = New MemoryStream

    Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write)

    cryptStream.Write(inputInBytes, 0, inputInBytes.Length)

    'cryptStream.Flush()

    cryptStream.FlushFinalBlock()

    decryptedStream.Position = 0

    ' Read the memory stream and convert it back into a string

    Dim result(decryptedStream.Length - 1) As Byte

    decryptedStream.Read(result, 0, decryptedStream.Length)

    cryptStream.Close()

    Dim myutf As UTF8Encoding = New UTF8Encoding

    Return myutf.GetString(result)

    End Function

    Public Function EncryptRSA(ByVal plainText As String, ByVal key As String) As ArrayList

    Dim rsa As New RSACryptoServiceProvider

    rsa.UseMachineKeyStore =

    True

    Dim EncryptedStrAsByt() As Byte

    Dim encrAl As New ArrayList

    Dim maxLimit As Integer = 58

    'get the public key so you can encrypt the message:

    rsa.FromXmlString(key)

    ' MessageBox.Show("On Encryption: " & publicKey)

    Dim strs() As String

    If (plainText.Length > maxLimit) Then

    'Split the text into blocks of 58 characters

    Dim splitText As String

    For counter As Integer = 0 To plainText.Length

    If (plainText.Length - counter < maxLimit) Then

    splitText = plainText.Substring(counter, plainText.Length - counter)

    Else

    splitText = plainText.Substring(counter, maxLimit)

    End If

    EncryptedStrAsByt = rsa.Encrypt(System.Text.Encoding.Unicode.GetBytes(splitText),

    False)

    encrAl.Add(EncryptedStrAsByt)

    counter = counter + (maxLimit - 1)

    Next

    Else

    EncryptedStrAsByt = rsa.Encrypt(System.Text.Encoding.Unicode.GetBytes(plainText),

    False)

    encrAl.Add(EncryptedStrAsByt)

    End If

    Return encrAl

    End Function

    Public Function DecryptRSA(ByVal inputBytes() As Byte, ByVal key As String) As Byte()

    Dim rsa As New RSACryptoServiceProvider

    rsa.UseMachineKeyStore =

    True

    'get the keys, thereby creating an RSA object that's identical

    ' to the one used in the Form_Load event when the keys were first built

    rsa.FromXmlString(key)

    'MessageBox.Show("On Decryption: " & xmlKeys)

    Dim DecryptedStrAsByte() As Byte = rsa.Decrypt(inputBytes, False)

    publicKey =

    String.Empty

    privateKey =

    String.Empty

    Return DecryptedStrAsByte

    'Dim DecryptedStrAsString = System.Text.Encoding.Unicode.GetString(DecryptedStrAsByt)

    End Function

     

    Public Shared Function Encrypt(ByVal plainText As String, _

    ByVal passPhrase As String, _

    ByVal saltValue As String, _

    ByVal hashAlgorithm As String, _

    ByVal passwordIterations As Integer, _

    ByVal initVector As String, _

    ByVal keySize As Integer) _

    As String

    Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)

    Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

    Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)

    Dim password As PasswordDeriveBytes = New PasswordDeriveBytes(passPhrase, _

    saltValueBytes, _

    hashAlgorithm, _

    passwordIterations)

    Dim keyBytes As Byte() = password.GetBytes(keySize / 8)

    'Dim keyBytes As Byte() = {23, 39, 79, 67, 81, 92, 53, 62, 23, 53, 31, 125, 128, 43, 11, 23, 48, 97, 56, 11, 5, 1, 65, 132}

    ' Create uninitialized Rijndael encryption object.

    Dim symmetricKey As RijndaelManaged = New RijndaelManaged

    ' It is reasonable to set encryption mode to Cipher Block Chaining

    ' (CBC). Use default options for other symmetric key parameters.

    symmetricKey.Mode = CipherMode.CBC

    symmetricKey.Padding = PaddingMode.PKCS7

    ' Generate encryptor from the existing key bytes and initialization

    ' vector. Key size will be defined based on the number of the key

    ' bytes.

    Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)

    ' Define memory stream which will be used to hold encrypted data.

    Dim memoryStream As MemoryStream = New MemoryStream

    ' Define cryptographic stream (always use Write mode for encryption).

    Dim cryptoStream As CryptoStream = New CryptoStream(memoryStream, _

    encryptor, _

    CryptoStreamMode.Write)

    ' Start encrypting.

    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)

    ' Finish encrypting.

    cryptoStream.FlushFinalBlock()

    ' Convert our encrypted data from a memory stream into a byte array.

    Dim cipherTextBytes As Byte() = memoryStream.ToArray()

    ' Close both streams.

    memoryStream.Close()

    cryptoStream.Close()

    ' Convert encrypted data into a base64-encoded string.

    Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)

    ' Return encrypted string.

    Encrypt = cipherText

    End Function

     

     

    Public Shared Function Decrypt(ByVal cipherText As String, _

    ByVal passPhrase As String, _

    ByVal saltValue As String, _

    ByVal hashAlgorithm As String, _

    ByVal passwordIterations As Integer, _

    ByVal initVector As String, _

    ByVal keySize As Integer) _

    As String

    ' Convert strings defining encryption key characteristics into byte

    ' arrays. Let us assume that strings only contain ASCII codes.

    ' If strings include Unicode characters, use Unicode, UTF7, or UTF8

    ' encoding.

    Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)

    Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)

    ' Convert our ciphertext into a byte array.

    Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)

    ' First, we must create a password, from which the key will be

    ' derived. This password will be generated from the specified

    ' passphrase and salt value. The password will be created using

    ' the specified hash algorithm. Password creation can be done in

    ' several iterations.

    Dim password As PasswordDeriveBytes = New PasswordDeriveBytes(passPhrase, _

    saltValueBytes, _

    hashAlgorithm, _

    passwordIterations)

    ' Use the password to generate pseudo-random bytes for the encryption

    ' key. Specify the size of the key in bytes (instead of bits).

    Dim keyBytes As Byte() = password.GetBytes(keySize / 8)

    'Dim keyBytes As Byte() = {23, 39, 79, 67, 81, 92, 53, 62, 23, 53, 31, 125, 128, 43, 11, 23, 48, 97, 56, 11, 5, 1, 65, 132}

    ' Create uninitialized Rijndael encryption object.

    Dim symmetricKey As RijndaelManaged = New RijndaelManaged

    ' It is reasonable to set encryption mode to Cipher Block Chaining

    ' (CBC). Use default options for other symmetric key parameters.

    symmetricKey.Mode = CipherMode.CBC

    symmetricKey.Padding = PaddingMode.PKCS7

    ' Generate decryptor from the existing key bytes and initialization

    ' vector. Key size will be defined based on the number of the key

    ' bytes.

    Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)

    ' Define memory stream which will be used to hold encrypted data.

    Dim memoryStream As MemoryStream = New MemoryStream(cipherTextBytes)

    ' Define memory stream which will be used to hold encrypted data.

    Dim cryptoStream As CryptoStream = New CryptoStream(memoryStream, _

    decryptor, _

    CryptoStreamMode.Read)

    ' Since at this point we don't know what the size of decrypted data

    ' will be, allocate the buffer long enough to hold ciphertext;

    ' plaintext is never longer than ciphertext.

    Dim plainTextBytes As Byte()

    ReDim plainTextBytes(cipherTextBytes.Length)

    ' Start decrypting.

    Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, _

    0, _

    plainTextBytes.Length)

    ' Close both streams.

    memoryStream.Close()

    cryptoStream.Close()

    ' Convert decrypted data into a string.

    ' Let us assume that the original plaintext string was UTF8-encoded.

    Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, _

    0, _

    decryptedByteCount)

    ' Return decrypted string.

    Decrypt = plainText

    End Function

    Public Function GetKeysForRSA(ByRef pubKey As String, ByRef priKey As String)

    Try

    Dim rsa As New RSACryptoServiceProvider

    rsa.UseMachineKeyStore =

    True

    pubKey = rsa.ToXmlString(

    False)

    priKey = rsa.ToXmlString(

    True)

    rsa =

    Nothing

    Catch ex As Exception

    Throw ex

    End Try

    End Function

    End

    Class

     

Post a reply

No one has replied yet! Why not be the first?

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” - Donald Knuth