惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
F
Fortinet All Blogs
D
Docker
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
罗磊的独立博客
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
J
Java Code Geeks
T
The Blog of Author Tim Ferriss
U
Unit 42
N
Netflix TechBlog - Medium
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Proofpoint News Feed
G
Google Developers Blog
H
Help Net Security

博客园 - 大豆男生

C# 和 OpenResty 中进行 CRC32 Linq分组后,再对分组后的每组数据进行排序,获取每组的第一条记录 WebClient 指定安全协议(Tls1.1,Tls1.2,Tls1.3) .Net Core 中的 MurmurHash VS2019 .Net Core 3.0 Web 项目启用动态编译 IIS 上部署 ASP.NET Core 应用程序 IIS (安装SSL证书后) 实现 HTTP 自动跳转到 HTTPS 使用浏览器自定义协议启动本地程序(.EXE文件) 腾讯防水墙(滑动验证码)的简单使用 https://007.qq.com C# 使用 PerformanceCounter 获取 CPU 和 硬盘的使用率 .Net 控制台中文(简体/繁体)乱码问题 .Net Core 使用 System.Drawing.Common 部署到CentOS上遇到的问题 .Net Core 读取配置文件 appsettings.json JavaScript 获取按键,并屏蔽系统 Window 事件 frp 初探 nginx 禁止未绑定的域名访问 .NET MVC JSON JavaScriptSerializer 字符串的长度超过 maxJsonLength 值问题的解决 async,await,Task 的一些用法 Newtonsoft.Json(Json.net) 的使用
再谈 C# 对象二进制序列化,序列化并进行 AES 加密
大豆男生 · 2018-11-22 · via 博客园 - 大豆男生

对象的二进制序列化非常有用,也非常方便。

我们可以把对象序列化为字节数组,也可以把对象序列化到文件,还可以把对象序列化到文件并进行加密。 

先引用这些命名空间:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;

序列化对象到字节数组:

/// <summary>
/// 把对象序列化为字节数组
/// </summary>
public static byte[] SerializeObjectToBytes(object obj)
{
    if (obj == null)
        return null;
    MemoryStream ms = new MemoryStream();
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(ms, obj);
    byte[] bytes = ms.ToArray();
    return bytes;
}

/// <summary>
/// 把字节数组反序列化成对象
/// </summary>
public static object DeserializeObjectFromBytes(byte[] bytes)
{
    object obj = null;
    if (bytes == null)
        return obj;
    MemoryStream ms = new MemoryStream(bytes)
    {
        Position = 0
    };
    BinaryFormatter formatter = new BinaryFormatter();
    obj = formatter.Deserialize(ms);
    ms.Close();
    return obj;
}

序列化对象到文件:

public static void SerializeObjectToFile(string fileName, object obj) 
{
    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(fs, obj);
    }
}

/// <summary>
/// 把文件反序列化成对象
/// </summary>
public static object DeserializeObjectFromFile(string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        BinaryFormatter formatter = new BinaryFormatter();
        object obj = formatter.Deserialize(fs);
        return obj;
    }
}

序列化对象到文件,并进行 AES 加密:

/// <summary>
/// 把对象序列化到文件(AES加密)
/// </summary>
/// <param name="keyString">密钥(16位)</param>
public static void SerializeObjectToFile(string fileName, object obj, string keyString)
{
    using (AesCryptoServiceProvider crypt = new AesCryptoServiceProvider())
    {
        crypt.Key = Encoding.ASCII.GetBytes(keyString);
        crypt.IV = Encoding.ASCII.GetBytes(keyString);
        using (ICryptoTransform transform = crypt.CreateEncryptor())
        {
            FileStream fs = new FileStream(fileName, FileMode.Create);
            using (CryptoStream cs = new CryptoStream(fs, transform, CryptoStreamMode.Write))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(cs, obj);
            }
        }
    }
}

/// <summary>
/// 把文件反序列化成对象(AES加密)
/// </summary>
/// <param name="keyString">密钥(16位)</param>
public static object DeserializeObjectFromFile(string fileName, string keyString)
{
    using (AesCryptoServiceProvider crypt = new AesCryptoServiceProvider())
    {
        crypt.Key = Encoding.ASCII.GetBytes(keyString);
        crypt.IV = Encoding.ASCII.GetBytes(keyString);
        using (ICryptoTransform transform = crypt.CreateDecryptor())
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            using (CryptoStream cs = new CryptoStream(fs, transform, CryptoStreamMode.Read))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                object obj = formatter.Deserialize(cs);
                return obj;
            }
        }
    }
}