我想解密一个我以前用TripleDESCryptoServiceProvider用C#加密过的文件。
下面是我的加密代码:
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();
}我已经找到了Crypto++库,并设法构建并链接了它。因此,我尝试使用以下(原生) 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);那段代码不能正确解密。解密后的结果与之前加密的明文不匹配。对我的代码有什么想法吗?
发布于 2010-03-11 18:47:59
正如my other post中所述,我设法用Windows Crypto API完成了这项任务。
发布于 2010-02-03 23:05:20
你能在c++中加密和解密吗?你能在c#中加密和解密吗?
您确定您正在使用相同的模式,填充和加密,解密序列?
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;发布于 2010-08-11 16:43:51
尝试CBC模式(TripleDESCryptoServiceProvider的默认模式)
https://stackoverflow.com/questions/2192584
复制相似问题