2012-11-23 32 views
0

我想用Bruce Schneier的类加密文本,由Jim Conger转换为C++代码加密后,我想解密加密的文本。要尝试这一点,我正在使用它的文件。我创建了一个示例项目,但解密后的文件不包含与初始文件相同的文本。可能是什么问题?可可项目中的C++代码的Blowfish加密

以下是河豚类文件的下载link

我在XCode中创建了Command line tool项目,并将main.m文件更改为main.mm。在这里,你可以找到我的main.mm文件的内容:

#import "blowfish.h" 
#include <stdlib.h> 
#include <stdio.h> 

#define my_fopen(fileptr, filename, mode) \ 
fileptr = fopen(filename, mode); \ 
if (fileptr == NULL) { \ 
fprintf(stderr, "Error: Couldn't open %s.\n", filename); \ 
exit(1); \ 
} 

const char *input_file_name = "test.txt"; 
const char *encoded_file_name = "encoded.txt"; 
const char *decoded_file_name = "decoded.txt"; 
unsigned char key[] = "thisisthekey"; 

int main(void) { 
    FILE *infile, *outfile; 
    int result, filesize; 
    const int n = 8; // make sure this is a multiple of 8 
    const int size = 1; 
    unsigned char input[n], output[n]; 

    CBlowFish bf; 
    bf.Initialize(key, sizeof(key)-1); // subtract 1 to not count the null terminator 

    my_fopen(infile, input_file_name, "rb") 
    my_fopen(outfile, encoded_file_name, "wb") 

    filesize = 0; 
    while (result = fread(input, size, n, infile)) { 
     filesize += result; 
     fwrite(output, size, bf.Encode(input, output, result), outfile); 
    } 

    fclose(outfile); 
    fclose(infile); 

    my_fopen(infile, encoded_file_name, "rb") 
    my_fopen(outfile, decoded_file_name, "wb") 

    while (result = fread(input, size, n, infile)) { 
     bf.Decode(input, output, result); 
     fwrite(output, sizeof(output[0]), filesize < result ? filesize : result, outfile); 
     filesize -= result; 
    } 

    fclose(outfile); 
    fclose(infile); 

    return 0; 
} 

回答

1

您使用的是与填充分组密码(查看源代码CBlowFish::Encode)加密流。你不能这样做,因为解密操作将无法知道它应该解密的填充块的构成。例如,假设你正在加密“FOOBAR”,但你第一次阅读“FOO”,并且这个加密为“XYZZY”。然后你将“BAR”加密为“ABCDE”。您的书面文件将包含“XYZZYABCDE”。但那是“XY”“ZZYA”“BCDE”?或者一个块,“XYZZYABCDE”还是什么?

如果要加密流,请使用流密码。或者,如果要将其剪切为任意块,则必须保留输出块边界,以便可以解密块。

+0

你有什么例子吗? –

+0

@大卫请看看我的问题:http://stackoverflow.com/questions/19031842/dycrypt-value-from-blowfish-objective-c – QueueOverFlow

1

您必须编码/解码相应的数据块。 fread()和fwrite()不会返回相同的no。的字节(结果),所以您的纯文本数据块和密文数据块不会对齐。

定义数据块的长度(比如64字节),并在编码和解码时使用它。

否则使用使用1个字节的“数据块”的流密码;)

+0

你有任何例子吗? –

+1

http://en.wikipedia.org/wiki/Stream_cipher –

+0

谢谢,现在我知道从哪里开始吧! –