我在通用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)
出了什么问题?
答案 0 :(得分:2)
只是查看代码,似乎您将加密结果(通常是二进制blob转换为Base64字符串,这很好)。但是,当您解密时,您并没有完全撤消Base64编码,而是将其视为二进制blob,难怪解码将失败。
答案 1 :(得分: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);
}