DEV Community

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

Posted on • Edited on

3 2

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay