Application that creates a license key for your applications

This piece of code is ALL the code behind for a standard .net 1 form application that generates a license key that can be used by your applications. 

The form looks like this:

And, here is the code that consumes the key:

    Private Sub ProcessLicenseKey()
 
        ' This subroutine reads the distribution key, decrypts it, extracts the
        ' expiration date, and warns as expiration is within 2 months, and exits
        ' if expiration is past.
        Dim baseDir = Path.GetDirectoryName(Application.ExecutablePath)
        Dim expirationDate As DateTime
        Dim keyValid As Boolean = True
 
        Try
            Dim encryptedText As String = File.ReadAllText(Path.Combine(baseDir, "KEY.DAT"))
            Dim licenseKey As LicenseKey = New LicenseKey()
            expirationDate = licenseKey.GetExpirationDate(encryptedText)
            If Not (ValidKey(expirationDate)) Then
                Application.Exit()
            End If
 
        Catch ex As FileNotFoundException
            Dim msg As String = "Unable to read distribution key." + vbCrLf
            msg += String.Format("Error: {0}", ex.Message) + vbCrLf
            msg += "Contact your Run-Biz representative." + vbCrLf
            msg += "Program will be terminated."
            MessageBox.Show(msg)
            keyValid = False
 
        Catch ex As Exception
            Dim msg As String = "Unexpected error occurred." + vbCrLf
            msg += String.Format("Error: {0}", ex.Message) + vbCrLf
            msg += "Contact your Run-Biz representative." + vbCrLf
            msg += "Program will be terminated."
            MessageBox.Show(msg)
            keyValid = False
 
        End Try
 
        If Not keyValid Then
            Application.Exit()
        End If
 
    End Sub
End Class

 

 

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text
Public Class Form1
 
    Dim customerName As String
    Dim expirationDate As String
    Dim serverName As String
 
    Dim passPhrase As String = "MickeyScentMe"
    Dim saltValue As String = "NaCl4AllF00ds"
    Dim hashAlgorithm As String = "SHA1"
 
    Dim passwordIterations As Integer = 2
    Dim initVector As String = "@1B2c3D4e5F6g7H8"
    Dim keySize As Integer = 256
 
    Dim baseDir = Path.GetDirectoryName(Application.ExecutablePath) 'Application.ExecutablePath
 
    Private Function GetStringToEncrypt() As String
 
        Dim source As String
 
        source = String.Format("{0}|{1}|{2}|{3}", "RUNBIZ", serverName, customerName, expirationDate)
        Return source
 
    End Function
 
    Private Function GetValues() As Boolean
 
        lblStatus.ForeColor = Color.Red
 
        customerName = txtCustomerName.Text.Trim().ToUpper()
        If String.IsNullOrEmpty(customerName) Then
            lblStatus.Text = "Customer name cannnot be blank."
            Return False
        End If
 
        expirationDate = dtpExpirationDate.Value.ToString("MMddyyyy")
        serverName = txtServerName.Text.Trim().ToUpper()
        If String.IsNullOrEmpty(serverName) Then
            lblStatus.Text = "Server name cannnot be blank."
            Return False
        End If
 
        Return True
 
    End Function
 
    Public Function Encrypt(ByVal plainText As String) As String
 
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
 
        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
 
 
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
 
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()
 
        symmetricKey.Mode = CipherMode.CBC
 
        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
 
        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
 
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function
 
    Public Function Decrypt(ByVal cipherText As String) As String
        ' Convert strings defining encryption key characteristics into byte
        ' arrays. Let us assume that strings only contain ASCII codes.
        ' If strings include Unicode characters, use Unicode, UTF7, or UTF8
        ' encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
 
        ' Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
 
        ' First, we must create a password, from which the key will be
        ' derived. This password will be generated from the specified
        ' passphrase and salt value. The password will be created using
        ' the specified hash algorithm. Password creation can be done in
        ' several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
 
        ' Use the password to generate pseudo-random bytes for the encryption
        ' key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
 
        ' Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()
 
        ' It is reasonable to set encryption mode to Cipher Block Chaining
        ' (CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC
 
        ' Generate decryptor from the existing key bytes and initialization
        ' vector. Key size will be defined based on the number of the key
        ' bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
 
        ' Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New MemoryStream(cipherTextBytes)
 
        ' Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
 
        ' Since at this point we don't know what the size of decrypted data
        ' will be, allocate the buffer long enough to hold ciphertext;
        ' plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
 
        ' Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
 
        ' Close both streams.
        memoryStream.Close()
        cryptoStream.Close()
 
        ' Convert decrypted data into a string.
        ' Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
 
        ' Return decrypted string.  
        Return plainText
    End Function
 
    Private Function CreateKey() As String
 
        Dim plainText As String = GetStringToEncrypt()
        plainText = plainText.PadRight(64, " ")
 
        Dim strEncryptedText As String
        strEncryptedText = Encrypt(plainText)
        lblEncryptedText.Text = strEncryptedText
 
        Dim strDecrptedText As String
        strDecrptedText = Decrypt(strEncryptedText).Trim()
        lblPlainText.Text = strDecrptedText
 
        Return strEncryptedText
 
    End Function
 
    Public Sub SaveKey(key As String)
 
        Dim keyDir = Path.Combine(baseDir, customerName.Replace(" ", ""))
        Directory.CreateDirectory(keyDir)
        File.WriteAllText(Path.Combine(keyDir, "KEY.DAT"), key)
        lblStatus.Text = String.Format("Key saved as: {0}\{1}", keyDir, "KEY.DAT")
 
    End Sub
 
    Private Sub btnCreateKey_Click(sender As Object, e As EventArgs) Handles btnCreateKey.Click
 
        Dim encryptedText As String
 
        lblStatus.Text = "Generating Key"
        If GetValues() Then
            encryptedText = CreateKey()
            SaveKey(encryptedText)
        End If
 
    End Sub
 
    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
 
        Application.Exit()
 
    End Sub
 
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
 
        ' Default date to 1 year from today
        dtpExpirationDate.Value = DateTime.Now().AddYears(1)
    End Sub
 
End Class

 

 



RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences