Skip to main content
 首页 » 编程设计

c#之加密和解密字节数组

2024年02月13日13mate10pro

我有以下实用函数来将我的对象序列化为加密的字节数组,并从解密的字节数组反序列化

//encryption key 
public static byte[] Key = new byte[]{0x43, 0x72, 0x6e, 0x6d, 0x54, 0x4d, 0x65, 
                                      0x94, 0x16, 0x32, 0x44, 0x84, 0x7e, 0x18, 
                                      0x64, 0x76, 0x6e, 0x63, 0x64, 0x7a, 0x5f, 
                                      0x84, 0x7f, 0x9a}; 
 
//Decrypt byte[] 
public static byte[] Decrypt(byte[] data) 
{ 
    MemoryStream ms = new MemoryStream(); 
    Rijndael alg = Rijndael.Create(); 
    alg.Key = Key; 
    CryptoStream cs = new CryptoStream(ms, 
    alg.CreateDecryptor(), CryptoStreamMode.Write); 
    cs.Write(data, 0, data.Length); 
    cs.Close(); 
    byte[] decryptedData = ms.ToArray(); 
    return decryptedData; 
} 
 
//Encrypt byte[] 
public static byte[] Encrypt(byte[] data) 
{ 
    MemoryStream ms = new MemoryStream(); 
    Rijndael alg = Rijndael.Create(); 
    alg.Key = Key; 
    CryptoStream cs = new CryptoStream(ms, 
    alg.CreateEncryptor(), CryptoStreamMode.Write); 
    cs.Write(data, 0, data.Length); 
    cs.Close(); 
    byte[] encryptedData = ms.ToArray(); 
    return encryptedData; 
} 
 
//serialize object to memory stream 
public static MemoryStream SerializeToStream(object o) 
{ 
    MemoryStream stream = new MemoryStream(); 
    IFormatter formatter = new BinaryFormatter(); 
    formatter.Serialize(stream, o); 
    return stream; 
} 
 
//deserialize object from memory stream 
public static T DerializeFromStream<T>(MemoryStream memoryStream) where T : new() 
{ 
    if (memoryStream == null) { return new T(); } 
    T o; 
    BinaryFormatter binaryFormatter = new BinaryFormatter(); 
    using (memoryStream) 
    { 
        memoryStream.Seek(0, SeekOrigin.Begin); 
        o = (T)binaryFormatter.Deserialize(memoryStream); 
    } 
    return o; 
} 

这里是使用上述实用函数的测试

//serialize to stream then to byte array 
var obj = new SomeObject(); 
var bytes = SerializeToStream(obj).ToArray(); 
bytes = Encrypt(bytes); 
 
//deserialize to decrypted byte array then to stream then to object 
var memoryStream = new MemoryStream(); 
var Decryptedbytearray = Decrypt(bytes); 
//fille the stream 
memoryStream.Write(Decryptedbytearray, 0, Decryptedbytearray.Length); 
//deserialize the object from the stream 
//it fails here giving an exception saying the binary data is not valid 
var obj2 = DerializeFromStream<SomeObject>(memoryStream); 

反序列化对象时出现问题,看最后一行注释,我做错了什么?

请您参考如下方法:

如果您调试代码,您会发现它没有正确解密。原因是您不仅要使用相同的 key,还要使用相同的 IV。

来自 MSDN :

The IV property is automatically set to a new random value whenever you create a new instance of one of the SymmetricAlgorithm classes or when you manually call the GenerateIV method. The size of the IV property must be the same as the BlockSize property divided by 8.

看看this question有关如何从密码短语创建 key 和 IV 的详细信息。