One Time Pad in C

January 21, 2020

Get the size of the file you wish to encrypt:

du -b filename
Generate a key file:
head -c <size> /dev/urandom > filename_key
To encrypt:
./otp filename key output
To decrypt:
./otp output key filename
To compile:
gcc -Wall -g -std=gnu18 otp.c -o otp
// One Time Pad

#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

int main(int argc, char **argv) 
    FILE *input, *key, *output;

    struct stat input_info;
    struct stat key_info;

    if (argc == 4) {
        input = fopen(argv[1], "rb");
        key = fopen(argv[2], "rb");
        output = fopen(argv[3], "wb");
    else {
        printf("Enter 3 valid filenames: input, key, and output.\n");
        return EXIT_FAILURE;

    if (input == NULL || output == NULL || key == NULL) {
        printf("Error opening file.\n");
        return EXIT_FAILURE;

    fstat(fileno(input), &input_info);
    fstat(fileno(key), &key_info);

    if (key_info.st_size < input_info.st_size) {
        printf("Keyfile must be the same size or larger than source.\n");
        return EXIT_FAILURE;

    for (int i=0;;++i) {
        if (i >= input_info.st_size) break;
        fputc((fgetc(input) ^ fgetc(key)), output);

    return EXIT_SUCCESS;


©2013-2023 All Rights Reserved.