Solved

VB.NET encryption using AES algorithm and given passphrase.

Posted on 2015-02-03
5
405 Views
Last Modified: 2015-02-12
I would like to begin by saying that I have no experience with VB.NET.  I have a vendor that wants to show my website through an iframe and is sending a query string to validate the user with the url parameter of the iframe tag.  He would like to encrypt the variables within the query string.  I have demonstrated the encryption with ColdFusion utilitizing the encrypt tag and the attributes of a given passkey (ex. TestPass), the AES algorithm and Hex encoding.  The line would look like the below.

encrypt(string,'TestPass','AES','Hex')

My question is...  how do I encrypt the same string with VB.NET?
0
Comment
Question by:ppiTech
5 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 40588787
Do you want the same encryption result that you would get with ColdFusion?
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 40588860
Something like this:
Imports System.Security.Cryptography
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Text

Module Module1
	Sub Main()
		Dim encryptMe = "The quick brown fox jumped over the fence to snatch a meal."
		Dim encrypted = New AESEncryption("TestPass").Encrypt(encryptMe)
		Console.WriteLine("Original: {0}", encryptMe)
		Console.WriteLine("Encrypted: {0}", Encoding.Default.GetString(encrypted))
		Dim unencrypted = New AESEncryption("TestPass").Decrypt(encrypted)
		Console.WriteLine("Unencrypted: {0}", unencrypted)
		Console.ReadLine()
	End Sub
End Module

Public Class AESEncryption
	Private ReadOnly fKey As Byte()
	Private ReadOnly fIV As Byte()
	Private ReadOnly fBitSize As Integer
	Private Shared ReadOnly fKeySizes As List(Of Integer)
	Private Shared ReadOnly fBlockSizes As List(Of Integer)

	Shared Sub New()
		Using aes = New AesCryptoServiceProvider()
			Dim temp = New List(Of Integer)()
			For Each keysize As KeySizes In aes.LegalKeySizes
				Dim i As Integer = keysize.MinSize
				While i <= keysize.MaxSize
					If Not temp.Contains(i) Then temp.Add(i)
					If i = keysize.MaxSize Then Exit While
					i += keysize.SkipSize
				End While
			Next
			fKeySizes = temp

			temp = New List(Of Integer)()
			For Each keysize As KeySizes In aes.LegalBlockSizes
				Dim i As Integer = keysize.MinSize
				While i <= keysize.MaxSize
					If Not temp.Contains(i) Then temp.Add(i)
					If i = keysize.MaxSize Then Exit While
					i += keysize.SkipSize
				End While
			Next
			fBlockSizes = temp
		End Using
	End Sub

	Public Sub New(ByVal Key As Byte(), ByVal InitializationVector As Byte())
		Try
			Dim keySizes As String = fKeySizes.Aggregate("", Function(current, i) String.Format("{0}{1}, ", current, i))
			keySizes = keySizes.Remove(keySizes.Length - 3)

			Dim blockSizes As String = fBlockSizes.Aggregate("", Function(current, i) String.Format("{0}, ", current, i))
			blockSizes = blockSizes.Remove(blockSizes.Length - 3)

			fKey = Key
			fIV = InitializationVector
			fBitSize = fKey.Length * 8
		Catch ex As ArgumentException
			Throw New EncryptionException(ex.Message, ex)
		Catch ex As Exception
			Throw
		End Try
	End Sub

	Public Sub New(ByVal Key As String, ByVal BitSize As Integer)
		Try
			Dim keySizes As String = fKeySizes.Aggregate("", Function(current, i) String.Format("{0}{1}, ", current, i))
			keySizes = keySizes.Remove(keySizes.Length - 3)

			Dim entropy As Byte() = Encoding.UTF32.GetBytes(Key)
			Using hmacsha512 = New HMACSHA512(Convert.FromBase64String("i88NEiez3c50bHqr3YGasDc4p8jRrxJAaiRiqixpvp4XNAStP5YNoC2fXnWkURtkha6M8yY901Gj07IRVIRyGL==")) With {.ProduceLegacyHmacValues = True}
				hmacsha512.Initialize()
				For i As Integer = 0 To 999
					entropy = hmacsha512.ComputeHash(entropy)
				Next
			End Using

			Dim keylen As Integer = BitSize / 8
			fKey = New Byte(keylen - 1) {}
			Buffer.BlockCopy(entropy, 0, fKey, 0, keylen)
			fIV = New Byte(fBlockSizes(0) / 8 - 1) {}

			Buffer.BlockCopy(entropy, entropy.Length - fIV.Length - 1, fIV, 0, fIV.Length)
			fBitSize = BitSize
		Catch ex As ArgumentException
			Throw New EncryptionException(ex.Message, ex)
		Catch ex As Exception
			Throw
		End Try
	End Sub

	Public Sub New(ByVal Key As String)
		Me.New(Key, fKeySizes.Max())
	End Sub

	Public Function Encrypt(ByVal Data As Object) As Byte()
		Try
			Dim m_encrypted As Byte()
			Using aesCryptoServiceProvider = New AesCryptoServiceProvider() With {.KeySize = fBitSize, .Mode = CipherMode.CBC}
				Using cryptoTransform = aesCryptoServiceProvider.CreateEncryptor(fKey, fIV)
					Using memoryStream = New MemoryStream()
						Using cryptoStream = New CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write)
							Using swStream = New StreamWriter(cryptoStream)
								swStream.Write(Data)
							End Using
						End Using
						m_encrypted = memoryStream.ToArray()
					End Using
				End Using
			End Using
			Return m_encrypted
		Catch ex As Exception
			Return Nothing
		End Try

	End Function

	Public Function Decrypt(ByVal Data As Byte()) As Object
		Try
			Dim m_decrypted As Object = Nothing
			Using aesCryptoServiceProvider = New AesCryptoServiceProvider() With {.KeySize = fBitSize, .Mode = CipherMode.CBC}
				Using cryptoTransform = aesCryptoServiceProvider.CreateDecryptor(fKey, fIV)
					Using memoryStream = New MemoryStream(Data)
						Using cryptoStream = New CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Read)
							Using srStream = New StreamReader(cryptoStream)
								m_decrypted = srStream.ReadToEnd()
							End Using
						End Using
					End Using
				End Using
			End Using
			Return m_decrypted
		Catch ex As Exception
			Return Nothing
		End Try
	End Function
End Class

Public NotInheritable Class EncryptionException
	Inherits Exception
	Public Sub New()
		MyBase.New()
	End Sub

	Public Sub New(ByVal message As String)
		MyBase.New(message)
	End Sub

	Public Sub New(ByVal message As String, ByVal inner As Exception)
		MyBase.New(message, inner)
	End Sub

	Private Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
		MyBase.New(info, context)
	End Sub

	<Conditional("DEBUG")> _
	Public Shared Sub Assert(ByVal isOk As Boolean, Optional ByVal message As String = "")
		If Not isOk Then
			If String.IsNullOrEmpty(message) Then
				Throw New EncryptionException()
			Else
				Throw New EncryptionException(message)
			End If
		End If
	End Sub
End Class

Open in new window

Produces the following output -Capture.JPG-saige-
0
 

Author Comment

by:ppiTech
ID: 40588886
bob learned..  I would like the result to be the same.
0
 
LVL 52

Expert Comment

by:_agx_
ID: 40589178
(No points... this isn't my area)

> I would like the result to be the same.

@Bob Learned - FYI, some of the CF settings are implicit. Their ColdFusion code is using the following settings :

encrypt(string, password,'AES','Hex')

* string - plain text string treated as UTF8 encoded
* password - assumed to be base64 encoded
* 'AES' - Uses AES/ECB/PKCS5Padding
* 'Hex' - return encrypted bytes as hex
0
 

Author Comment

by:ppiTech
ID: 40594453
it_saige.. your code looks good just waiting for my vendor to get back to me.  I will update this question asap.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Article by: Nadia
Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now