C++ – What encryption scheme meets requirement of decimal plaintext & ciphertext and preserves length

aesccryptographyencryption

I need an encryption scheme where the plaintext and ciphertext are composed entirely of decimal digits.

In addition, the plaintext and ciphertext must be the same length.

Also the underlying encryption algorithm should be an industry-standard.
I don't mind if its symmetric (e.g AES) or asymmetric (e.g RSA) – but it must be a recognized algorithm for which I can get a FIPS-140 approved library. (Otherwise it won't get past the security review stage).

Using AES OFB is fine for preserving the length of hex-based input (i.e. where each byte has 256 possible values: 0x00 –> 0xFF). However, this will not work for my means as plaintext and ciphertext must be entirely decimal.

NB: "Entirely decimal" may be interpreted two ways – both of which are acceptable for my requirements:

  1. Input & output bytes are characters '0' –> '9' (i.e. byte values: 0x30 -> 0x39)
  2. Input & output bytes have the 100 (decimal) values: 0x00 –> 0x99 (i.e. BCD)

Some more info:
The max plaintext & ciphertext length is likely to be 10 decimal digits.
(I.e. 10 bytes if using '0'–>'9' or 5 bytes if using BCD)

Consider following sample to see why AES fails:
Input string is 8 digit number.
Max 8-digit number is: 99999999
In hex this is: 0x5f5e0ff

This could be treated as 4 bytes: <0x05><0xf5><0xe0><0xff>

If I use AES OFB, I will get 4 byte output.

Highest possible 4-byte ciphertext output is <0xFF><0xFF><0xFF><0xFF>

Converting this back to an integer gives: 4294967295
I.e. a 10-digit number.

==> Two digits too long.

One last thing – there is no limit on the length any keys / IVs required.

Best Answer

Use AES/OFB, or any other stream cipher. It will generate a keystream of pseudorandom bits. Normally, you would XOR these bits with the plaintext. Instead:

For every decimal digit in the plaintext
  Repeat
    Take 4 bits from the keystream
  Until the bits form a number less than 10
  Add this number to the plaintext digit, modulo 10

To decrypt, do the same but subtract instead in the last step.

I believe this should be as secure as using the stream cipher normally. If a sequence of numbers 0-15 is indistinguishable from random, the subsequence of only those of the numbers that are smaller than 10 should still be random. Using add/subtract instead of XOR should still produce random output if one of the inputs are random.

Related Topic