security: adds HMAC API and improves security several token-generating functions

Added a few commits to finish off #5368
Sure seems like it. Could we do that in a BC way?