Home » Programming » C# » Updated version of CryptographyHelper class for .NET Framework 4

Updated version of CryptographyHelper class for .NET Framework 4

posted in: C#, Cryptography, Programming, VB.Net 1

This updated version of mine “CryptographyHelper” wrapper/helper class supports .NET Framework 4 .

With this vb.net class you can easly encrypt/decrypt strings using a robust symmetric Rijndael algorithm or you can get also MD5 or SHA1, SHA256 hash codes of a string.

During the encryption, the CryptographyHelper encrypts a clear text and saves it in a binary stream, then converts the binary output in Hexadecimal or Base64 encoding type for a string rapresentation. The opposite job during the decryption.

How to use:


[sourcecode language=”vb”] Imports {project’s name}.Cryptography

Dim crypt As New CryptographyHelper

‘select your favorite encoding type (Hexadecimal or Base64) for encrypted/decryptet text
‘in output/input;
‘during the encryption, the CryptographyHelper encrypts a clear text and saves it in a
‘binary stream, then converts the binary output in Hexadecimal or Base64 encoding type
‘for a string rapresentation. The opposite job during the decryption.
crypt.EncodingType = CryptographyHelper.ENCODING_TYPE.Hexadecimal

‘choose a password
Dim password As String = "my secret password"

‘encrypt/decrypt strings using a robust symmetric Rijndael algorithm
Dim encrypted_text As String = crypt.Encrypt("plain text to encrypt…", password)
Dim decrypted_text As String = crypt.Decrypt(encrypted_text, password)

‘you can also get an hash of a string
Dim MD5hash As String = crypt.GetHash("string to hash", CryptographyHelper.HASH_TYPE.MD5)
Dim SHA1hash As String = crypt.GetHash("string to hash", CryptographyHelper.HASH_TYPE.SHA1)
Dim SHA256hash As String = crypt.GetHash("string to hash", CryptographyHelper.HASH_TYPE.SHA256)
[/sourcecode]

Enjoy 🙂

Max

[sourcecode language=”vb”]

‘ CryptographyHelper & Cryptography VB.NET classes for .NET Framework 4
‘ https://www.maxvergelli.com/

‘ Copyright (c) 2016 Max Vergelli

‘ Vers. 3.5.1
‘ Date: 23/03/2016

‘ Description:
‘ With the “CryptographyHelper” wrapper class, you can easly encrypt/decrypt strings in
‘ .NET Framework 4 using a robust symmetric Rijndael algorithm or you can get also MD5
‘ or SHA1, SHA256 hash codes of a string.
‘ During the encryption, the CryptographyHelper encrypts a clear text and saves it in a
‘ binary stream, then converts the binary output in Hexadecimal or Base64 encoding type
‘ for a string rapresentation. The opposite job during the decryption.


‘ Usage:

‘ Imports {project’s name}.Cryptography

‘ Dim crypt As New CryptographyHelper

‘ ‘select your favorite encoding type (Hexadecimal or Base64) for encrypted/decryptet text
‘ ‘in output/input;
‘ ‘during the encryption, the CryptographyHelper encrypts a clear text and saves it in a
‘ ‘binary stream, then converts the binary output in Hexadecimal or Base64 encoding type
‘ ‘for a string rapresentation. The opposite job during the decryption.
‘ crypt.EncodingType = CryptographyHelper.ENCODING_TYPE.Hexadecimal

‘ ‘choose a password
‘ Dim password As String = "my secret password"

‘ encrypt/decrypt strings using a robust symmetric Rijndael algorithm
‘ Dim encrypted_text As String = crypt.Encrypt("plain text to encrypt…", password)
‘ Dim decrypted_text As String = crypt.Decrypt(encrypted_text, password)

‘ ‘you can also get an hash of a string
‘ Dim MD5hash As String = crypt.GetHash("string to hash", CryptographyHelper.HASH_TYPE.MD5)
‘ Dim SHA1hash As String = crypt.GetHash("string to hash", CryptographyHelper.HASH_TYPE.SHA1)
‘ Dim SHA256hash As String = crypt.GetHash("string to hash", CryptographyHelper.HASH_TYPE.SHA256)


‘ License:

‘ Permission is hereby granted, free of charge, to any person obtaining a copy
‘ of this software and associated documentation files (the "Software"), to deal
‘ in the Software without restriction, including without limitation the rights
‘ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
‘ copies of the Software, and to permit persons to whom the Software is
‘ furnished to do so, subject to the following conditions:

‘ The above copyright notice and this permission notice shall be included in
‘ all copies or substantial portions of the Software.

‘ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
‘ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
‘ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
‘ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
‘ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
‘ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
‘ THE SOFTWARE.

Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

Namespace Cryptography

Public Class CryptographyHelper

Private _encoding As ENCODING_TYPE

Public Enum ENCODING_TYPE As Integer
Hexadecimal = 1
Base64 = 2
End Enum

Public Enum HASH_TYPE As Integer
MD5 = 1
SHA1 = 2
SHA256 = 3
SHA512 = 4
End Enum

Public Sub New(Optional ByVal encoding As ENCODING_TYPE = ENCODING_TYPE.Hexadecimal)

‘by default encryption/hashing outputs hexadecimal strings
‘and decryption get hexstrings as input
If encoding <> ENCODING_TYPE.Hexadecimal And encoding <> ENCODING_TYPE.Base64 Then
encoding = ENCODING_TYPE.Hexadecimal
End If
_encoding = encoding

End Sub

Public Property EncodingType() As ENCODING_TYPE
Get
Return _encoding
End Get
Set(ByVal value As ENCODING_TYPE)
_encoding = value
End Set
End Property

Public Function GetHash(ByRef input As String, Optional ByVal type As HASH_TYPE = HASH_TYPE.MD5) As String

Dim crypt As New Cryptography
Dim bytes() As Byte = Nothing
Select Case type
Case HASH_TYPE.MD5
bytes = crypt.CreateMD5Hash(input)
Case HASH_TYPE.SHA1
bytes = crypt.CreateSHA1Hash(input)
Case HASH_TYPE.SHA256
bytes = crypt.CreateSHA256Hash(input)
Case HASH_TYPE.SHA512
bytes = crypt.CreateSHA512Hash(input)
Case Else
bytes = crypt.CreateMD5Hash(input)
End Select
Dim hash As String = ""
Select Case _encoding
Case ENCODING_TYPE.Hexadecimal
hash = crypt.BytesToHexString(bytes)
Case ENCODING_TYPE.Base64
hash = crypt.BytesToBase64(bytes)
Case Else
hash = crypt.BytesToHexString(bytes)
End Select
crypt = Nothing
Return hash

End Function

Public Function Encrypt(ByRef input As String, ByRef password As String) As String

Dim crypt As New Cryptography(password)
Dim bytes() As Byte = crypt.Encrypt(input)
Dim encrypted As String = ""
If bytes IsNot Nothing Then
Select Case _encoding
Case ENCODING_TYPE.Hexadecimal
encrypted = crypt.BytesToHexString(bytes)
Case ENCODING_TYPE.Base64
encrypted = crypt.BytesToBase64(bytes)
Case Else
encrypted = crypt.BytesToHexString(bytes)
End Select
End If
crypt = Nothing
Return encrypted

End Function

Public Function Decrypt(ByRef input As String, ByRef password As String) As String

Dim decrypted As String = ""
If input.Length > 0 Then
Dim crypt As New Cryptography(password)
Dim enc_bytes() As Byte = Nothing
Select Case _encoding
Case ENCODING_TYPE.Hexadecimal
enc_bytes = crypt.HexStringToBytes(input)
Case ENCODING_TYPE.Base64
enc_bytes = crypt.Base64ToBytes(input)
Case Else
enc_bytes = crypt.HexStringToBytes(input)
End Select
decrypted = crypt.Decrypt(enc_bytes)
crypt = Nothing
End If
Return decrypted

End Function

End Class

Public Class Cryptography

Private _key_str As String = Nothing
Private _key_byte() As Byte = Nothing
Private _txt_converter As New UnicodeEncoding
Private _rijndael As New RijndaelManaged ‘"rèin-daal" 🙂

Public Sub New(Optional ByVal encryption_key As String = "")

If encryption_key <> "" Then EncryptionKey = encryption_key

End Sub

Protected Overrides Sub Finalize()

If _txt_converter IsNot Nothing Then
_txt_converter = Nothing
End If
If _rijndael IsNot Nothing Then
_rijndael = Nothing
End If
_key_str = Nothing
_key_byte = Nothing

End Sub

Public Property EncryptionKey() As String

Get
Return _key_str
End Get

Set(ByVal value As String)

Try
‘set the key string
_key_str = value

‘set hash in bytes of the key string
Dim hash256 As New SHA256Managed
_key_byte = hash256.ComputeHash(_txt_converter.GetBytes(_key_str))
hash256 = Nothing

‘If UBound(_key_byte) < 0 Then Exit Property ‘.NET <= 3.5
If _key_byte.GetUpperBound(0) < 0 Then Exit Property ‘.NET Framework 4

‘set Rijndael Key and IV vector for 256 bit encryption
Dim main_key(31) As Byte
Dim main_vector(15) As Byte
Dim diff_block As Integer = 5
_rijndael.KeySize = 256 ‘bit

Dim n As Integer = 0
Dim x As Integer = 0
Dim y As Integer = 0

‘For n = 0 To UBound(main_key) ‘.NET <= 3.5
For n = 0 To main_key.GetUpperBound(0) ‘.NET Framework 4

main_key(n) = _key_byte(x)
‘If n > diff_block And n <= UBound(main_vector) + diff_block Then ‘.NET <= 3.5
If n > diff_block And n <= main_vector.GetUpperBound(0) + diff_block Then ‘.NET Framework 4
main_vector(y) = _key_byte(x)
y = y + 1
End If
x = x + 1

‘If x > UBound(_key_byte) Then x = 0 ‘.NET <= 3.5
If x > _key_byte.GetUpperBound(0) Then x = 0 ‘.NET Framework 4

Next
_rijndael.Key = main_key
_rijndael.IV = main_vector

Catch

‘set a blank encryption key then we cannot encrypt/decrypt
_key_str = Nothing

End Try

End Set

End Property

Public Function Encrypt(ByRef clear_text As String) As Byte()

Dim enc_bytes() As Byte = Nothing
Try
If _key_str IsNot Nothing Then
‘get byte array from text
Dim bytes() As Byte = _txt_converter.GetBytes(clear_text)

‘encrypt data
Dim encryptor As ICryptoTransform = _rijndael.CreateEncryptor()
Dim msEncrypt As New MemoryStream
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)

‘write all data to the crypto stream and flush it
csEncrypt.Write(bytes, 0, bytes.Length)
csEncrypt.FlushFinalBlock()

‘get encrypted byte array
enc_bytes = msEncrypt.ToArray()

msEncrypt = Nothing
csEncrypt = Nothing
End If
Catch

End Try

Return enc_bytes

End Function

Public Function Decrypt(ByRef encrypted_text() As Byte) As String

Dim dec_text As String = Nothing

Try
If _key_str IsNot Nothing Then
Dim decryptor As ICryptoTransform = _rijndael.CreateDecryptor()
Dim msDecrypt As New MemoryStream(encrypted_text)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

‘prepare buffer
Dim bytes() As Byte = New Byte(encrypted_text.Length – 1) {}

‘read the data out of the crypto stream
csDecrypt.Read(bytes, 0, bytes.Length)

‘convert the byte array back into a string
dec_text = _txt_converter.GetString(bytes)

‘strip null chars at the end of the string
StripNullAtEnd(dec_text)

msDecrypt = Nothing
csDecrypt = Nothing
End If
Catch

End Try

Return dec_text

End Function

Public Function BytesToBase64(ByRef input_bytes() As Byte) As String

Dim s As String = Nothing
Try
s = Convert.ToBase64String(input_bytes)
Catch

End Try
Return s

End Function

Public Function Base64ToBytes(ByRef input_base64 As String) As Byte()

Dim b() As Byte = Nothing
Try
b = Convert.FromBase64String(input_base64)
Catch

End Try
Return b

End Function

Public Function BytesToHexString(ByRef input_bytes() As Byte) As String

Dim s As String = Nothing
Try
‘Dim s As String = BitConverter.ToString(input_bytes).Replace("-", String.Empty)
Dim builder As New StringBuilder()
For i As Integer = 0 To input_bytes.Length – 1
builder.AppendFormat("{0:x2}", input_bytes(i))
Next
s = builder.ToString()
builder = Nothing
Catch

End Try
Return s

End Function

Public Function HexStringToBytes(ByRef input_hex_string As String) As Byte()

Dim bytes As Byte() = Nothing
Try
‘i variable used to hold position in string
Dim i As Integer = 0
‘x variable used to hold byte array element position
Dim x As Integer = 0
‘allocate byte array based on half of string length
bytes = New Byte((input_hex_string.Length) 2 – 1) {}
‘loop through the string – 2 bytes at a time converting
‘it to decimal equivalent and store in byte array
While input_hex_string.Length > i + 1
Dim lngDecimal As Long = Convert.ToInt32(input_hex_string.Substring(i, 2), 16)
bytes(x) = Convert.ToByte(lngDecimal)
i = i + 2
x += 1
End While
‘return the finished byte array of decimal values
Catch

End Try
Return bytes

End Function

Public Function CreateMD5Hash(ByRef input As String) As Byte()

Dim hash As Byte() = Nothing
Try
Dim bytes() As Byte = _txt_converter.GetBytes(input)
Dim objMD5 As New MD5CryptoServiceProvider
hash = objMD5.ComputeHash(bytes)
objMD5 = Nothing
Catch

End Try
Return hash

End Function

Public Function CreateSHA1Hash(ByRef input As String) As Byte()

Dim hash As Byte() = Nothing
Try
Dim bytes() As Byte = _txt_converter.GetBytes(input)
Dim objSHA As New SHA1CryptoServiceProvider
hash = objSHA.ComputeHash(bytes)
objSHA = Nothing
Catch

End Try
Return hash

End Function

Public Function CreateSHA256Hash(ByRef input As String) As Byte()
Dim hash As Byte() = Nothing
Try
Dim bytes() As Byte = _txt_converter.GetBytes(input)
Dim objSHA As New SHA256CryptoServiceProvider
hash = objSHA.ComputeHash(bytes)
objSHA = Nothing
Catch

End Try
Return hash

End Function

Public Function CreateSHA512Hash(ByRef input As String) As Byte()
Dim hash As Byte() = Nothing
Try
Dim bytes() As Byte = _txt_converter.GetBytes(input)
Dim objSHA As New SHA512CryptoServiceProvider
hash = objSHA.ComputeHash(bytes)
objSHA = Nothing
Catch

End Try
Return hash

End Function

Private Sub StripNullAtEnd(ByRef input_string As String)

Dim nullchar As Char = Convert.ToChar(0) ‘&H0
If input_string.Length > 0 And input_string.EndsWith(nullchar.ToString) Then
Dim n As Long
For n = input_string.Length – 1 To 0 Step -1
If input_string.Chars(n) <> nullchar Then
input_string = input_string.Substring(0, n + 1)
Exit For
End If
Next
End If
Convert.ToString(input_string)

End Sub

End Class

End Namespace

[/sourcecode]

  1. Serdar
    | Reply

    Hi,

    Code at line 380 :
    bytes = New Byte((input_hex_string.Length) 2 – 1) {}

    there is a problem with this. Can you please take a look at that ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.