Made key-gen algorithm better