Padding
Most modern cryptographic constructions disclose message lengths. The ciphertext for a given message will always have the same length or a constant number of bytes added to it.
For most applications, this is not an issue. But in some specific situations, such as interactive remote shells, hiding the length may be desirable. Padding can be used for that purpose.
This API was introduced in libsodium 1.0.14.
Example
Usage
The sodium_pad()
function adds padding data to a buffer buf
whose original size is unpadded_buflen
in order to extend its total length to a multiple of blocksize
.
The new length is put into padded_buflen_p
.
The function returns -1
if the padded buffer length would exceed max_buflen
, or if the block size is 0
. It returns 0
on success.
The sodium_unpad()
function computes the original, unpadded length of a message previously padded using sodium_pad()
. The original length is put into unpadded_buflen_p
.
Algorithm
These functions use the ISO/IEC 7816-4 padding algorithm. It supports arbitrary block sizes, ensures that the padding data are checked for computing the unpadded length, and is more resistant to some classes of attacks than other standard padding algorithms.
Notes
Padding should be applied before encryption and removed after decryption.
Usage of padding to hide the length of a password is not recommended. A client willing to send a password to a server should hash it instead, even with a single iteration of the hash function.
This ensures that the length of the transmitted data is constant and that the server doesn’t effortlessly get a copy of the password.
Applications may eventually leak the unpadded length via side channels, but the sodium_pad()
and sodium_unpad()
functions themselves try to minimize side channels for a given length & <block size mask>
value.
Last updated