解密可串行结构不起作用
试图解密时我的错误是什么?
当调用DecrypToken显示此消息时:
mscorlib.dll中发生未处理的类型为“System.Runtime.Serialization.SerializationException”的异常
附加信息:输入流不是有效的二进制格式。
[编辑]
数据现在将数据从十六进制格式转换回来。
Key和IV现在被保存以重用。
现在得到这个错误:
mscorlib.dll中发生未处理的类型为“System.Runtime.Serialization.SerializationException”的异常
其他信息:分析完成前遇到的流结束。
代码:
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Security.Cryptography;
namespace DecryptStruct
{
class Program
{
static byte[] theKey = null;
static byte[] theIV = null;
[Serializable]
internal struct Token
{
public string user;
public string host;
public string now;
}
static string EncryptToken(string user, string host)
{
Token token = new Token();
token.user = user;
token.now = DateTime.Now.ToString();
token.host = host;
//serialize
IFormatter form = new BinaryFormatter();
MemoryStream ser = new MemoryStream();
form.Serialize(ser, (object)token);
//setup crypto
Rijndael alg = Rijndael.Create();
alg.GenerateIV();
alg.GenerateKey();
//save keys
theKey = alg.Key;
theIV = alg.IV;
//rewind stream
ser.Position = 0;
//encrypt
MemoryStream enc = new MemoryStream();
CryptoStream cw = new CryptoStream(enc, alg.CreateEncryptor(), CryptoStreamMode.Write);
cw.Write(ser.ToArray(), 0, (int)ser.Length);
cw.FlushFinalBlock();
enc.Position = 0; //rewind
byte[] benc = enc.ToArray();
string hex = Convert.ToBase64String(benc);
cw.Close();
return hex;
}
static Token DecrypToken(string hex)
{
byte[] benc = Convert.FromBase64String(hex);
MemoryStream enc = new MemoryStream(benc);
//setup crypto
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());
byte[] buf = new byte[(int)ser.Length];
cr.Read(buf, 0, (int)ser.Length);
MemoryStream unenc = new MemoryStream(buf);
unenc.Position = 0;
//deserialize
Token tk = (Token)form.Deserialize(unenc);
return tk;
}
static void Main(string[] args)
{
string enc = EncryptToken("username", "myhost");
Token token = DecrypToken(enc);
}
}
}
你用十六进制编码它并在这里转换它:
byte[] benc = enc.ToArray();
string hex = BitConverter.ToString(benc);
cw.Close();
return hex.Replace("-", "");
但是你不要做相反的事情!
GenerateIV()和GenerateKey()方法分别用一个新的随机IV和关键字初始化算法。 您必须使用完全相同的密钥和IV来解密用于加密的数据,但在加密时不会存储任何值,而是在解密例程期间生成另一个(完全不同的)密钥/ IV。
如另一个答案所示,您还忘记了在加密时反转使用的文本编码。 我建议使用Convert.ToBase64String()到加密数据转换为字符串值,并且Convert.FromBase64String()解密时将其转换回成一个字节数组。
上一篇: Decrypt serializable struct is not work
下一篇: Deep Copy in C#
