-
Notifications
You must be signed in to change notification settings - Fork 0
/
padding.c
58 lines (42 loc) · 1.6 KB
/
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
57
58
// Padding for SHA256
#include <stdio.h> // I/O Stuff
#include <inttypes.h> // Also includes formatters for printf
union block {
uint64_t sixfour[8];
uint32_t threetwo[16];
uint8_t eight[64];
};
uint64_t nozerobytes(uint64_t nobits) {
uint64_t result = 512ULL - (nobits % 512ULL); // How many bits did you have?
if (result < 65) { // If it's less than 65.. (65 => Num of bits thats definitely needed to pad)
result += 512; // Add an extra block, full of 0's
}
result -= 72; // Take those 72 bits away from res
return (result / 8ULL); // Divide res by 8 to get the num of bytes to add on
}
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Error: expected single filename as argument. \n");
return 1;
}
FILE *infile = fopen(argv[1], "rb");
if (!infile) {
printf("Error: couldn't open file %s. \n", argv[1]);
}
uint8_t b;
// Instead of reading every byte on the fly
union block M;
uint64_t nobits; // 64 bits limitation for SHA
uint8_t i;
for (nobits = 0, i = 0;fread(&M.eight[i], 1, 1, infile) == 1; nobits += 8) { // & => Sends the address of b, fread can use to override whats stored at b
printf("%02" PRIx8, M.eight[i]); // PRIx8 correct format specifier for an unsigned 8 bit int
}
printf("%02" PRIx8 , 0x80); // Bits: 1000 0000
// How much padding in terms of 0 bits are needed to add on?
for (uint64_t i = nozerobytes(nobits); i > 0; i--) {
printf("%02" PRIx8, 0x00);
}
printf("%016" PRIx64 " \n", nobits);
fclose(infile);
return 0;
}