Fixed leaks in key generation and other cleanups. Patch by Tomas Mraz.