CLEANUP KeyGen: refactor duplicate code.