-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpkcs7_padding.c
56 lines (53 loc) · 1.46 KB
/
pkcs7_padding.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "pkcs7_padding.h"
int pkcs7_padding_pad_buffer( uint8_t *buffer, size_t data_length, size_t buffer_size, uint8_t modulus ){
uint8_t pad_byte = modulus - ( data_length % modulus ) ;
if( data_length + pad_byte > buffer_size ){
return -pad_byte;
}
int i = 0;
while( i < pad_byte){
buffer[data_length+i] = pad_byte;
i++;
}
return pad_byte;
}
int pkcs7_padding_valid( uint8_t *buffer, size_t data_length, size_t buffer_size, uint8_t modulus ){
uint8_t expected_pad_byte = modulus - ( data_length % modulus ) ;
if( data_length + expected_pad_byte > buffer_size ){
return 0;
}
int i = 0;
while( i < expected_pad_byte ){
if( buffer[data_length + i] != expected_pad_byte){
return 0;
}
i++;
}
return 1;
}
size_t pkcs7_padding_data_length( uint8_t * buffer, size_t buffer_size, uint8_t modulus ){
/* test for valid buffer size */
if( buffer_size % modulus != 0 ||
buffer_size < modulus ){
return 0;
}
uint8_t padding_value;
padding_value = buffer[buffer_size-1];
/* test for valid padding value */
if( padding_value < 1 || padding_value > modulus ){
return buffer_size;
}
/* buffer must be at least padding_value + 1 in size */
if( (uint8_t)buffer_size < padding_value + 1 ){
return 0;
}
uint8_t count = 1;
buffer_size --;
for( ; count < padding_value ; count++){
buffer_size --;
if( buffer[buffer_size] != padding_value ){
return 0;
}
}
return buffer_size;
}