【问题标题】:Decrypt serializable struct is not work解密可序列化结构不起作用
【发布时间】:2014-08-01 14:11:22
【问题描述】:

尝试解密时我的错误是什么?
调用 DecrypToken 时显示此消息:
mscorlib.dll 中出现“System.Runtime.Serialization.SerializationException”类型的未处理异常
附加信息:输入流不是有效的二进制格式。

[编辑]
数据现在从十六进制格式转换回数据。
现在保存密钥和 IV 以供重复使用。

现在出现此错误:
mscorlib.dll 中出现“System.Runtime.Serialization.SerializationException”类型的未处理异常

附加信息:在解析完成之前遇到流结束。

代码:

使用系统; 使用 System.Runtime.Serialization; 使用 System.Runtime.Serialization.Formatters.Binary; 使用 System.IO; 使用 System.Security.Cryptography; 命名空间解密结构 { 课堂节目 { 静态字节[] theKey = null; 静态字节[] theIV = null; [可序列化] 内部结构令牌 { 公共字符串用户; 公共字符串主机; 现在公开字符串; } 静态字符串加密令牌(字符串用户,字符串主机) { 令牌令牌 = 新令牌(); 令牌.用户 = 用户; token.now = DateTime.Now.ToString(); token.host = 主机; //连载 IFormatter form = new BinaryFormatter(); MemoryStream ser = new MemoryStream(); form.Serialize(ser, (object)token); //设置加密 Rijndael alg = Rijndael.Create(); alg.GenerateIV(); alg.GenerateKey(); //保存密钥 theKey = alg.Key; theIV = alg.IV; //倒流流 ser.Position = 0; //加密 MemoryStream enc = new MemoryStream(); CryptoStream cw = new CryptoStream(enc, alg.CreateEncryptor(), CryptoStreamMode.Write); cw.Write(ser.ToArray(), 0, (int)ser.Length); cw.FlushFinalBlock(); 编码位置 = 0; //倒带 byte[] benc = enc.ToArray(); 字符串十六进制 = Convert.ToBase64String(benc); cw.Close(); 返回十六进制; } 静态令牌解密令牌(字符串十六进制) { byte[] benc = Convert.FromBase64String(hex); MemoryStream enc = new MemoryStream(benc); //设置加密 Rijndael alg = Rijndael.Create(); alg.Key = theKey; alg.IV = theIV; CryptoStream cr = new CryptoStream(enc, alg.CreateDecryptor(), CryptoStreamMode.Read); IFormatter form = new BinaryFormatter(); MemoryStream ser = new MemoryStream(); form.Serialize(ser, (object)new Token()); 字节[] buf = 新字节[(int)ser.Length]; cr.Read(buf, 0, (int)ser.Length); MemoryStream unenc = new MemoryStream(buf); unenc.Position = 0; //反序列化 Token tk = (Token)form.Deserialize(unenc); 返回tk; } 静态无效主要(字符串 [] 参数) { string enc = EncryptToken("username", "myhost"); 代币 token = DecrypToken(enc); } } }

【问题讨论】:

  • 你把它转换成十六进制然后你不把它转换回来!

标签: c# serialization encryption struct


【解决方案1】:

GenerateIV()GenerateKey() 方法分别使用新的随机 IV 和密钥初始化算法。您必须使用与加密数据完全相同的密钥和 IV 来解密数据,但在加密时不会存储任何一个值,而是在解密例程期间生成另一​​个(完全不同的)密钥/IV。

正如另一个答案所表明的那样,您还忘记了在加密时反转您使用的文本编码。我建议使用Convert.ToBase64String() 将加密数据转换为字符串值,并在解密时使用Convert.FromBase64String() 将其转换回字节数组。

【讨论】:

    【解决方案2】:

    您将其编码为十六进制并在此处进行转换:

            byte[] benc = enc.ToArray();
    
            string hex = BitConverter.ToString(benc);
    
            cw.Close();
    
            return hex.Replace("-", "");
    

    但你不能反其道而行之!

    【讨论】:

      猜你喜欢
      • 2014-05-30
      • 2019-07-21
      • 2019-10-08
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多