# Tokens tied to a browser with ENCRYPTREQ() and DECRYPTREQ()

> Encrypt a value together with the user agent (and optionally the IP address) of the request, and read it back only from the same client.

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 8cdff67bb59806a632b3b63151bc64dc8416ae5d8892adb0e9296bb52e288e0a
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`ENCRYPTREQ($, value, key, [strict])` encrypts a value **together with the user agent of the request** and returns a text token. `DECRYPTREQ($, token, key)` reads the value back, and returns nothing (`undefined`) when the key is wrong, the token is empty, or the request comes from a different client. With `strict` set to `true` the IP address of the request is part of the token too, so it also stops working when the address changes.

Use it for values that you hand to the browser and expect back from the same browser: a short-lived link, a download address, a form token. It is not a replacement for a session: the user agent is easy to copy. For tokens that do not depend on the request see the encrypt and decrypt recipe.

```js controllers/tokens.js
exports.install = function() {
	ROUTE('GET /issue/', issue);
	ROUTE('GET /read/', read);
	ROUTE('GET /read-wrong-key/', wrongkey);
};

function issue($) {
	$.json({ token: ENCRYPTREQ($, { id: 5 }, 'my-secret'), strict: ENCRYPTREQ($, 'only-here', 'my-secret', true) });
}

function read($) {
	$.json({ value: DECRYPTREQ($, $.query.token, 'my-secret') || null });
}

function wrongkey($) {
	$.json({ value: DECRYPTREQ($, $.query.token, 'another-secret') || null });
}
```
