c# - 不同字符串上的解密错误不一致
问题描述
我正在尝试使用密码解密数据并且它确实加密得很好,但是在某些情况下我无法从中解密,总是出错:
System.Security.Cryptography.CryptographicException: 'Length of the data to decrypt is invalid.'
我真的不确定为什么它不解密。这是我加密和解密的源代码:
private static byte[] key = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
private static byte[] iv = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 };
public static string Crypt(this string text)
{
SymmetricAlgorithm algorithm = DES.Create();
ICryptoTransform transform = algorithm.CreateEncryptor(key, iv);
byte[] inputbuffer = System.Text.Encoding.Unicode.GetBytes(text);
byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
return Convert.ToBase64String(outputBuffer);
}
public static string Decrypt(this string text)
{
SymmetricAlgorithm algorithm = DES.Create();
ICryptoTransform transform = algorithm.CreateDecryptor(key, iv);
byte[] inputbuffer = Convert.FromBase64String(text);
byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length);
return Encoding.Unicode.GetString(outputBuffer);
}
我试图找到答案,但是我不确定这是否是解密方法的缺陷,因为它在大多数情况下确实有效,但在某些情况下会出现此错误。我不知道为什么会出现错误,我已经与我加密的其他较长的字符串进行了比较,解密就好了。有时它会因 71 个字符而崩溃,但它适用于另一个 282 个字符的字符串。我已经删除了 base64 不支持的特殊字符,只留下了支持的“/”。
编辑:作为一个例子,这个字符串可以正常使用 258 个字符:
原来的:
"The room has three rooms, two of them are rooms with 2 double beds, a large wardrobe, bathroom in each room, the third room, is a living room, where there is a breakfast room, large refrigerator, television, telephone, microwave, coffee maker, plus a terrace"
加密字符串:
"Uy59aiizgznbLhdM1x8twTGK6fsv4AuQBqS9SNjhoqq98hKaVjotbgpE8aE5/Knbte8KQpLOO0bhU4UjNi8yyAu58L4h0bdtADrrr3HQ07Bx9yGos9Hnl5KFg3shNu/TnodJwK5aDSs6IhlBGkBWs91xuSCXAoIwfHTLwjkkQa5wv4WLdw3Zzj19EdeRwWNNstFQ/ICNJysVP5eaFQnlVJZ4XwN/BVyuPuOnFSYizC1Tu/tFr/4EHSa/eree1pzjPfeqtcy7dKYIyHkniIRyoKMxuBXgDHAwolFcuWM53tWswy74zkCyS25o0aydrt8qEGMKDEGVjjwT6BhREpX0gyO3jAAKy4KwE+D/SfBDeQlYH64uwai4wMi5qz5dy4kbmyZvdzaAERM6p5MNKNXWPQ5qT2XtcOCM/nSI1ioY9nG8pZBxJ8kui5+mYuYf16rKkiuxSHZddAsSzEol0XVgIhS5cVaHIH2Sb4YhJ/IcVfW1MzVaE959ykWpWJ3a4FSI1R0s0AdHXrsII//21zrTO6s9O7EbnVYaPlxTByIgx6c58CCfr4CPfePtPmG2VT14BwfgVLJu26+SawPl79wzuwZ6DJBBIzZq/3xQi6SVfKZYDvxz5ywhpTQHKb5/bQyo0cBMZ0OkTpp8qYlKzy7dQNjsmthuWKsxqW5F6o7uUFfpXFCYT2OyOf2lHvdoXUWdDWqecxfa8183vkH6p8AAI++suJ6/5LieD3ampvb91HNfA3HMz3exnA=="
虽然这个其他字符串不解密(只有 79 个字符):
原来的:
Name:Dance classes/Description:Dance classes with Joan the dancer/Picture:IMAGE
加密:
ha3P4ZB+q3dCn2HLwWUTH/vJ3IEgKAW9Ha/33Co9bgUuPym+cgSs6dndhecKdOXRZVjw4hx/qKxpMGMXVH+X70jZogA/Ef08AGzV/GTnz4S8UM0q2+VK6epL7P0D0Mz2b+NrD86Fu7FGvaHrlhiOHwT5h87EmlOkn1jHhKKdf+khRDbYyvECrKfSa5SZg0OAHv3Z6nuO