Solved

Simple Encrypt / Decrypt solution needed

Posted on 2006-07-17
11
348 Views
Last Modified: 2008-01-09
Hi,

I need to encrypt / decrypt some strings.  

I would like the resulting encrypted strings to be shorter in length then what the TripleDESCryptoServiceProvider returns (after the ToBase64String call)

I don't need the encryption algo to be very strong as the data isn't that sensitive....I am more concerned about the final encrypted string's length.

Anyone have any ideas?

Thanks!
0
Comment
Question by:thomp361
  • 8
  • 3
11 Comments
 
LVL 4

Expert Comment

by:sr101880
ID: 17122322
This class should do the trick it is using sha1 but as you can see you change it to a couple different types:

   Public Class myHash

        Public Shared Function ComputeHash(ByVal plainText As String, _
                                           ByVal saltBytes() As Byte) _
                                           As String

            ' If salt is not specified, generate it on the fly.
            If (saltBytes Is Nothing) Then

                'Define min and max salt sizes.
                Dim minSaltSize As Integer
                Dim maxSaltSize As Integer

                minSaltSize = 4
                maxSaltSize = 8

                'Generate a random number for the size of the salt.
                Dim random As Random
                random = New Random

                Dim saltSize As Integer
                saltSize = random.Next(minSaltSize, maxSaltSize)

                'Allocate a byte array, which will hold the salt.
                saltBytes = New Byte(saltSize - 1) {}

                ' Initialize a random number generator.
                Dim rng As RNGCryptoServiceProvider
                rng = New RNGCryptoServiceProvider

                'Fill the salt with cryptographically strong byte values.
                rng.GetNonZeroBytes(saltBytes)

            End If

            ' Convert plain text into a byte array.
            Dim plainTextBytes As Byte()
            plainTextBytes = Encoding.UTF8.GetBytes(plainText)

            ' Allocate array, which will hold plain text and salt.
            Dim plainTextWithSaltBytes() As Byte = New Byte(plainTextBytes.Length + saltBytes.Length - 1) {}

            ' Copy plain text bytes into resulting array.
            Dim I As Integer
            For I = 0 To plainTextBytes.Length - 1
                plainTextWithSaltBytes(I) = plainTextBytes(I)
            Next I

            ' Append salt bytes to the resulting array.
            For I = 0 To saltBytes.Length - 1
                plainTextWithSaltBytes(plainTextBytes.Length + I) = saltBytes(I)
            Next I

            ' Set hashing algorithm.
            Dim hash As HashAlgorithm
            hash = New SHA1Managed
            'hash = New SHA256Managed
            'hash = New SHA384Managed
            'hash = New SHA512Managed
            'hash = New MD5CryptoServiceProvider

            ' Compute hash value of our plain text with appended salt.
            Dim hashBytes As Byte()
            hashBytes = hash.ComputeHash(plainTextWithSaltBytes)

            ' Create array which will hold hash and origanl salt bytes.
            Dim hashwithSaltBytes() As Byte = New Byte(hashBytes.Length + saltBytes.Length - 1) {}

            ' Copy hash bytes into resulting array.
            For I = 0 To hashBytes.Length - 1
                hashwithSaltBytes(I) = hashBytes(I)
            Next I

            ' Append salt bytes to the result.
            For I = 0 To saltBytes.Length - 1
                hashwithSaltBytes(hashBytes.Length + I) = saltBytes(I)
            Next I

            ' Convert result into a base64-encoded string.
            Dim hashValue As String
            hashValue = Convert.ToBase64String(hashwithSaltBytes)

            'Return the result.
            ComputeHash = hashValue


        End Function

        ' <summary>
        ' Compares a hash of the specified plan text value to a given hash value.  
        ' Plain text is hashed with the same salt value as the original hash.
        ' </summary>

        Public Shared Function VerifyHash(ByVal plainText As String, _
                                          ByVal hashValue As String) _
                                          As Boolean

            ' Convert base64-encoded hash value into a byte array.
            Dim hashWithSaltBytes As Byte()
            hashWithSaltBytes = Convert.FromBase64String(hashValue)

            ' We must know the size of hash (without salt).
            Dim hashSizeInBits As Integer
            Dim hashSizeInBytes As Integer

            'Size of hash is based on the specified alogorithm.
            hashSizeInBits = 160 'SHA1

            'hashSizeInBits = 256 'SHA256
            'hashSizeInBits = 384 'SHA384
            'hashSizeInBits = 512 'SHA512
            'hashSizeInBits = 128 'MD5

            ' Convert size of hash from bits to bytes.
            hashSizeInBytes = hashSizeInBits / 8

            'Make sure that the specified hash value is long enough.
            If (hashWithSaltBytes.Length < hashSizeInBytes) Then
                VerifyHash = False
            End If

            ' Allocate array to hold original salt bytes retrieved from hash.
            Dim saltBytes() As Byte = New Byte(hashWithSaltBytes.Length - hashSizeInBytes - 1) {}

            ' Copy salt from the end of the hash to the new array.
            Dim I As Integer
            For I = 0 To saltBytes.Length - 1
                saltBytes(I) = hashWithSaltBytes(hashSizeInBytes + I)
            Next I

            ' Compute a new hash string.
            Dim expectedHashString As String
            expectedHashString = ComputeHash(plainText, saltBytes)

            ' If the computed hash matches the specified hash,
            ' the plain text value must be correct.
            VerifyHash = (hashValue = expectedHashString)

        End Function


    End Class


Let me know if you have any questions.
0
 
LVL 4

Expert Comment

by:sr101880
ID: 17122343
By the way don't forget to add:

Imports System.Security.Cryptography

before your class. :-)
0
 

Author Comment

by:thomp361
ID: 17122480
Hi,

Thanks for the response but....I need to decrypt the string......so hashing won't work in my scenario.


0
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

 
LVL 4

Expert Comment

by:sr101880
ID: 17122493
I am sorry the above class only does a compare after the encrypt.  This function is very simple and it will do what you requested:

    Function EncryptnDeCrypt(ByVal Pwd As Object) As String

        Dim Temp As String
        Dim PwdChr As Integer
        Dim EncryptKey As Integer

        EncryptKey = Int(Math.Sqrt(Len(Pwd) * 81)) + 23

        'EncryptKey = Int(Math.Sqrt(Len(Pwd) * 91)) + 23


        For PwdChr = 1 To Len(Pwd)
            Temp = Temp + Chr(Asc(Mid(Pwd, PwdChr, 1)) Xor EncryptKey)
        Next PwdChr

        EncryptPassword = Temp

    End Function

You can change the key as needed like the commented line above.
0
 
LVL 4

Expert Comment

by:sr101880
ID: 17122519
I was writting this new post just as you posted a reply sorry about the misunderstanding. :-)  All you have to do is send the text to the function and it Encrypt or Decrypt as needed.  Let me know if you have any questions.
0
 
LVL 4

Accepted Solution

by:
sr101880 earned 500 total points
ID: 17122571
I am on a roll today.  I made another mistake on my post the function should be as follows:

  Function EncryptnDeCrypt(ByVal Pwd As Object) As String

        Dim Temp As String
        Dim PwdChr As Integer
        Dim EncryptKey As Integer

        EncryptKey = Int(Math.Sqrt(Len(Pwd) * 81)) + 23

        'EncryptKey = Int(Math.Sqrt(Len(Pwd) * 91)) + 23


        For PwdChr = 1 To Len(Pwd)
            Temp = Temp + Chr(Asc(Mid(Pwd, PwdChr, 1)) Xor EncryptKey)
        Next PwdChr

        EncryptnDeCrypt= Temp

    End Function
0
 
LVL 4

Expert Comment

by:sr101880
ID: 17122591
Thanks for being patient with me.  I am heading straight to the kitchen for a coffee so I will smarten up.  ;-)
0
 

Author Comment

by:thomp361
ID: 17123059
Thanks, so how do I decrypt using this?

This algo does create a shorter encrypted string than 3DES, anyway to make it even shorter?

Thanks for your help!
0
 
LVL 4

Expert Comment

by:sr101880
ID: 17123693
All you need to do is send the encrypted string to same function to decrypt.  I don't know of a way to make it shorter than this.  I will do some digging, if I find anything I will post it for you.  Let me know if you run into any trouble.
0
 
LVL 4

Expert Comment

by:sr101880
ID: 17123706
btw,  What was the max length of the string you were looking for?
0
 

Author Comment

by:thomp361
ID: 17124454
I guess I should explain a little further.

I need the final encrypted string to be in the format of {A-Z,a-z,0-9}.

So I've been trying to convert the encrypted bytes into other bases, I can't use base64 because it has a couple special chars that don't fit in my above subset.  

So, in the end, my need to have the encrypted string converted to a string that uses {A-Z,a-z,0-9} as it's chars, kind of changes my ability to make the string shorter.

Your decrypt/encrypt function works great, this is probably beyond the scope my original question so I'll just award you the points.  Thanks for your help!

Sorry I didn't follow your decrypt....I think it didn't work for me because of the base conversions I was trying.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Opening and Closing Connections and Data Adapters 10 49
Receiving a string from a WebService Push 21 47
Close form "before" open 3 40
get row value in vb.net 4 14
Article by: Kraeven
Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

773 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