Better error handling in cert generation

Now it should correctly free all resources in case
of failure.