Fix race condition on writing public keys

Solving an issue reported by Nil Valls.