security: Fixing memory leaks and properly handling non-existing keys

Change-Id: I9145b009d9d9d5e7862a26d0be8c3b7085a42c4b
Refs: #1562, #1563