專案需整合舊有 C++ 撰寫的 des64.dll 進行 DES 加解密,透過 P/Invoke 即可在 C# 中直接呼叫非託管 DLL。
// 原始 C++ 宣告(假設)
// void b64_des(char* in_str, char* out_str, char* key, int len, unsigned int option);
// int b64_size(int len, unsigned int option);
[DllImport("des64.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void b64_des(StringBuilder in_str, StringBuilder out_str, string key, int length, uint option);
[DllImport("des64.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int b64_size(int length, uint option);
參數說明:
in_str:輸入明文/密文字串(使用 StringBuilder 接收修改)。out_str:輸出緩衝區(同樣用 StringBuilder)。key:加密金鑰字串。length:輸入字串長度。option:0 加密,1 解密。public static string DesEncryptDecrypt(string input, string key, uint mode)
{
// 1. 計算輸出緩衝區大小
int outLen = b64_size(input.Length, mode);
// 2. 準備 StringBuilder,預設容量 255,再調整為實際長度
StringBuilder output = new StringBuilder(255);
output.Capacity = outLen;
output.Length = outLen;
// 3. 輸入緩衝區
StringBuilder src = new StringBuilder(input);
// 4. 呼叫原生函式
b64_des(src, output, key, input.Length, mode);
// 5. 回傳結果(去除可能的尾隨空白)
return output.ToString().Trim();
}
非託管函式需直接寫入記憶體緩衝區,string 為不可變型別無法滿足;StringBuilder 提供可變字元緩衝區,且能透過 Capacity/Length 控制大小,完美對應 char* 輸出參數。
string plain = "HelloWorld";
string key = "MySecretKey";
string cipher = DesEncryptDecrypt(plain, key, 0); // 加密
string decrypted = DesEncryptDecrypt(cipher, key, 1); // 解密
Console.WriteLine($"Cipher: {cipher}");
Console.WriteLine($"Decrypted: {decrypted}");
des64.dll 為 32/64 位元與專案平台一致(或放置於 bin 目錄)。stdcall 慣例,需將 CallingConvention 改為 StdCall。CharSet.Ansi 適用單位元組字元集,若 DLL 為 Unicode 需改 CharSet.Unicode。try-catch 捕捉 DllNotFoundException、EntryPointNotFoundException。