License Manager

Apex6554 60 Reputation points
2023-05-06T11:06:36.0466667+00:00

This code is a license manager that allows a user to activate a license key for a software product. The user can select an activation request file, which contains their username and password. The code will then generate a license key using the provided username and password, and write the license key and expiry date to a license file. Finally, the code will attempt to activate the license using the generated license key and expiry date, by checking if the license key is valid and not expired. If the activation is successful, the code will display a message indicating that the license has been activated. Otherwise, it will display a message indicating that the activation failed. However I'm not getting any errors in my code when I click Activate button on my program all I get is a error message saying Failed to activate license. here is the code.. If you can help fix the problem I'm having i'll be s thankful!

namespace License_Manager
{

    public partial class LicenseManager : Form
    {
        private string CalculateMD5Hash(string input)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] inputBytes = Encoding.ASCII.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }


        public LicenseManager()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Activation Request Files|Activation.req";
            openFileDialog.Title = "Select Activation Request File";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog.FileName;
                string[] fileContent = System.IO.File.ReadAllLines(fileName);
                if (fileContent.Length >= 2)
                {
                    txtUsername.Text = fileContent[0];
                    txtPassword.Text = fileContent[1];
                }
                else
                {
                    MessageBox.Show("Invalid activation request file.");
                }
            }
        }

        private void btnActivate_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();
            string licenseFilePath = "License.key";

            // Check if the License.key file exists, and create it if it doesn't
            if (!File.Exists(licenseFilePath))
            {
                FileStream fileStream = File.Create(licenseFilePath);
                fileStream.Close();
            }

            // Generate the license key and expiry date
            string licenseKey = GenerateLicenseKey(username, password);
            DateTime expiryDate = DateTime.Today.AddDays(30);

            // Write the license key and expiry date to the License.key file
            string licenseData = string.Format("{0},{1}", licenseKey, expiryDate.ToString("yyyy-MM-dd"));
            File.WriteAllText(licenseFilePath, licenseData);

            // Activate the license
            if (ActivateLicense(licenseKey, expiryDate))
            {
                MessageBox.Show("License activated successfully.");
            }
            else
            {
                MessageBox.Show("Failed to activate the license.");
            }
        }

        private string GenerateLicenseKey(string username, string password)
        {
            string input = username + password;
            string hash = ComputeHash(input);
            string licenseKey = string.Format("{0}-{1}-{2}-{3}", hash.Substring(0, 5), hash.Substring(5, 5), hash.Substring(10, 5), hash.Substring(15, 5));
            return licenseKey;
        }

        private string ComputeHash(string input)
        {
            using (SHA256 sha256Hash = SHA256.Create())
            {
                byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }

        private bool ActivateLicense(string licenseKey, DateTime expiryDate)
        {
            // Check if the license key is valid and not expired
            string validLicenseKeyHash = "7E9D9CBA95CC6E842D6ECA7BC09E8A3B"; // replace with your own hash value or read it from a file
            string licenseData = File.ReadAllText("License.key");
            string[] licenseParts = licenseData.Split(',');
            string licenseKeyHash = ComputeHash(licenseParts[0]);
            DateTime licenseExpiryDate;
            if (DateTime.TryParseExact(licenseParts[1], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out licenseExpiryDate))
            {
                if (licenseKeyHash == validLicenseKeyHash && expiryDate <= licenseExpiryDate)
                {
                    // License key is valid and not expired
                    // Add your license activation code here (e.g. enable premium features or remove trial restrictions)
                    return true;
                }
            }
            // License key is invalid or expired
            return false;
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,650 questions
{count} votes