1

I have the following code that I need to get rid of the Microsoft.VisualBasic function ASC():

Dim keyWithoutDashes As String = p_licenseKey.Replace("-", "").Trim.ToLower
Dim checksum As Int32 = 0
Dim modValue As Byte
Dim checkValue As Byte
Dim checkChar As Char
checksum = 0
checkValue = CByte(Asc(keyWithoutDashes.Substring(24, 1)))
For pos = 0 To 23
    checksum += CByte(Asc(keyWithoutDashes.Substring(pos, 1)))
Next
checksum = checksum Mod 34
modValue = CByte(Asc(VALID_CHARACTERS_BACKWARD.Substring(checksum, 1)))
If modValue <> checkValue Then
    m_keyErrorMessage = "Invalid LicenseKey"
    Return False
End If

I have tried casting as int with no success. Any suggestions?

I need to make the code work in a Microsoft Portable Class Library.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Robert Beaubien
  • 3,126
  • 4
  • 22
  • 29
  • Is this what you're looking for? [Converting a character code to char (VB.NET)](http://stackoverflow.com/questions/4857866/converting-a-character-code-to-char-vb-net) – ADP_X Sep 26 '14 at 08:01
  • If you really need the `Asc` function and can't use `Microsoft.VisualBasic.dll`, you could just take a look at the [reference source](http://referencesource.microsoft.com/#Microsoft.VisualBasic/Strings.vb#245) and recreate/copy it yourself. – sloth Sep 26 '14 at 08:14
  • 2
    Asc() is a legacy function that pretends that Unicode doesn't exist. It should only ever be used to port legacy VBx code, preserving an ancient file format for example. Today you should always use AscW(), not just in PCL projects. Use Encoding.GetBytes() to convert a string to an array of bytes, you have to pick the correct Encoding class. Perhaps Encoding.Default, depending on where the data came from. Should not matter for a license key, it ought to only contain ASCII codes. – Hans Passant Sep 26 '14 at 09:22
  • How long does it take to check all possible 34 values for the last character until you hit a valid key? – John Alexiou Sep 26 '14 at 18:03
  • Um... That is just a very small part of the information and validation of the key. :-) – Robert Beaubien Sep 27 '14 at 15:55

1 Answers1

1

The answer thanks to Hans Passant's comment above:

checksum = 0
checkValue = Encoding.ASCII.GetBytes(keyWithoutDashes.Substring(24, 1))(0)
For pos = 0 To 23
  checksum += Encoding.ASCII.GetBytes(keyWithoutDashes.Substring(pos, 1))(0)
Next
checksum = checksum Mod 34
modValue = Encoding.ASCII.GetBytes(
  VALID_CHARACTERS_BACKWARD.Substring(checksum, 1))(0)

If modValue <> checkValue Then
  m_keyErrorMessage = "Invalid LicenseKey"
  Return False
End If
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Robert Beaubien
  • 3,126
  • 4
  • 22
  • 29