【发布时间】:2011-06-28 03:40:57
【问题描述】:
我正在尝试使用 XOR 加密/解密文件。我有以下加密/解密例程,其中每个字节都被异或,结果减去位于前一个位置的字节的值。 ASM表示如下
crypt:
mov dl, [eax+ecx] ; read byte
xor dl, 0C5h ; xor it with oxC5
sub dl, [eax+ecx-1] ; sub the previous byte
mov [eax+ecx], dl ; save the new byte
dec eax ; decrement pointer
test eax, eax
jg short crypt ;
这就是我的加密例程应该是什么样子,我正在尝试将此 C/C++ 移植。我的代码如下
#include <stdio.h>
unsigned int xorkey = 0xC5;
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("usage: encoder input output\n");
return -1;
}
FILE *in = fopen(argv[1], "rb");
if(in == NULL)
{
printf("failed to open: %s", argv[2]);
return -1;
}
FILE *out = fopen(argv[2], "wb");
if(out == NULL)
{
fclose(in);
printf("failed to open '%s' for writing.",argv[2]);
return -1;
}
int count;
char buffer[1024];
while(count = fread(buffer, 1, 1024, in))
{
int i;
int end = count;
for(i = 0;i < end; ++i)
{
((unsigned int *)buffer)[i] ^= xorkey;
}
if(fwrite(buffer, 1, count, out) != count)
{
fclose(in);
fclose(out);
printf("fwrite() error\n");
return -1;
}
}
fclose(in);
fclose(out);
return 0;
}
我不知道如何在 C++ 中减去字节。 XOR 例程本身看起来是正确的,不是吗? 请注意,我也在尝试从文件末尾到开头加密文件。有什么想法吗?
谢谢!
【问题讨论】:
-
有点难以在同一个句子中阅读“加密”和“异或”,而没有否定之间......混淆?当然。是的。完全。加密?没那么多。
-
没有像 C/C++ 这样的语言。它是 C 或 C++。选一个。 (我希望你为这段代码选择 C。)
-
@Keith 你显然从来没有上过密码学课,甚至懒得去阅读加密这个词的定义。 XOR cipher is absolutely an encryption method.
-
@Keith 如果有足够聪明的头脑解决问题,几乎任何问题都可以变得微不足道。加密就是加密,它不是一个松散定义的术语。
-
@Keith 告诉你,我会在 5 分钟内拼凑出一个 XOR 算法,如果我给你 5 年,你自己也无法解决 :) 这一切都取决于上下文。
标签: c encryption xor