注意⚠️:本文中所提简单比特翻转加密算法,严格意义上来说不能视为加密算法,或者说只能算作是广义上的加密算法,而不能称之为现代加密算法。当然也不能够满足现代密码学所需要的加密算法安全性能要求。

事情是这样的,春节期间一位小伙伴发来消息说不太理解加密算法。于是我想用这样一个超级简单的程序来讲讲加密算法的大致过程。那么在我们日常生活中,通过软件对文件进行加密和解密应该算是最容易理解的过程吧。

encrypt-file-diagram

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 1024

void help_msg() {
    printf("Usage: bit-flipping-encrypt ${source_path} ${destination_path}");
}

int main(int argc, char *argv[]) {
    if (argc < 3) {
        help_msg();
        return -1;
    }

    /* Open the FILE. */
    char *source_path = argv[1];
    FILE *source_file = fopen(source_path, "rb");
    if (source_file == NULL) {
        printf("File is not accessible. [%s]\n", source_path);
        return -1;
    }

    char *dest_path = argv[2];
    FILE *dest_file = fopen(dest_path, "wb");
    if (dest_file == NULL) {
        printf("File is not accessible. [%s]\n", dest_path);
        return -1;
    }

    /* Core Fragment Code */
    unsigned char buffer[BUF_SIZE];
    size_t read_count;
    while ((read_count = fread(buffer, 1, BUF_SIZE, source_file)) > 0) {
        /* Bit Flipping Encrypt Algorithm, Simple and NAIVE. */
        for (size_t i = 0; i < read_count; i++) {
            buffer[i] ^= (unsigned char) 0xff;
        }
        fwrite(buffer, read_count, 1, dest_file);
    }

    fclose(source_file);
    fclose(dest_file);

    return 0;
}