Wednesday, November 26, 2008

OpenSSL: License Key with RSA

In the last days I've played a bit with C libraries like OpenSSL and SQLite. The first post after Site downtime is dedicated to OpenSSL.
how do can you create your own license system for your application? With OpenSSL and less than 10 lines of code, you can do it. Take a look at the code below.



...
unsigned char checkDigest[SHA_DIGEST_LENGTH];
unsigned char shaDigest[SHA_DIGEST_LENGTH];
const char *userKey = "Matteo License";
unsigned char *signature = NULL;
unsigned int signatureLength = 0;

/* Generate Your RSA Key Pair */
RSA *rsa = RSA_generate_key(512, RSA_F4, NULL, NULL);

/* Generate SHA1 of User Key */
SHA1(userKey, strlen(userKey), shaDigest);

/* Create License Key for the User Key */
signature = OPENSSL_malloc(RSA_size(rsa));
signatureLength = RSA_private_encrypt(SHA_DIGEST_LENGTH, shaDigest,
signature, rsa, RSA_PKCS1_PADDING);

/* Check if User Signature is a valid License Key */
if (RSA_public_decrypt(signatureLength, signature, checkDigest,
rsa, RSA_PKCS1_PADDING) != SHA_DIGEST_LENGTH)
{
/* Valid License Key */
} else {
/* Invalid License Key */
}

free(signature);
RSA_free(rsa);
...

You need to store the RSA Public Key in your app and then give to each user a generated signature, and it's all.
Ok, this is a really base example (less than 10 lines of code) if you don't want reinvent a License Key system, take a look at AquaticPrime Framework (http://www.aquaticmac.com/).

No comments:

Post a Comment