XOR加密算法,也称为异或加密算法,是一种简单的对称加密算法。它的原理基于XOR(异或)运算,这是一种二进制运算,其规则是:当两个输入位相同时,输出为0;当两个输入位不同时,输出为1。
在XOR加密中,明文和密钥(也是一个二进制数)进行异或运算,得到密文。解密过程则是将密文和相同的密钥再次进行异或运算,从而还原出原始的明文。由于XOR运算的特性,任何数和0做XOR运算结果仍然是原来的数,而任何数和其自身做XOR运算结果都是0。这意味着,只要使用正确的密钥,就能轻松地解密出明文。
XOR加密算法的优点在于其操作简单,只需要进行异或运算即可。然而,由于它的加密方式相对简单,对于需要高度保密的信息来说,可能不是一种安全的加密算法。因此,在实际应用中,XOR加密算法通常只用于一些简单的加密需求,如隐藏一些不太敏感的信息等。
以下是c语言实现xor的例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <Windows.h>
#define MAXINPUT 170
#define KEY_SIZE 16
void xor_encrypt_decrypt(char *data, int data_size, char *key)
{
int i;
for (i = 0; i < data_size; ++i)
{
data[i] ^= key[i % KEY_SIZE];
}
}
int main(int argc, char *argv[])
{
printf("欢迎使用\n");
printf("请输入需要加密的文件的路径\n");
char file_path[MAXINPUT];
if (!fgets(file_path, MAXINPUT, stdin))
{
printf("ERROR: 读取文件路径失败\n");
return 1;
}
file_path[strcspn(file_path, "\n")] = 0; // 去除换行符
FILE *fp = fopen(file_path, "rb");
if (fp == NULL)
{
printf("ERROR: 打开文件出错\n");
return 1;
}
fseek(fp, 0L, SEEK_END);
long file_size = ftell(fp);
rewind(fp);
char *file_content = (char *)malloc(file_size);
if (file_content == NULL)
{
printf("ERROR: 内存分配失败\n");
fclose(fp);
return 1;
}
size_t bytesRead = fread(file_content, 1, file_size, fp);
if (bytesRead != file_size)
{
printf("ERROR: 读取文件内容出错\n");
free(file_content);
fclose(fp);
return 1;
}
char key[KEY_SIZE] = "MySecretKey";
xor_encrypt_decrypt(file_content, bytesRead, key);
char encrypted_file_path[MAXINPUT];
snprintf(encrypted_file_path, sizeof(encrypted_file_path), "%s.encrypted", file_path);
int fd = open(encrypted_file_path, O_WRONLY | O_CREAT | O_TRUNC);
if (fd == -1)
{
perror("ERROR: 创建文件失败");
free(file_content);
fclose(fp);
return 1;
}
ssize_t bytesWritten = write(fd, file_content, bytesRead);
if (bytesWritten != bytesRead)
{
printf("ERROR: 写入加密数据到文件失败\n");
close(fd);
free(file_content);
fclose(fp);
return 1;
}
close(fd);
free(file_content);
fclose(fp);
printf("加密后的文件已保存为: %s\n", encrypted_file_path);
return 0;
}