Reputation: 96491
Is it possible to guarantee output to be of certain length regardless of the input?
For example, i'd like to pass in a String and guarantee that its' encrypted equivalent will contain 45 characters. Those 45 characters must be there regardless whether input is 1 character of Alice in Wonderland.
Note: 45 is obviously an example, the point is that number of output characters should be controlled in some way (exact number, or divisible by 5, or even)
Upvotes: 2
Views: 5307
Reputation: 37832
If you set your limit "high enough", yes, you can easily do what you want, using padding plus a stream-cipher.
For instance, take a look at the CTR (counter) mode of operation of block-ciphers: http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
Using AES-128 in CTR mode, if you use a random IV and insert it at the beginning of the cipher text, you know that the size of the cipher text will be exactly 16 bytes + size of the plain text. Therefore, if you fix your cipher-text length at 100 bytes for example, you could encrypt plain texts of up to 84 bytes. You'd have to pad shorter plain texts. For instance, if you are encrypting ASCII texts, you could use the byte 0x00 as a marker of the end of the string (just as the "null-terminated strings" from C), and then just pad with random garbage until you get 84 bytes.
There are many, many other common padding schemes you could use: http://en.wikipedia.org/wiki/Padding_(cryptography)
I just thought about another possibility: you could use some kind of authenticated encryption, such as Galois/Counter Mode (GCM). You concatenate the random IV with the cipher text, and this with random bytes to pad it to the desired size. Then, to decrypt, you just try every substring of the ciphertext: if you got the correct substring, the decryption algorithm will output the plain text; otherwise, it will output "error". Just be aware that, using this, you could introduce some timing attacks on your scheme, and you might also do lots and lots of computations to decrypt the cipher text if the plain texts vary a lot in size.
In any case, be sure to have your scheme reviewed by an expert on cryptography (for instance, after you devise your scheme, ask about it at https://crypto.stackexchange.com/), because it is very easy to overlook some attack possibilities.
Upvotes: 2
Reputation: 41252
No - it is not possible to specify a fixed result length. If the data is long enough, then it cannot be encrypted to a fixed short arbitrary length (that would be amazing compression). It would be possible to devise a hash
of that nature possibly. But a hash is different (it is one way; you cannot extract the original data from the hash).
It would be possible to control the length by using padding, though.
Upvotes: 3