# Encrypt and decrypt data with a key

> Turn objects into opaque tokens with ENCRYPT() and read them back with DECRYPT(), for signed links and short-lived tokens.

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

`ENCRYPT(value, key)` serializes a value to JSON and returns an opaque text. `DECRYPT(text, key)` returns the original value, or `null` when the text was changed, is not valid, or was encrypted with another key. The `secret` setting of your config is mixed into the key, so tokens made on one installation do not open on another.

Use it for password reset links, invitation tokens and anything you need to hand to a client and verify later without storing it. Put an expiration inside the value (a timestamp) and check it after decrypting.

```text config
secret : change-this-secret-in-production
```

```js controllers/tokens.js
exports.install = function() {
	ROUTE('GET /token/', create);
	ROUTE('GET /verify/', verify);
};

function create($) {
	var token = ENCRYPT({ userid: '123', expire: Date.now() + 60000 }, 'reset-password');
	$.json({ token: token });
}

function verify($) {

	var data = DECRYPT($.query.token || '', 'reset-password');

	if (!data || data.expire < Date.now()) {
		$.invalid(401);
		return;
	}

	$.json({ userid: data.userid });
}
```
