1
0
This commit is contained in:
2025-06-20 11:23:21 +08:00
commit b5601aef8c
47 changed files with 1829 additions and 0 deletions

6
problems/p9/Cargo.toml Normal file
View File

@@ -0,0 +1,6 @@
[package]
name = "p9"
version = "0.1.0"
edition = "2024"
[dependencies]

79
problems/p9/src/main.rs Normal file
View File

@@ -0,0 +1,79 @@
fn pkcs7_padding(data: &mut Vec<u8>, block_size: usize) {
if block_size == 0 {
panic!("Block size must be greater than zero");
}
if block_size > 255 {
panic!("Block size must be less than or equal to 255");
}
let mut padding_length = block_size - (data.len() % block_size);
if padding_length == 0 {
padding_length = block_size;
}
data.extend(vec![padding_length as u8; padding_length]);
}
fn main() {
let mut plain_text = b"YELLOW SUBMARINE".to_vec();
pkcs7_padding(&mut plain_text, 20);
println!("Padded text: {:?}", plain_text);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normal_padding() {
let mut data = b"YELLOW SUBMARINE".to_vec(); // 16 bytes
pkcs7_padding(&mut data, 20);
assert_eq!(data.len(), 20);
assert_eq!(&data[16..], &[4, 4, 4, 4]);
}
#[test]
fn test_full_block_padding() {
let mut data = b"YELLOW".to_vec(); // 6 bytes
pkcs7_padding(&mut data, 6);
assert_eq!(data.len(), 12);
assert_eq!(&data[6..], &[6, 6, 6, 6, 6, 6]);
}
#[test]
fn test_single_byte_padding() {
let mut data = b"YELLOW SUBMARIN".to_vec(); // 15 bytes
pkcs7_padding(&mut data, 16);
assert_eq!(data.len(), 16);
assert_eq!(data[15], 1);
}
#[test]
fn test_empty_data() {
let mut data = Vec::new();
pkcs7_padding(&mut data, 8);
assert_eq!(data.len(), 8);
assert_eq!(data, vec![8; 8]);
}
#[test]
#[should_panic(expected = "Block size must be greater than zero")]
fn test_zero_block_size() {
let mut data = b"test".to_vec();
pkcs7_padding(&mut data, 0);
}
#[test]
#[should_panic(expected = "Block size must be less than or equal to 255")]
fn test_oversized_block() {
let mut data = b"test".to_vec();
pkcs7_padding(&mut data, 256);
}
#[test]
fn test_boundary_block_size() {
let mut data = b"A".to_vec();
pkcs7_padding(&mut data, 255);
assert_eq!(data.len(), 255);
assert_eq!(&data[1..], vec![254; 254]);
}
}