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
Solved

Simple Encrypt / Decrypt solution needed

Posted on 2006-07-17
11
349 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
VB.NET - Error - Object not set in Module 4 39
get row value in vb.net 4 17
.NET 2008 VB and C# 6 39
VB.NET 2008 - Windows Protected Your PC 7 41
This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
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…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

856 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