Justin8051
Justin8051

Reputation: 429

Converting SHA-2 hash into alphanumeric hash (vb.net)

I have SHA-2 hash values. Here's an example:

qlbQbEd8khe2vEYG9acKScUiVTC6y1UorkMvptATwwxkVApkOCUH7hwkncbi2TY78HrIeC19G8EHlaAmj6sBAwCxhF2TeOpmJ1+2OfbfXF+jMWUO74O7WHJuwoq+R5aKa0c2QYbyrcd/DWSprdkrF1gyz+RWVXYQug63aAhC0j0=

I need to convert these into an alphanumeric hash — that is, using only capital letters and numbers ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"). The process has to be reversible for SHA-2 hash comparison.

The reason for this conversion is aesthetics. The resulting hash will be used as a license key, and has to be shorter and more easily readable and typeable.

I read that I could try to re-encode that hash into Base36, but I have been unsuccessful. Can anyone give any suggestions?

Upvotes: 0

Views: 224

Answers (1)

Mo Khalefa
Mo Khalefa

Reputation: 576

This code is an example for converting Base36 to/from Base26

Const Base36 As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const Base26 As String = "abcdefghijklmnopqrstuvwxyz"

Function Num2Base(Vlu As Long, Base As String) As String
    Dim A() As Integer = Nothing
    Dim y As Integer = -1
    Dim X As Long = Vlu
    Dim Ln As Integer = Base.Length
    Do While X > -1
        y = y + 1
        ReDim Preserve A(y)
        A(y) = X Mod Ln
        X = ((X - A(y)) / Ln) - 1
    Loop
    Dim res As String = ""
    If y >= 0 Then
        For Each d As Integer In A
            res &= Mid(Base, d + 1, 1)
        Next
    End If
    Return res
End Function
Function Base2Num(s As String, Base As String) As Long
    If s.Length = 0 Then
        Throw New Exception("'S' can not be empty")
    End If

    Dim res As Long = -1
    Dim Ln As Integer = Base.Length
    Dim x As Integer = 0
    For Each c In s
        res += (Base.IndexOf(c) + 1) * (Ln ^ x)
        x += 1
    Next
    Return res
End Function

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim Num As Long = 1313
    Dim b36 As String = Num2Base(Num, Base36) 'convert Num to base36
    Dim b26 As String = Num2Base(Num, Base26) 'convert Num to base26
    MessageBox.Show("Num:" & Num & vbCrLf & "ToBase36:" & b36 & vbCrLf & "ToBase26:" & b26, "Message 1")

    Dim N36 As Long = Base2Num(b36, Base36) 'convert Base36 to Num
    Dim N26 As Long = Base2Num(b26, Base26) 'convert Base26 to Num
    MessageBox.Show("N36:" & N36 & vbCrLf & "N26:" & N26, "Message 2")

    b26 = Num2Base(Base2Num(b36, Base36), Base26) 'convert Base36 to Base 26

    MessageBox.Show("Base36 to Base 26 :" & b26, "Message 3")

    b36 = Num2Base(Base2Num(b26, Base26), Base36) 'convert Base26 to Base 36
    MessageBox.Show("Base26 to Base 36 :" & b36, "Message 4")

    MessageBox.Show(Num2Base(1486154465904653, Base36), "Message 5")
End Sub

Unfortunately this code can not work with long strings(more than 12 chrs) due the limitation of the type Long,so you may need to split SHA-2 string to small parts

Upvotes: 0

Related Questions