通用 Windows 平台 (UWP) 中的加密/解密存在数据错误(循环冗余检查)

本文关键字:存在 解密 循环冗余检查 数据 错误 平台 Windows UWP 通用 加密 | 更新日期: 2023-09-27 18:31:59

我在我的通用Windows平台(UWP)应用程序中使用了DES加密/解密算法。 数据加密工作正常,但解密有错误:

这是我的代码:

private static byte[] IV = { 12, 11, 12, 55, 0, 108, 121, 54 };
private static string stringKey = "SA/DF@#asx.";
private static BinaryStringEncoding encoding;
private static byte[] keyByte;
private static SymmetricKeyAlgorithmProvider objAlg;
private static CryptographicKey Key;

加密:

public static string Encrypt(String strMsg)
{
     IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg,encoding);
     IBuffer buffEncrypt = CryptographicEngine.Encrypt(Key, buffMsg, IV.AsBuffer());
     return CryptographicBuffer.EncodeToBase64String(buffEncrypt);
}

解密:

public static string Decrypt(String strMsg)
{
     var bb = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);
     IBuffer buffEncrypt = CryptographicEngine.Decrypt(Key, bb, IV.AsBuffer());
     return CryptographicBuffer.EncodeToBase64String(buffEncrypt);
}

解密有这个错误:

Data error (cyclic redundancy check). (Exception from HRESULT: 0x80070017)

怎么了?

通用 Windows 平台 (UWP) 中的加密/解密存在数据错误(循环冗余检查)

仅查看代码,似乎您已将加密结果(通常是二进制blob转换为Base64字符串,这很好)。但是,当您解密时,您并没有完全撤消 Base64 编码,而是将其视为二进制 blob,难怪解码会失败。

好的,我终于找到了答案:解密步骤的定位有误!

正确的算法:

private static byte[] IV = { 12, 11, 12, 55, 0, 108, 121, 54 };
private static string stringKey = "SA/DF@#asx.";
private static BinaryStringEncoding encoding;
private static byte[] keyByte;
private static SymmetricKeyAlgorithmProvider objAlg;
private static CryptographicKey Key;

UWP 中的 DES 加密:

public static string Encrypt(String strMsg)
{
     IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg,encoding);
     IBuffer buffEncrypt = CryptographicEngine.Encrypt(Key, buffMsg, IV.AsBuffer());
     return CryptographicBuffer.EncodeToBase64String(buffEncrypt);
}

和解密步骤:

public static string Decrypt(String strMsg)
{
    Byte[] bb = Convert.FromBase64String(strMsg);
    IBuffer buffEncrypt = CryptographicEngine.Decrypt(Key, bb.AsBuffer(), IV.AsBuffer());
    return CryptographicBuffer.ConvertBinaryToString(encoding, buffEncrypt);
}