AES对称加密算法简记(三)

  • 对称加密算法的使用
  • ==核心步骤代码==
  • 具体的使用方法
  • 加密解密AssetBundle数据
  • 加密解密网络数据
  • 参考链接
  • 其他相关链接可做参考


对称加密算法的使用

这里使用的是C#的加密算法库System.Security.Cryptography
下面先看一下核心代码示例,这里用的是AES算法;再下面的例子用的是Rijndael算法。其余算法与AES/Rijndael的用法步骤相同,便不做记录。

核心步骤代码

byte[] key = Encoding.UTF8.GetBytes(KEY);
byte[] iv = Encoding.UTF8.GetBytes(IV);

Aes aes = Aes.Create();
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform crypto = aes.CreateEncryptor(key, iv);
CryptoStream cryptoStream = new CryptoStream(memoryStream, crypto, CryptoStreamMode.Write);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
memoryStream.Close();
  • Aes为加密算法类,可以根据需要改为DES或者TripleDES算法等算法类,在System.Security.Cryptography中都有。
  • MemoryStream位于System.IO命名空间,为系统内存提供流式的读写操作。常作为其他流数据交换时的中间对象操作。
  • 所有的算法类都有CreateEncryptorCreateDecryptor两个方法,一个用于解密,另一个用于加密。他们分别有两个重载函数,一个可以不用添加参数,使用计算机产生的密钥;另一个是上面例子中的添加两个字节数组作为参数,一个为自建密钥Key,另一个为初始化向量IV,当然可以使用算法中的字段设置这两个值,关于这两个值的作用 CryptoStream定义将数据流链接到加密转换的流。相关链接:https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.cryptostream?view=netcore-3.1
  • cryptoStream.FlushFinalBlock();用缓冲区的当前状态更新基础数据源或存储库,随后清除缓冲区。
  • 解密之后的字节数组可以通过Convert.ToBase64String(bytes);Base64编码方式进行解析,大部分加解密需要一起使用。

具体的使用方法

加密和解密本地文档使用的是Rijndael对称算法。对称算法在数据流通过时对它进行加密。

  • 因此首先需要建立一个正常的流(例如I/O流)。使用FileStream类将文本文件读入字节数组,也使用该类作为输出机制。
  • 接下来定义相应的对象变量。在定义SymmetricAlgorithm抽象类的对象变量时我们可以指定任何一种对称加密算法提供程序。代码使用的是Rijndael算法,但是很容易改为DES或者TripleDES算法。.NET使用强大的随机密钥设置了提供程序的实例,选择自己的密钥是比较危险的,接受计算机产生的密钥是一个更好的选择,文中的代码使用的是计算机产生的密钥。算法实例提供了一个对象来执行实际数据传输。每种算法都有CreateEncryptorCreateDecryptor两个方法,它们返回实现ICryptoTransform接口的对象。
  • 最后,现在使用BinaryReaderReadBytes方法读取源文件,它会返回一个字节数组。BinaryReader读取源文件的输入流,在作为CryptoStream.Write方法的参数时调用ReadBytes方法。指定的CryptoStream实例被告知它应该操作的下层流,该对象将执行数据传递,无论流的目的是读或者写。
string file;
string tempfile = Path.GetTempFileName();
//打开指定的文件
FileStream fsIn = File.Open(file, FileMode.Open, FileAccess.Read);
FileStream fsOut = File.Open(tempfile, FileMode.Open, FileAccess.Write);

//定义对称算法对象实例和接口SymmetricAlgorithm所有的对称算法类都是从这个基类继承而来的
SymmetricAlgorithm symm = new RijndaelManaged();
ICryptoTransform transform = symm.CreateEncryptor();
CryptoStream cstream = new CryptoStream(fsOut, transform, CryptoStreamMode.Write);

BinaryReader br = new BinaryReader(fsIn);
// 读取源文件到cryptostream 
cstream.Write(br.ReadBytes((int)fsIn.Length), 0, (int)fsIn.Length);
cstream.FlushFinalBlock();
cstream.Close();
fsIn.Close();
fsOut.Close();

Console.WriteLine("created encrypted file {0}", tempfile);
Console.WriteLine("will now decrypt and show contents");

上面是一个加密的过程,也可以反向操作,来进行解密。下面的代码是一个简单的解密过程:

FileStream afsIn = File.Open(tempfile, FileMode.Open, FileAccess.Read);
transform = symm.CreateDecryptor();
cstream = new CryptoStream(fsIn, transform, CryptoStreamMode.Read);

StreamReader sr = new StreamReader(cstream);
Console.WriteLine("decrypted file text: " + sr.ReadToEnd());
fsIn.Close();

还可以如下示例代码所示:

public static string MyEncrypt(string data)
{
    byte[] bs = Encoding.UTF8.GetBytes(data);
    RijndaelManaged aes256 = new RijndaelManaged
    {
        Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012"),
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };
    return Convert.ToBase64String(aes256.CreateEncryptor().TransformFinalBlock(bs, 0, bs.Length));
}
public static string MyDecrypt(string data)
{
    byte[] bs = Convert.FromBase64String(data);
    RijndaelManaged aes256 = new RijndaelManaged
    {
        Key = Encoding.UTF8.GetBytes("12345678901234567890123456789012"),
        Mode = CipherMode.ECB,
        Padding = PaddingMode.PKCS7
    };
    return Encoding.UTF8.GetString(aes256.CreateDecryptor().TransformFinalBlock(bs, 0, bs.Length));
}
加密解密AssetBundle数据

示例代码如下:

private static string KEY = "123456_abcdeABCD";
private static string IV = "123456_abcdeABCD";

/// <summary>
/// AES加密
/// </summary>
/// <returns></returns>
private IEnumerator AES_EncryptionAB()
{
    byte[] bytes = null;
    UnityWebRequest request = new UnityWebRequest("file:///" + Application.dataPath + "/../BuildAssetBundle\\Window\\myab");
    yield return request.SendWebRequest();
    if (request.isDone && request.error == null)
        bytes = request.downloadHandler.data;
    //WWW www = new WWW("file:///" + Application.dataPath + "/../BuildAssetBundle\\Window\\myab");
    //yield return www;
    //if (www.isDone && www.error == null)
    //byte[] bytes = www.bytes;

    byte[] key = Encoding.UTF8.GetBytes(KEY);
    byte[] iv = Encoding.UTF8.GetBytes(IV);

    Aes aes = Aes.Create();
    MemoryStream memoryStream = new MemoryStream();
    ICryptoTransform crypto = aes.CreateEncryptor(key, iv);
    CryptoStream cryptoStream = new CryptoStream(memoryStream, crypto, CryptoStreamMode.Write);
    cryptoStream.Write(bytes, 0, bytes.Length);
    cryptoStream.FlushFinalBlock();

    File.WriteAllBytes(Application.dataPath + "/../BuildAssetBundle\\Window\\myab_AES_Encryption.assetbundle", memoryStream.ToArray());
}
/// <summary>
/// AES解密
/// </summary>
/// <returns></returns>
private IEnumerator AES_DncryptionAB()
{
    byte[] bytes = null;
    UnityWebRequest request = new UnityWebRequest("file:///" + Application.dataPath + "/../BuildAssetBundle\\Window\\myab_AES_Encryption.assetbundle");
    yield return request.SendWebRequest();
    if (request.isDone && request.error == null)
        bytes = request.downloadHandler.data;
    //WWW www = new WWW("file:///" + Application.dataPath + "/../BuildAssetBundle\\Window\\myab_AES_Encryption.assetbundle");
    //yield return www;
    //if (www.isDone && www.error == null)
    //    bytes = www.bytes;

    byte[] key = Encoding.UTF8.GetBytes(KEY);
    byte[] iv = Encoding.UTF8.GetBytes(IV);

    Aes aes = Aes.Create();
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(key, iv), CryptoStreamMode.Write);
    cryptoStream.Write(bytes, 0, bytes.Length);
    cryptoStream.FlushFinalBlock();

    AssetBundle ab = AssetBundle.LoadFromMemory(memoryStream.ToArray());
    GameObject go = ab.LoadAsset("Sphere") as GameObject;
    Instantiate(go, Vector3.zero, Quaternion.identity);
    ab.Unload(false);
}
加密解密网络数据

如果我有一个只想自己看到的文档,我不会简单的通过e-mail发送给你。我将使用对称算法加密它;如果有人截取了它,他们也不能阅读该文档,因为他们没有用于加密的唯一密钥。但是你也没有密钥。我需要使用某种方式将密钥给你,这样你才能解密文档,但是不能冒密钥和文档被截取的风险。
非对称算法就是一种解决方案。这类算法使用的两个密钥有如下关系:使用公共密钥加密的信息只能被相应的私有密钥解密。因此,我首要求你给我发送你的公共密钥。在发送给我的途中可能有人会截取它,但是没有关系,因为他们只能使用该密钥给你的信息加密。我使用你的公共密钥加密文档并发送给你。你使用私有密钥解密该文档,这是唯一可以解密的密钥,并且没有通过网络传递。
不对称算法比对称算法计算的花费多、速度慢。因此我们不希望在线对话中使用不对称算法加密所有信息。相反,我们使用对称算法。下面的例子中我们使用不对称加密来加密对称密钥。接着就使用对称算法加密了。实际上安全接口层(SSL)建立服务器和浏览器之间的安全对话使用的就是这种工作方式。
示例是一个TCP程序,分为服务器端和客户端。

  • 服务器端的工作流程是:
  1. 从客户端接收公共密钥。
  2. 使用公共密钥加密未来使用的对称密钥。
  3. 将加密了的对称密钥发送给客户端。
  4. 给客户端发送使用该对称密钥加密的信息。
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;

public class CryptoServer
{
    private const int RSA_KEY_SIZE_BITS = 1024;
    private const int RSA_KEY_SIZE_BYTES = 252;
    private const int TDES_KEY_SIZE_BITS = 192;

    public static void Main(string[] args)
    {
        int port;
        string msg;
        TcpListener listener;
        TcpClient client;
        SymmetricAlgorithm symm;
        RSACryptoServiceProvider rsa;
        //获取端口
        try
        {
            port = Int32.Parse(args[0]);
            msg = args[1];
        }
        catch
        {
            Console.WriteLine("USAGE");
            return;
        }
        //建立监听
        try
        {
            listener = new TcpListener(port);
            listener.Start();
            Console.WriteLine("Listening on port {0}...", port);

            client = listener.AcceptTcpClient();
            Console.WriteLine("connection....");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
            return;
        }

        try
        {
            rsa = new RSACryptoServiceProvider();
            rsa.KeySize = RSA_KEY_SIZE_BITS;

            // 获取客户端公共密钥
            rsa.ImportParameters(getClientPublicKey(client));

            symm = new TripleDESCryptoServiceProvider();
            symm.KeySize = TDES_KEY_SIZE_BITS;

            //使用客户端的公共密钥加密对称密钥并发送给客。
            encryptAndSendSymmetricKey(client, rsa, symm);

            //使用对称密钥加密信息并发送
            encryptAndSendSecretMessage(client, symm, msg);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
        finally
        {
            try
            {
                client.Close();
                listener.Stop();
            }
            catch
            {
                //错误
            }
            Console.WriteLine("Server exiting...");
        }
    }

    private static RSAParameters GetClientPublicKey(TcpClient client)
    {
        // 从字节流获取串行化的公共密钥,通过串并转换写入类的实例
        byte[] buffer = new byte[RSA_KEY_SIZE_BYTES];
        NetworkStream ns = client.GetStream();
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        RSAParameters result;

        int len = 0;
        int totalLen = 0;

        while ((len = ns.Read(buffer, 0, buffer.Length)) > 0)
        {
            totalLen += len;
            ms.Write(buffer, 0, len);
        }

        ms.Position = 0;

        result = (RSAParameters)bf.Deserialize(ms);
        ms.Close();

        return result;
    }

    private static void EncryptAndSendSymmetricKey(TcpClient client, RSACryptoServiceProvider rsa, SymmetricAlgorithm symm)
    {
        // 使用客户端的公共密钥加密对称密钥
        byte[] symKeyEncrypted;
        byte[] symIVEncrypted;

        NetworkStream ns = client.GetStream();

        symKeyEncrypted = rsa.Encrypt(symm.Key, false);
        symIVEncrypted = rsa.Encrypt(symm.IV, false);

        ns.Write(symKeyEncrypted, 0, symKeyEncrypted.Length);
        ns.Write(symIVEncrypted, 0, symIVEncrypted.Length);
    }

    private static void EncryptAndSendSecretMessage(TcpClient client, SymmetricAlgorithm symm, string secretMsg)
    {
        // 使用对称密钥和初始化矢量加密信息并发送给客户端
        byte[] msgAsBytes;
        NetworkStream ns = client.GetStream();
        ICryptoTransform transform =
        symm.CreateEncryptor(symm.Key, symm.IV);
        CryptoStream cstream = new CryptoStream(ns, transform, CryptoStreamMode.Write);

        msgAsBytes = Encoding.ASCII.GetBytes(secretMsg);

        cstream.Write(msgAsBytes, 0, msgAsBytes.Length);
        cstream.FlushFinalBlock();
    }
}
  • 客户端的工作流程是:
  1. 建立和发送公共密钥给服务器。
  2. 从服务器接收被加密的对称密钥。
  3. 解密该对称密钥并将它作为私有的不对称密钥。
  4. 接收并使用不对称密钥解密信息。
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;

public class CryptoClient
{
    private const int RSA_KEY_SIZE_BITS = 1024;
    private const int RSA_KEY_SIZE_BYTES = 252;
    private const int TDES_KEY_SIZE_BITS = 192;
    private const int TDES_KEY_SIZE_BYTES = 128;
    private const int TDES_IV_SIZE_BYTES = 128;
    public static void Main(string[] args)
    {
        int port;
        string host;
        TcpClient client;
        SymmetricAlgorithm symm;
        RSACryptoServiceProvider rsa;

        if (args.Length != 2)
        {
            Console.WriteLine("USAGE");
            return;
        }

        try
        {
            host = args[0];
            port = Int32.Parse(args[1]);
        }
        catch
        {
            Console.WriteLine("USAGE");
            return;
        }

        try //连接
        {
            client = new TcpClient();
            client.Connect(host, port);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.Write(e.StackTrace);
            return;
        }

        try
        {
            Console.WriteLine("Connected. Sending public key.");
            rsa = new RSACryptoServiceProvider();
            rsa.KeySize = RSA_KEY_SIZE_BITS;
            sendPublicKey(rsa.ExportParameters(false), client);
            symm = new TripleDESCryptoServiceProvider();
            symm.KeySize = TDES_KEY_SIZE_BITS;

            MemoryStream ms = getRestOfMessage(client);
            extractSymmetricKeyInfo(rsa, symm, ms);
            showSecretMessage(symm, ms);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.Write(e.StackTrace);
        }
        finally
        {
            try
            {
                client.Close();
            }
            catch
            { //错误
            }
        }
    }

    private static void SendPublicKey(RSAParameters key, TcpClient client)
    {
        NetworkStream ns = client.GetStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ns, key);
    }

    private static MemoryStream GetRestOfMessage(TcpClient client)
    {
        //获取加密的对称密钥、初始化矢量、秘密信息。对称密钥用公共RSA密钥
        //加密,秘密信息用对称密钥加密
        MemoryStream ms = new MemoryStream();
        NetworkStream ns = client.GetStream();
        byte[] buffer = new byte[1024];

        int len = 0;

        // 将NetStream 的数据写入内存流
        while ((len = ns.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, len);
        }
        ms.Position = 0;
        return ms;
    }

    private static void ExtractSymmetricKeyInfo(RSACryptoServiceProvider rsa, SymmetricAlgorithm symm, MemoryStream msOrig)
    {
        MemoryStream ms = new MemoryStream();

        // 获取TDES密钥--它被公共RSA密钥加密,使用私有密钥解密
        byte[] buffer = new byte[TDES_KEY_SIZE_BYTES];
        msOrig.Read(buffer, 0, buffer.Length);
        symm.Key = rsa.Decrypt(buffer, false);

        // 获取TDES初始化矢量
        buffer = new byte[TDES_IV_SIZE_BYTES];
        msOrig.Read(buffer, 0, buffer.Length);
        symm.IV = rsa.Decrypt(buffer, false);
    }

    private static void ShowSecretMessage(SymmetricAlgorithm symm, MemoryStream msOrig)
    {
        //内存流中的所有数据都被加密了
        byte[] buffer = new byte[1024];
        int len = msOrig.Read(buffer, 0, buffer.Length);

        MemoryStream ms = new MemoryStream();
        ICryptoTransform transform = symm.CreateDecryptor(symm.Key, symm.IV);
        CryptoStream cstream = new CryptoStream(ms, transform,
        CryptoStreamMode.Write);
        cstream.Write(buffer, 0, len);
        cstream.FlushFinalBlock();

        // 内存流现在是解密信息,是字节的形式,将它转换为字符串
        ms.Position = 0;
        len = ms.Read(buffer, 0, (int)ms.Length);
        ms.Close();

        string msg = Encoding.ASCII.GetString(buffer, 0, len);
        Console.WriteLine("The host sent me this secret message:");
        Console.WriteLine(msg);
    }
}