RingDotNetfor Ring

Protecting and signing messages

Encrypting a message is not enough: you must also be sure that nobody changed it. This lesson derives keys from a password, encrypts with AES, adds an HMAC (encrypt-then-MAC), detects tampering, and signs a message with an RSA key pair.

What you will learn#

This builds on the tutorial Hashing and encryption (hashes and basic encryption).

Two different problems#

ProblemToolKey
Nobody should read the messageencryption (AES)one secret key, shared by sender and receiver
Nobody should change it, and I want to know it is genuineHMAC (shared key) or a signature (RSA)HMAC: the same shared key. Signature: a private key signs, the public key verifies.

Use both for a protected message: encrypt first, then compute the HMAC over the encrypted bytes (encrypt-then-MAC). The receiver checks the HMAC first, so a forged or damaged package is refused before any decryption work happens.

The program#

samples/UsingDotNet/tutorials/ch08_crypto.ring
# protecting and signing messages - AES, HMAC (encrypt-then-MAC), a password-derived key and RSA signatures
load "dotnet.ring"

using {
	"System"
	"System.Text"
	"System.Security.Cryptography"
}

func main

	oRandom = new RandomNumberGenerator()

	# 1. A key from a password: PBKDF2 stretches it (many rounds, a random salt) into as many bytes as we ask for.
	#    64 bytes: the first 32 are the AES key, the last 32 the HMAC key (never use one key for two jobs).
	cSalt = oRandom.GetBytes(16)
	cKeys = deriveKeys("correct horse battery staple",cSalt)
	cEncryptionKey = left(cKeys,32)
	cMacKey = right(cKeys,32)
	? "1. keys derived from the password: " + len(cEncryptionKey) + " + " + len(cMacKey) + " bytes"

	# 2. Encrypt: a fresh random IV for every message, AES in CBC mode, then an HMAC over IV + ciphertext (encrypt-then-MAC)
	cMessage = "Transfer 100 to account 4521"
	cPackage = protect(cMessage,cEncryptionKey,cMacKey)
	? nl + "2. the message has " + len(cMessage) + " bytes, the protected package " + len(cPackage) + " bytes (16 IV + padded ciphertext + 32 tag)"
	? "   the plain text is not in the package: " + yesNo(substr(cPackage,"Transfer") = 0)

	# 3. Open it: check the tag FIRST; only a package that passes is decrypted
	aResult = unprotect(cPackage,cEncryptionKey,cMacKey)
	? nl + "3. opened: " + aResult[1] + " -> " + aResult[2]

	# 4. Tampering: change one byte of the package. The tag no longer fits and the package is refused, nothing is decrypted.
	cBad = left(cPackage,20) + char((ascii(cPackage[21]) + 1) % 256) + right(cPackage,len(cPackage) - 21)
	aBad = unprotect(cBad,cEncryptionKey,cMacKey)
	? nl + "4. one changed byte: " + aBad[1] + " (" + aBad[2] + ")"

	# 5. The same message twice gives different packages: the IV is random, so an observer cannot see that a message repeats
	? nl + "5. two protections of one message are equal: " + yesNo(protect(cMessage,cEncryptionKey,cMacKey) = cPackage)

	# 6. A digital signature: RSA. The PRIVATE key signs; the PUBLIC key (which anyone may have) verifies who wrote it and that it is unchanged.
	oSigner = new RSA().Create(2048)
	cPublicKey = oSigner.ToXmlString(False)                  # False: the public part only
	oHash = new HashAlgorithmName().SHA256
	oPadding = new RSASignaturePadding().Pkcs1
	cOrder = "Pay 100 to Ann"
	cSignature = oSigner.SignData([ :data = cOrder, :hashAlgorithm = oHash, :padding = oPadding ])
	oVerifier = new RSA().Create(NULL)
	oVerifier.FromXmlString(cPublicKey)
	? nl + "6. the signature has " + len(cSignature) + " bytes (a 2048-bit key)"
	? "   verified with the public key: " + yesNo(oVerifier.VerifyData([ :data = cOrder, :signature = cSignature, :hashAlgorithm = oHash, :padding = oPadding ]))
	? "   the order was changed to 'Pay 900 to Ann': " + yesNo(oVerifier.VerifyData([ :data = "Pay 900 to Ann", :signature = cSignature, :hashAlgorithm = oHash, :padding = oPadding ]))

# the keys of a password: PBKDF2 with SHA-256, 100000 rounds, nBytes long
func deriveKeys cPassword, cSalt

	oDerive = (new Rfc2898DeriveBytes).@New([ :password = cPassword, :salt = cSalt, :iterations = 100000, :hashAlgorithm = new HashAlgorithmName().SHA256 ])
	cKeys = oDerive.GetBytes(64)
	oDerive.Dispose()
	return cKeys

# IV + AES-CBC(message) + HMAC-SHA256(IV + ciphertext)
func protect cMessage, cEncryptionKey, cMacKey

	oAes = new Aes().Create(NULL)
	oAes.Key = cEncryptionKey
	cIv = new RandomNumberGenerator().GetBytes(16)
	oAes.IV = cIv
	oEncryptor = oAes.CreateEncryptor(NULL)
	cCipher = oEncryptor.TransformFinalBlock(cMessage,0,len(cMessage))
	oEncryptor.Dispose()
	oAes.Dispose()
	cBody = cIv + cCipher
	return cBody + tagOf(cBody,cMacKey)

# returns [status, text]: "ok" and the message, or "refused" and the reason
func unprotect cPackage, cEncryptionKey, cMacKey

	if len(cPackage) < 16 + 16 + 32
		return ["refused","too short"]
	ok
	cBody = left(cPackage,len(cPackage) - 32)
	cTag = right(cPackage,32)
	if not sameBytes(cTag,tagOf(cBody,cMacKey))
		return ["refused","the tag does not match: changed or wrong key"]
	ok
	oAes = new Aes().Create(NULL)
	oAes.Key = cEncryptionKey
	oAes.IV = left(cBody,16)
	oDecryptor = oAes.CreateDecryptor(NULL)
	cCipher = right(cBody,len(cBody) - 16)
	cPlain = oDecryptor.TransformFinalBlock(cCipher,0,len(cCipher))
	oDecryptor.Dispose()
	oAes.Dispose()
	return ["ok",cPlain]

func tagOf cBody, cMacKey

	oHmac = new HMACSHA256().@New([ :key = cMacKey ])
	cTag = oHmac.ComputeHash(cBody)
	oHmac.Dispose()
	return cTag

# compare without stopping at the first difference (the time must not tell how many bytes were equal)
func sameBytes cA, cB

	if len(cA) != len(cB)
		return False
	ok
	nDifference = 0
	for nIndex = 1 to len(cA)
		nDifference = nDifference | (ascii(cA[nIndex]) ^ ascii(cB[nIndex]))
	next
	return nDifference = 0

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. keys derived from the password: 32 + 32 bytes

2. the message has 28 bytes, the protected package 80 bytes (16 IV + padded ciphertext + 32 tag)
   the plain text is not in the package: yes

3. opened: ok -> Transfer 100 to account 4521

4. one changed byte: refused (the tag does not match: changed or wrong key)

5. two protections of one message are equal: no

6. the signature has 256 bytes (a 2048-bit key)
   verified with the public key: yes
   the order was changed to 'Pay 900 to Ann': no
Note

This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.

How it works#

Keys from a password#

A password is short and predictable; a key must be 32 random-looking bytes. Rfc2898DeriveBytes (PBKDF2) repeats a hash 100,000 times with a random salt and returns as many bytes as you ask for. 64 bytes are split in two: one key for encryption and a different one for the HMAC — never use one key for two jobs. The salt is not secret: store it next to the package. The constructor has several forms, so it is made with named arguments: dnNew("Rfc2898DeriveBytes",[ :password = ..., :salt = ..., :iterations = ..., :hashAlgorithm = ... ]).

Encrypting#

Aes (made with new Aes().Create(NULL)) needs a Key and an IV (initialization vector). The IV must be new and random for every message; it is not secret and is stored in front of the ciphertext. CreateEncryptor(NULL) gives the transformer and TransformFinalBlock(text, 0, len) encrypts a whole message. Byte arrays are plain Ring texts in this package, so the message goes in as it is and the ciphertext comes back as a text of bytes. AES works on blocks of 16 bytes, so the 28-byte message becomes 32 bytes.

The package is IV (16) + ciphertext (32) + tag (32) = 80 bytes. Protecting the same message twice gives different packages (step 5) because the IV differs, so an observer cannot even see that a message repeats.

The tag#

HMACSHA256 with the MAC key computes a 32-byte tag over IV + ciphertext. unprotect recomputes it and compares. In step 4 one byte of the package is changed and the package is refused — no decryption, no garbage. The comparison sameBytes does not stop at the first difference: a comparison that stops early takes a different time for different inputs, and that difference can leak the tag to an attacker (timing attack).

Warning

Never decrypt data before you have verified it. Padding errors and other messages of the decryptor can reveal information about the plaintext (padding oracle attacks). Modern code also uses an authenticated mode such as AES-GCM; this lesson shows the construction by hand because it is available in every .NET version and explains why the tag exists.

Signatures#

RSA uses a pair of keys. new RSA().Create(2048) makes the pair; ToXmlString(False) exports the public half as text, which you may give to anyone. SignData(data, hashAlgorithm, padding) hashes the data with SHA-256 and signs the hash with the private key (256 bytes for a 2048-bit key). Anyone with the public key can VerifyData — and a change in the message, even 100 to 900, makes the check fail (step 6). The private key never leaves the signer.

The algorithm and the padding are objects: new HashAlgorithmName().SHA256, new RSASignaturePadding().Pkcs1.

Note

Aes.Create, CreateEncryptor and the like have an overload with a name or key, so the form without arguments is written with NULL. A transform is released with oEncryptor.Dispose().

What this program is not#

It is a teaching construction. For real systems use a well-reviewed protocol (TLS for networks, the platform's data-protection APIs for files), keep keys out of source code, and have security-sensitive code reviewed by someone who knows the field.

What you learned#

Exercises#

  1. Put the salt in front of the package so that it can be opened with only the password.
  2. Save the public key XML in a file and verify a signature in a second program.
  3. Sign a file's SHA-256 hash instead of the whole file with SignHash.
  4. Time deriveKeys and change the number of rounds; how many are comfortable for your computer?

Next#

Digital signatures

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.