Cleaned up key generation code