DEV Community

Cover image for CryptoPals Crypto Challenges Using Rust: Implement PKCS#7 Padding
Naveen ⚑
Naveen ⚑

Posted on • Updated on

CryptoPals Crypto Challenges Using Rust: Implement PKCS#7 Padding

This is Challenge 9 of Cryptopals challenges implemented in Rust language.

Context πŸ’‘

We have to implement simple PKCS#7 padding.

PKCS#7 padding is utilized in encryptions to pad an input to make it's length multiple of specific block size and also store information of how much of padding bytes are there in the input itself.

So, to illustrate, if block size is 4, then PKCS#7 would apply following paddings:

Input         Padded Input     No. of padding bytes
----------------------------------------------------
y              y333                     3
yo             yo22                     2
yol            yol1                     1
yolo           yolo4444                 4

Enter fullscreen mode Exit fullscreen mode

After decryption, the last byte is read from output to know how much of padding bytes are there and that much number of bytes removed from end of the output to yield original unpadded message.

Code πŸ•Ά

The code is pretty much simple:

pub fn pad_pkcs7(message: &str, block_size: usize) -> String {
    let padding_size = block_size - message.len() % block_size;
    let padding_char = padding_size as u8 as char;
    let padding: String = (0..padding_size).map(|_| padding_char).collect();
    format!("{}{}", message, padding)
}
Enter fullscreen mode Exit fullscreen mode

That's it.

See code on Github

Find me on:
Twitter - @heyNvN

naveeen.com

Top comments (0)