【问题标题】:How do I decrypt a file with Crypto++ that was encrypted with C#如何使用 C# 加密的 Crypto++ 解密文件
【发布时间】:2010-08-11 16:43:50
【问题描述】:


我想解密我之前使用 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);

该代码无法正确解密。解密后的结果与之前加密的明文不匹配。对我的代码有任何想法吗?

【问题讨论】:

    标签: c# c++ encryption crypto++


    【解决方案1】:

    你能用c++加密和解密吗? c#能加解密吗?

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

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

    【讨论】:

    • 是的,我可以在 C# 和 C++ 中加密和解密,我确实有一个方法 DecryptData(MemoryStream stream) 可以正常工作,我还使用 CFB_FIPS_Mode::Encryption encryption_DES_EDE2_CFB 测试了 Crypto++ 的加密;加密_DES_EDE2_CFB.SetKeyWithIV(pKey, sizeof(pKey), pIV, sizeof(pIV));加密_DES_EDE2_CFB.ProcessString(密文,lpData,bufferSize); tdes.Mode = CBC,tdes.Padding = PKCS7
    【解决方案2】:

    我设法使用my other post 中所述的 Windows Crypto API 完成了这项任务。

    【讨论】:

    • 这不是问题的答案。我打算在类似的问题中引用这篇文章,但我不能,因为 CryptoAPI 不是 Crypto++。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 2017-06-01
      • 2020-06-16
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多