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

Added a few commits to finish off #5368

- [ ] Rebase to catch up with major refactoring effort.