Improved create_key function