Monday, July 19, 2010

Retrieve Windows Product Key Function

I found a nice little function to retrieve the Windows Product Key.
Credits go to Digital Thunder : http://www.codeproject.com/KB/vb/SysInfo.aspx

' Usage : GetProductKey("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\")
' A function that retrieves the product key used to install Windows.
 
    Public Function GetProductKey(ByVal regKey As String) As String
 
        ' This function will retreive the digital product ID from the registry 
        ' and decode it into the CD key used to install a Microsoft product.
        ' All that is needed is the registry path to the digital proudct ID block
        ' for the product in question.
 
        Dim validChars() As String = {"B", "C", "D", "F", "G", "H", "J", "K", "M", _
                                      "P", "Q", "R", "T", "V", "W", "X", "Y", "2", _
                                      "3", "4", "6", "7", "8", "9"}
        Dim CDKey As String = ""
 
        Dim encodedKey(15) As Byte
        Dim digitalProductID As Byte()
        Dim dpidDataBlock As Object
 
        ' Get the Digital Product ID data-block from the registry.
        dpidDataBlock = My.Computer.Registry.GetValue(regKey, "DigitalProductId", 0)
 
        If dpidDataBlock Is Nothing Then Return "Not Available"
 
        digitalProductID = DirectCast(dpidDataBlock, Byte())
 
        ' Extract the encoded CD key (15 bytes) from the digital product ID block.
        For n As Integer = 52 To 67
            encodedKey(n - 52) = digitalProductID(n)
        Next
 
        ' Decode the CD key.
        ' Note: The actual CD key is not stored in the registry; only the positions  
        ' within the validChars() array of the characters that make up the CD key
        ' are stored and encoded.
 
        For i As Integer = 28 To 0 Step -1
            ' Calculate where the dashes are.
            If ((i + 1) Mod 6) = 0 Then
                CDKey += " - "
            Else
                Dim j As Integer = 0
                For k As Integer = 14 To 0 Step -1
                    Dim Value As Integer = CInt(CLng(j * 2 ^ 8) Or encodedKey(k))
                    encodedKey(k) = CByte(Value \ 24)
                    ' Position within the validChar() array of the character to add to the CD key string.
                    j = Value Mod 24
                Next
                CDKey += validChars(j)
            End If
        Next
        Return StrReverse(CDKey)
 
    End Function

No comments:

Post a Comment