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

问题描述 投票:3回答:2

我在我的通用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)

怎么了?

c# encryption uwp
2个回答
2
投票

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


1
投票

好的,我终于找到了答案:找到解密步骤时出错了!

正确的算法:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.