数据加密 | Personal Blog

数据加密

概念

编码

将字符序列转化为字节序列的过程

数据流

输入设备和输出设备的数据传递

Encoding类

using System.Text;

Encoding.GetEncodings() //返回一个数组

编码实例

using System;
using System.Text;

namespace _20200330
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var i in Encoding.GetEncodings())
            {
                Encoding en1 = i.GetEncoding();
                Console.WriteLine("编码名称:{0,-18},编码描述:{1}",i.Name,en1.EncodingName);
            }
            string s1;
            s1=Console.ReadLine();
            Encoding en = Encoding.ASCII;
            byte[] bytes = en.GetBytes(s1);
            Console.WriteLine(BitConverter.ToString(bytes));
            Encoding en2 = Encoding.Unicode;
            byte[] bytes1 = en2.GetBytes(s1);
            Console.WriteLine(BitConverter.ToString(bytes1));
        }
    }
}

文件的读取实例

FileStream类

FileStream类可以对各种类型的文件进行读写操作

using System;
using System.IO;//关键命名空间
using System.Text;
namespace 20200331
{
    class Program
    {
        static void Main(string[] args)
        {
            //FileStream fs =new FileStream(string path,FileMode mode,FileAccess access);
            //                              path指定文件路径,mode指定文件操作方式,access控制文件访问权限
            FileStream fs =new FileStream("1.txt",FileMode.OpenOrCreate,FileAccess.ReadWrite);//构造一个文件流
            //在Debug目录下新建一个1.txt
            FileStream fs2 =new FileStream("2.txt",FileMode.Create,FileAccess.ReadWrite);//构造另一个文件流
            byte[] buffer= new byte[1024];//构造缓冲区
            int num =fs.Read(buffer,0,buffer.Length);//从0位置开始读取buffer.length长度,将文件实际读取的长度赋给mum
            fs2.Write(buffer,0,num);//将缓冲区中的数据流写入另一文件//此时文件位指针fs2.Position不断后移,文件的读取从指针指向的位置进行,每次读取之前需要改变指针位置
            fs2.Close();
            String str =Encoding.UTF8.GetString(buffer,0,num);//将buffer从0位置开始解码mum个位置
            fs.Close();//关闭文件
            Console.WriteLine(str);
        }
    }
}

StreamReader和StreamWriter类

只能操作文本

using System;
using System.IO;
using System.Text;
namespace 20200407
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = new FileStream("1.txt",FileMode.Open,FileAccess.Read);//构造一个文件流
            StreamReader sr= new StreamReader(fs);//操作sr相当于操作fs
            String str=sr.ReadToEnd();//全部读取
            fs.Close();
            sr.Close();
        }
    }
}

Aes类

加密流 CryptoStream

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

public static byte[] EncryptString(string str, byte[] key, byte[] iv)
{
    byte[] encrypted;
    using (Aes aesAlg = Aes.Create())//此时已经自动创建了key和iv
    {
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(key, iv);//key是密钥,iv是初始化向量,一个随机生成的字符集
        //明文按块加密,每一块和前一块进行按位异或操作,第一块与iv进行按位异或
        MemoryStream ms = new MemoryStream();                       //内存流
        //CryptoStream cs = new CryptoStream(Stream stream,ICryptoTransform transform,CryptoStreamMode mode);
        //                                加密或解密后的目的流   加密转换的方式              模式,解密读取,加密写入
        CryptoStream cs = new CryptoStream(ms,encryptor,CryptoStreamMode.Write);
        //byte[] oldBytes= Encoding.UTF8.GetBytes(str);
        //cs.Write(oldBytes, 0, oldBytes.Length);
        using (StreamWriter sw = new StreamWriter(cs))//
        {
            sw.Write(str);
        }
        encrypted = ms.ToArray();
        cs.Close();
        ms.Close();
    }
    return encrypted;
}

/// <summary>
使用AES算法解密字符串
///</summary>
public static string DescrptString(byte[] data, byte[] key, byte[] iv)
{
    string str = null;
    using (Aes aesAlg = Aes.Create())
    {
        ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, iv);
        MemoryStream ms = new MemoryStream(data);
        CryptoStream cs = new CryptoStream(ms,decryptor,CryptoStreamMode.Read);
        using (StreamReader sr = new StreamReader(cs))
        {
            str = sr.ReadToEnd();
        }
        cs.Close();
        ms.Close();
    }
    return str;
}

/// <summary>根据提供的密码生成Key和IV</summary>
public static void GenKeyIV(string password, out byte[] key, out byte[] iv)//返回多个值,key数组和iv数组
{
    using (Aes aes = Aes.Create())
    {
        key = new byte[aes.Key.Length];                     //创建密钥空间
        byte[] pwdBytes = Encoding.UTF8.GetBytes(password);//获得密码的UTF-8编码,存储到pwdBytes数组中,若密码数据长度不够,还可以补全
        for (int i = 0; i < pwdBytes.Length; i++)
        {
            key[i] = pwdBytes[i];                           //将pwdBytes数组中的数据赋给key数组
        }
        iv = new byte[aes.IV.Length];
        for (int i = 0; i < pwdBytes.Length; i++)
        {
            iv[i] = pwdBytes[i];
        }
    }
}

/// <summary>根据提供的密码生成Key和IV</summary>
public static void GenKeyIV(out byte[] key, out byte[] iv)//没有密码的情况直接赋值
{
    using (Aes aes = Aes.Create())
    {
        key = aes.Key;
        iv = aes.IV;
    }
}