Protecting data
Many programs hand a small piece of data to the outside and take it back later: a cookie, a "remember me" value, a link in an e-mail. The Data Protection API encrypts and signs such data for you, without keys to manage. This lesson protects and unprotects text, shows purposes, tampering and key folders, and makes tokens that expire.
What you will learn#
- what the Data Protection API does and when to use it,
ProtectandUnprotect,- purposes: tokens for one use cannot be used for another,
- why a changed token is refused,
- keys in a folder, and what happens with other keys,
- time-limited tokens.
The tutorial Hashing and encryption and the tutorial Protecting and signing messages used the cryptography classes directly: you choose the algorithm, the key and the mode, and every choice is a chance for a mistake. The Data Protection API is the high-level tool: you give it a text, it gives you a token.
The API is part of the ASP.NET Core runtime, so the program has "RingDotNet.Web" in its using { } (Getting started).
The program#
# protecting data - the Data Protection API: purposes, tampering, keys on disk, and values that expire
load "dotnet.ring"
using {
"Microsoft.AspNetCore.DataProtection"
"System"
"System.Threading"
"System.IO"
"RingDotNet.Web" # the Data Protection API is part of the ASP.NET Core runtime: this line starts it
}
func main
# The Data Protection API encrypts and signs small pieces of data (a cookie, a token, a "remember me" value, a link in an e-mail)
# without you handling keys, algorithms or initialization vectors. It makes keys, keeps them in a folder, renews them,
# and encrypts with AES and signs with HMAC. ASP.NET Core uses it for its cookies and tokens.
cKeys = new Path().Combine([new Path().GetTempPath(),"ringdotnet_protection_keys"])
if new Directory().Exists(cKeys)
new Directory().Delete([ :path = cKeys, :recursive = True ])
ok
new Directory().CreateDirectory(cKeys)
oProvider = (new DataProtectionProvider).Create(new DirectoryInfo(cKeys))
# 1. A protector is made for a PURPOSE (a text that names what the data is for). Protect turns a text into an unreadable token
# and Unprotect gives the text back.
oProtector = oProvider.CreateProtector("tutorial.cookies")
cToken = (new DataProtectionCommonExtensions).Protect(oProtector,"user=ann;role=admin")
? "1. the protected text starts with CfDJ8 (every token of this API does): " + (left(cToken,5) = "CfDJ8")
? " it does not show the data: " + (substr(cToken,"ann") = 0) + ", and it is longer than the data: " + (len(cToken) > 40)
? " Unprotect gives back: " + (new DataProtectionCommonExtensions).Unprotect(oProtector,cToken)
# 2. The same data protected twice gives different tokens (a random value is part of each one), but both unprotect to the same text
cToken2 = (new DataProtectionCommonExtensions).Protect(oProtector,"user=ann;role=admin")
? nl + "2. two tokens of the same text are different: " + (cToken != cToken2) + "; the second also gives: " + (new DataProtectionCommonExtensions).Unprotect(oProtector,cToken2)
# 3. Purposes keep uses apart: a token made for "tutorial.cookies" cannot be opened with the protector of "tutorial.password-reset".
# So a stolen cookie value does not work as a reset link, even though the same keys are used.
oOther = oProvider.CreateProtector("tutorial.password-reset")
? nl + "3. unprotect with another purpose: " + tryUnprotect(oOther,cToken)
# 4. Tampering: change one character of the token and the check fails. The data can not be modified, only replaced by a valid token.
cTampered = left(cToken,20) + changeChar(substr(cToken,21,1)) + substr(cToken,22)
? nl + "4. unprotect a token with one changed character: " + tryUnprotect(oProtector,cTampered)
# 5. The keys are on disk, so a NEW provider on the same folder opens the old tokens (after a restart of the program, or in another
# copy of it). Without the key folder the tokens can not be opened: it is as secret as a password.
aFiles = new Directory().GetFiles(cKeys)
oProvider2 = (new DataProtectionProvider).Create(new DirectoryInfo(cKeys))
oProtector2 = oProvider2.CreateProtector("tutorial.cookies")
? nl + "5. key files in the folder: " + len(aFiles.toList()) + ", a second provider on the same folder opens the token: " + (new DataProtectionCommonExtensions).Unprotect(oProtector2,cToken)
cOtherFolder = cKeys + "_other"
new Directory().CreateDirectory(cOtherFolder)
oStranger = (new DataProtectionProvider).Create(new DirectoryInfo(cOtherFolder)).CreateProtector("tutorial.cookies")
? " a provider with other keys: " + tryUnprotect(oStranger,cToken)
# 6. Time limits: a token that is valid for a short time only (a link in an e-mail, a one-time code)
oLimited = oProtector.ToTimeLimitedDataProtector()
cShort = (new DataProtectionAdvancedExtensions).Protect(oLimited,"reset:42",new TimeSpan().FromMilliseconds(1200))
? nl + "6. a token that is valid for 1.2 seconds: now " + tryUnprotectLimited(oLimited,cShort)
new Thread().Sleep(2000)
? " after 2 seconds: " + tryUnprotectLimited(oLimited,cShort)
new Directory().Delete([ :path = cKeys, :recursive = True ])
new Directory().Delete([ :path = cOtherFolder, :recursive = True ])
func tryUnprotect oProtector,cToken
try
return "valid, it gives '" + (new DataProtectionCommonExtensions).Unprotect(oProtector,cToken) + "'"
catch
return "refused (a cryptographic error)"
done
func changeChar cChar
if cChar = "A"
return "B"
ok
return "A"
# the time-limited protector also gives the time when the token expires (an out value: the answer is a list)
func tryUnprotectLimited oLimited,cToken
try
aResult = (new DataProtectionAdvancedExtensions).Unprotect(oLimited,cToken)
if islist(aResult)
return "valid, it gives '" + aResult[1] + "'"
ok
return "valid, it gives '" + aResult + "'"
catch
return "refused (it expired or it is not valid)"
done1. the protected text starts with CfDJ8 (every token of this API does): 1
it does not show the data: 1, and it is longer than the data: 1
Unprotect gives back: user=ann;role=admin
2. two tokens of the same text are different: 1; the second also gives: user=ann;role=admin
3. unprotect with another purpose: refused (a cryptographic error)
4. unprotect a token with one changed character: refused (a cryptographic error)
5. key files in the folder: 1, a second provider on the same folder opens the token: user=ann;role=admin
a provider with other keys: refused (a cryptographic error)
6. a token that is valid for 1.2 seconds: now valid, it gives 'reset:42'
after 2 seconds: refused (it expired or it is not valid)This program uses a few generic functions (dnStatic, callMethod) where a class cannot be used. The lesson The generic functions explains them.
How it works#
A provider and a protector#
DataProtectionProvider.Create(folder) makes a provider whose keys are kept in the folder as files (it makes the first key itself and renews keys before they expire). CreateProtector("purpose") makes a protector for a purpose. Protect(text) returns a token: encrypted with AES and signed, so nobody can read it and nobody can change it. Unprotect(token) returns the text. Protect and Unprotect for texts are extension methods, so they are called with dnStatic("...DataProtectionCommonExtensions","Protect",[protector,text]) (the tutorial Caching); CreateProtector is a method of the provider object.
Every token of this API starts with CfDJ8, the Base64 text of a fixed header, and it does not show the data. A random value is part of each token, so protecting the same text twice gives two different tokens that both open to the same text.
Purposes#
A purpose is a text that names what the token is for ("tutorial.cookies", "tutorial.password-reset"). A token made for one purpose cannot be opened by the protector of another purpose, even with the same keys. So a user who copies a cookie value into a reset link gets an error. Use a different purpose for every kind of token in your program, written like a namespace (company.app.feature).
Tampering#
Changing one character of a token makes Unprotect raise a cryptographic error (the signature does not fit). The program catches it with try and prints refused. You cannot make a different valid token without the key, so a token can carry data that the user must not change, for example the user id in a cookie. Remember what this does not protect against: a token can be copied and used again by someone who has it (a replay), so tokens that open a door (a reset link) should expire and be used once.
Keys#
The key folder is the secret. A second provider on the same folder opens the old tokens (after a restart, or from another copy of the program that shares the folder); a provider with other keys refuses them (step 5). That is what you want: protect the folder like a password, back it up, and share it between the servers that must open each other's tokens. In a real program choose a folder outside the project, with strict rights, and never put it in version control. Keys are renewed every 90 days by default and old keys stay available for opening old tokens.
Time-limited tokens#
ToTimeLimitedDataProtector makes a protector whose Protect(text, lifetime) adds an expiration time inside the token. Before the time the token opens; after it, Unprotect raises an error. Use it for password-reset links, e-mail confirmations and one-time codes. The check happens inside the token, so the server does not need to keep a list. These methods are in the DataProtectionAdvancedExtensions class.
This API is for data that you give out and take back. It is not a way to store passwords (use a slow password hash, the tutorial Login, sessions and cookies) and not a replacement for the encryption of a database.
What you learned#
ProtectandUnprotectencrypt and sign small values,- a purpose keeps uses apart,
- a changed token is refused,
- the key folder is the secret and can be shared,
- time-limited tokens expire by themselves.
Exercises#
- Make a "remember me" cookie: protect the user id and the time, and write a function that reads it back or answers not valid.
- Make a password-reset link that is valid for 15 minutes (the tutorial A chat over TCP shows a small server to send it from).
- Look at the key file in the folder: it is XML. Which parts are readable and which are not?
- Protect a long text (10 000 characters) and look at the size of the token.