REFACTORED: key generation