Create a license key and verify it in app using RSACryptoServiceProvider

232 views Asked by At

For a new .net server application, I'm creating a small POC (Prof of concept) for a simple license key generator and verification of the license key. My concept is that by installing the server application I use a simple .net app (Winform) to generate a ComputerId based on some hardware properties. This ComputerId we will then use this to create a license key. In the Winform app, we enter the license key and verify that it is generated on this server.

I created a console app where I first create a RSA Private and Public key.

private static (string privateKeyParameters, string publicKeyParameters) GenerateKeyPair(int keySize)
{
    string PrivateRsaKey;
    string PublicRsaKey;

    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.KeySize = keySize;

        PrivateRsaKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey());
        PublicRsaKey = Convert.ToBase64String(rsa.ExportRSAPublicKey());
    }

    return (PrivateRsaKey, PublicRsaKey);
}

Using the private key I then generate and sign the license key.

private static string CreateLicense(string computerId)
{
    byte[] SignedLicense;
    byte[] UnsignedComputerId = Encoding.UTF8.GetBytes(computerId);
    int i = 0;
    var rsaKeys = GenerateKeyPair(2048);
    string license;

    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportRSAPrivateKey(Convert.FromBase64String(rsaKeys.privateKeyParameters), out i);

        SignedLicense = rsa.SignData(UnsignedComputerId, "SHA1");
        license = Convert.ToBase64String(SignedLicense);
    }

    return license;
}

And at last I verify the license key

private static bool VerifyLicense(string license)
{
    int i;
    byte[] UnsignedComputerId = Encoding.UTF8.GetBytes(computerId);
    byte[] SignedLicense = Convert.FromBase64String(license);
    bool VerifOK = false;
    var rsaKeys = GenerateKeyPair(2048);

    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportRSAPublicKey(Convert.FromBase64String(rsaKeys.publicKeyParameters), out i);
        VerifOK = rsa.VerifyData(UnsignedComputerId, "SHA1", SignedLicense);
    }

        return VerifOK;
}
static void Main(string[] args)
{
    var (privateKeyParameters, publicKeyParameters) = GenerateKeyPair(1024);
    var license = CreateLicense(computerId);

    Console.WriteLine("Privatekey: " + privateKeyParameters);
    Console.WriteLine();
    Console.WriteLine("Publickey: " + publicKeyParameters);

    Console.WriteLine();
    Console.WriteLine("License: " + license);

    Console.WriteLine();
    Console.WriteLine("License is verified: " + VerifyLicense(license));

    Console.ReadLine();
}

Then in the Main method call these methods, but I always get False by verifying the license key.

What am I doing wrong here?

0

There are 0 answers