在不同的Endianness上使用Blowfish

时间:2013-05-01 06:28:32

标签: c++ encryption endianness blowfish

我正在编写一个FTP程序,需要在大端计算机和小端计算机之间进行Blowfish加密。 Here is the code I am using to do the encryption.正如您所看到的,它在代码中已经考虑了Endianness。问题是,当我在一台机器上加密然后在不同字节序的机器上解密时,结果是错误的。

目前我只是将加密的字符串写入文件,然后在另一台机器(共享内存)上读取它以获得简单的测试用例。

以下是我创建的两个辅助方法(相当直接):

      //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,但没有运气。

0 个答案:

没有答案