2010-02-03 125 views
2


我想解密先前使用TripleDESCryptoServiceProvider使用C#加密的文件。
这里是我的代码用于加密:如何解密使用C#加密的Crypto ++的文件

private static void EncryptData(MemoryStream streamToEncrypt) 
    { 
     // initialize the encryption algorithm 
     TripleDES algorithm = new TripleDESCryptoServiceProvider(); 

     byte[] desIV = new byte[8]; 
     byte[] desKey = new byte[16]; 

     for (int i = 0; i < 8; ++i) 
     { 
      desIV[i] = (byte)i; 
     } 

     for (int j = 0; j < 16; ++j) 
     { 
      desKey[j] = (byte)j; 
     } 

     FileStream outputStream = new FileStream(TheCryptedSettingsFilePath, FileMode.OpenOrCreate, FileAccess.Write); 
     outputStream.SetLength(0); 

     CryptoStream encStream = new CryptoStream(outputStream, algorithm.CreateEncryptor(desKey, desIV), 
      CryptoStreamMode.Write); 

     // write the encrypted data to the file 
     encStream.Write(streamToEncrypt.ToArray(), 0, (int)streamToEncrypt.Length); 

     encStream.Close(); 
     outputStream.Close(); 
    } 

我已经找到了加密++库,并成功地建立并链接。于是,我就解密是用下面的(本地)C++代码的加密后存储在C#中的文件:

FILE *fp; 
long len; 
char *buf; 
if (_wfopen_s(&fp, _T("MyTest.bin"), _T("rb")) != 0) 
{ 
    return false; 
} 

fseek(fp ,0 ,SEEK_END); //go to end 
len = ftell(fp); //get position at end (length) 
fseek(fp, 0, SEEK_SET); //go to beg. 
buf = (char *)malloc(len); //malloc buffer 
fread(buf, len, 1, fp); //read into buffer 
fclose(fp); 
BYTE pIV[] = {0, 1, 2, 3, 4, 5, 6, 7}; 
BYTE pKey[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; 

const BYTE* lpData = (const BYTE*)(LPCTSTR)buf; 
size_t bufferSize = strlen(buf); 
BYTE* result = (BYTE *)malloc(bufferSize); 

CFB_FIPS_Mode<DES_EDE2>::Decryption decryption_DES_EDE2_CFB; 
decryption_DES_EDE2_CFB.SetKeyWithIV(pKey, sizeof(pKey), pIV, sizeof(pIV)); 
decryption_DES_EDE2_CFB.ProcessString(result, lpData, bufferSize); 

该代码将无法正确解密。解密后的结果与先前加密的纯文本不匹配。任何关于我的代码的想法?

回答

0

我设法做任务与Windows加密API为my other post规定。

+0

这不是问题的答案。我打算在类似的问题中引用此帖,但是我不能,因为CryptoAPI不是Crypto ++。 – jww 2016-08-11 22:37:43

0

你可以在C++中加密和解密吗? 你可以在c#中加密和解密吗?

你确定你使用相同的模式,填充和加密,解密序列?

tdes.Mode = CipherMode.ECB; 
tdes.Padding = PaddingMode.PKCS7; 
+0

是的,我可以加密和在C#和C解密++,我有一个方法DecryptData(MemoryStream的流),其工作正常,我也测试了加密,加密+使用CFB_FIPS_Mode ::加密encryption_DES_EDE2_CFB; \t encryption_DES_EDE2_CFB.SetKeyWithIV(pKey,sizeof(pKey),pIV,sizeof(pIV)); \t encryption_DES_EDE2_CFB.ProcessString(ciphertext,lpData,bufferSize); tdes.Mode = CBC,tdes.Padding = PKCS7 – 2010-02-03 15:49:17

0

尝试CBC模式(TripleDESCryptoServiceProvider的默认模式)