【发布时间】: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