?
Solved

VB.NET encryption using AES algorithm and given passphrase.

Posted on 2015-02-03
5
Medium Priority
?
707 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 34

Accepted Solution

by:
it_saige earned 2000 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

752 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