For our native code, we’re going to create an implementation of the Caesar cipher.[27] This isn’t something you would use for real encryption, but if you think about the implications of bugs in native crypto implementations, the impact is pretty huge.
Let’s start with our legacy code:
| caesar.c |
| #include <stdlib.h> |
| #include <string.h> |
| #include <ctype.h> |
| |
| char *caesar(int shift, char *input) |
| { |
| char *output = malloc(strlen(input)); |
| memset(output, '\0', strlen(input)); |
| |
| for (int x = 0; x < strlen(input); x++) { |
| if (isalpha(input[x])) { |
| int c = toupper(input[x]); |
| c = (((c - 65) + shift) % 26) + 65; |
| output[x] = c; |
| } else { |
| output[x] = input[x]; |
| } |
| } |
| |
| return output; |
| } |
Like all substitution ciphers, this function accepts a number in which to shift each character. We’ll be using the English alphabet, so our shift will be between 1 and 25.
This code has some bugs. They may or may not be obvious, but there’s a good chance a simple unit test wouldn’t expose them.