123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
- namespace Flyinsono.Client.Test
- {
- public class DllHelper
- {
- public static void EncryptDllToBin(IList<string> dllFilePathList)
- {
- byte[] key = GetKey();
- foreach (var dllFilePath in dllFilePathList)
- {
- if (!File.Exists(dllFilePath))
- {
- Logger.WriteLineInfo($"{dllFilePath} is not exist");
- continue;
- }
- Logger.WriteLineInfo($"{dllFilePath} start dllEncryption");
- // 读取 DLL 文件内容
- byte[] dllData = File.ReadAllBytes(dllFilePath);
- // 加密 DLL 数据
- byte[] encryptedData = EncryptData(dllData, key);
- string directoryPath = Path.GetDirectoryName(dllFilePath);
- var fileName = Path.GetFileNameWithoutExtension(dllFilePath);
- var binFilePath = Path.Combine(directoryPath, $"{fileName}.bin");
- var destinationFilePath = System.IO.Path.Combine(directoryPath, binFilePath);
- // 保存加密后的数据到二进制文件
- File.WriteAllBytes(destinationFilePath, encryptedData);
- Logger.WriteLineInfo($"{dllFilePath} save as {binFilePath}");
- //删除dll
- File.Delete(dllFilePath);
- }
- Logger.WriteLineInfo($"Dll Encryption Completed");
- }
- public static byte[] GetDllBytes(string binName)
- {
- byte[] encryptedData = File.ReadAllBytes(binName);
- byte[] key = GetKey();
- // 解密数据
- byte[] decryptedData = DecryptData(encryptedData, key);
- return decryptedData;
- }
- static byte[] EncryptData(byte[] data, byte[] key)
- {
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = key;
- aesAlg.IV = new byte[16]; // 使用默认 IV
- // 创建加密器并加密数据
- ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
- using (MemoryStream msEncrypt = new MemoryStream())
- {
- using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
- {
- csEncrypt.Write(data, 0, data.Length);
- csEncrypt.FlushFinalBlock();
- return msEncrypt.ToArray();
- }
- }
- }
- }
- static byte[] DecryptData(byte[] data, byte[] key)
- {
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = key;
- aesAlg.IV = new byte[16]; // 使用默认 IV
- // 创建解密器并解密数据
- ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
- using (MemoryStream msDecrypt = new MemoryStream(data))
- {
- using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
- {
- using (MemoryStream msDecrypted = new MemoryStream())
- {
- csDecrypt.CopyTo(msDecrypted);
- return msDecrypted.ToArray();
- }
- }
- }
- }
- }
- static byte[] GetKey()
- {
- //todo 读取配置
- string inputString = "vinno123";
- byte[] key = Encoding.UTF8.GetBytes(inputString);
- // 确保密钥长度符合 AES 要求
- Array.Resize(ref key, 32); // AES-256 使用 32 字节的密钥
- return key;
- }
- }
- }
|