I need an algorithm that can take an integer, an arbitrary range, a key of 16/24/32 bytes, and an initialization vector of 16 bytes(ideally), and return an integer in the same range.
My latest attempt at this repeatedly encrypts an integer with AES_OFB until it is in the requested range. I'm using a stream cipher so that the ciphertext can be truncated without ruining the whole thing. The issue is that the decryption process sometimes halts too early.
data = 0x7234 range = 0x1000 to 0xa000 inclusive data = aes_ofb_encrypt(data) // keystream "0x8d7c", data == 0xff48 0xff48 is not in the range, try again data = aes_ofb_encrypt(data) // keystream "0xe5b7", data == 0x1aff 0x1aff is in the range return data // 0x1aff decrypting: data = 0x1aff range = 0x1000 to 0xa000 inclusive data = aes_ofb_decrypt(data) // keystream "0x8d7c", data = 0x9783 0x9783 is in the range // halting too early!! return 0x9783 // this isn't the right value!
Is there a better way to encrypt integers of an arbitrary range? Ideally I want it to be as strong as the AES algorithm. This example is obviously vulnerable to a brute force attack, but for cases where the integers are of or exceed 128 bits of length, I want the strength of the AES algorithm. Is this possible?