4.12. Encrypting in a Single Reduced Character Set
Problem
You’re storing data in a format in which particular characters are invalid. For example, you might be using a database, and you’d like to encrypt all the fields, but the database does not support binary strings. You want to avoid growing the message itself (sometimes database fields have length limits) and thus want to avoid encoding binary data into a representation like base64.
Solution
Encrypt the data using a stream cipher (or a block cipher in a streaming mode). Do so in such a way that you map each byte of output to a byte in the valid character set.
For example, let’s say that your character set is the 64 characters consisting of all uppercase and lowercase letters, the 10 numerical digits, the space, and the period. For each character, do the following:
Map the input character to a number from 0 to 63.
Take a byte of output from the stream cipher and reduce it modulo 64.
Add the random byte and the character, reducing the result modulo 64.
The result will be a value from 0 to 63. Map it back into the desired character set.
Decryption is done with exactly the same process.
See Recipe 5.2 for a discussion of picking a streaming cipher solution. Generally, we recommend using AES in CTR mode or the SNOW 2.0 stream cipher.
Discussion
If your character set is an 8-bit quantity per character (e.g., some subset of ASCII instead of Unicode or something like that), the following code will work:
typedef struct { unsigned char *cset; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access