简单的异或加密

本文介绍了一种利用C语言实现的加密与解密方法,通过输入输出重定向来处理文本文件,并使用特定密钥进行XOR操作加密与解密文本。该方法展示了如何在不依赖复杂加密库的情况下实现基本的数据保护功能。

利用一个简单的事实:

x ^ y ^ z 得到 a

那么 a ^ z ^ y 就可以得到 x,或者 a ^ y ^ z 也可以得到 x

加密:提供一个key.txt和input.txt,key.txt装你的密钥,比如:abc123,input.txt装原文(可以包含中文)

解密:key.txt内容仍然是密钥,或者key.txt的内容修改为321cba,input.txt装密文

最高支持密钥长度64位

利用了“输入输出重定向”

这个的缺点在于很可能你加密的密钥是abc123,你输入的密钥是aBc123、ABC123甚至vcx123也能解密,也就是说这货并不具备实用性。对于更多的内容请参考加密解密相关的书籍

main.c

#include <stdio.h>

#include "20/xor.h"

int main(int argc, char *argv[]) {
    _xor();
    return 0;
}

xor.h

#ifndef XOR_H
#define XOR_H

/**
    Using a series of characters to
    xor encrypt your text.
    key.txt is required by this program
    to supply key word.
    for example, if you use 'abc123' as
        the key word to encrypt your text,
        you'll need to use '321cba' to
        decrypt the text.
    You'll need to use input-redirect
    and output-redirect to make this
    work for your input file and output
    file.
    Maximum supports 64-character key.
*/
void _xor();


#endif // XOR_H

xor.c

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

#include "xor.h"

#define MAX_KEY_LEN 64

void _xor() {
    char key[MAX_KEY_LEN];
    FILE *fp;
    fp = fopen("key.txt", "r");
    if (fp == NULL) {
        printf("CANNOT OPEN key.txt\n");
        return;
    }
    // read key word
    char ch;
    while(isspace(ch = getc(fp))) // skip leading white-characters
            ;
    int j = 0;
    for (int i = 0; i < MAX_KEY_LEN && ch!=EOF; i++) {
        if (ch!='\n' && ch!='\r') {
            key[j++] = ch;
        }
        ch = getc(fp);
    }
    // encrypt/decrypt
    int orig_char, new_char;
    while ((orig_char = getchar())!=EOF) {
        for (int i = 0; i < j; i++) {
            new_char = orig_char ^ key[i];
        }
        putchar(new_char);
    }

}

run.bat

xor.exe <input.txt >out.txt
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值