我正在编写一个需要在大端计算机和小端计算机之间进行 Blowfish 加密的 FTP 程序。这是我用来进行加密的代码。 如您所见,它已经在代码中考虑了字节序。问题是,当我在一台机器上加密然后在不同字节序的机器上解密时,结果是错误的。
目前我只是将加密的字符串写入文件,然后在另一台机器(共享内存)上读取它以获取一个简单的测试用例。
这是我创建的两个辅助方法(相当严格):
//Encrypts string and return encrpted string
void encrypt(Blowfish* BF, unsigned char* whatToEncrypt, int size, unsigned char* encryptionKey){
char* tmp = (char*)malloc(sizeof(char)*(PASSWORD_LENGTH+1));
memcpy(tmp, encryptionKey, (PASSWORD_LENGTH+1));
//Set BF Password
BF->Set_Passwd((char*)tmp);
BF->Encrypt((void *)whatToEncrypt, size);
}
//decrypts enrypted string and returns a string
void decrypt(Blowfish* BF, unsigned char* whatToDecrypt, int size, unsigned char* encryptionKey){
char* tmp = (char*)malloc(sizeof(char)*(PASSWORD_LENGTH+1));
memcpy(tmp, encryptionKey, (PASSWORD_LENGTH+1));
//Set BF Password
BF->Set_Passwd(tmp);
//decrypt
BF->Decrypt((void *)whatToDecrypt, size);
}
机器 1 代码:
int main(){
Blowfish BF;
unsigned char* test = new unsigned char[8];
for (int i = 0; i < 8; i++){
test[i] = 'a'+i;
}
unsigned char* test_key = new unsigned char[9];
for (int i = 0; i < 8; i++){
test_key[i] = 'f';
}
test_key[8] = '\0';
cout << "test: " << test<<endl;
encrypt(&BF, test, 8, test_key);
cout << "test: " << test<<endl;
FILE* in = fopen("example.txt", "w");
for (int i = 0; i < 8; i++){
fputc(test[i], in);
}
fclose(in);
}
机器2代码:
int main(){
FILE* in = fopen("example.txt", "r");
Blowfish BF;
unsigned char* test = new unsigned char[9];
for (int i = 0; i < 8; i++){
test[i] = fgetc(in);
}
test[8] = '\0';
fclose(in);
unsigned char* test_key = new unsigned char[9];
for (int i = 0; i < 8; i++){
test_key[i] = 'f';
}
test_key[8] = '\0';
cout << "test: " << test<<endl;
decrypt(&BF,test, 8, test_key);
cout << "test: " << test<<endl;
}
如您所见,密钥是硬编码的,所以它是相同的,但输出仍然是错误的。我尝试在两台机器之间的每个组合(在blowfish.h中)中手动分配WordByte,但没有成功。