Solved

Simple Encrypt / Decrypt solution needed

Posted on 2006-07-17
11
344 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
Comment Utility
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
Comment Utility
By the way don't forget to add:

Imports System.Security.Cryptography

before your class. :-)
0
 

Author Comment

by:thomp361
Comment Utility
Hi,

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


0
 
LVL 4

Expert Comment

by:sr101880
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 4

Accepted Solution

by:
sr101880 earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
btw,  What was the max length of the string you were looking for?
0
 

Author Comment

by:thomp361
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

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

16 Experts available now in Live!

Get 1:1 Help Now