本專案 Encryption_Demo 以程式碼模擬「採用安全認證的資訊加密流程圖」與「解密流程圖」,旨在教學示範完整加密流程的運作邏輯,僅限於程式內部資料傳遞模擬,不涉及實際網路傳輸。
圖一:採用安全認證的資訊加密流程圖
圖二:採用安全認證技術的資訊解密過程圖
圖三:加密流程文字說明
圖四:解密流程文字說明
程式核心在於精確計算各區塊在合併密文中的位移。採用算法如下:
// 合併密文結構
加密後的會話密文 (RsaEncryptData) : 1152 bytes
摘要簽章資料 (CombinData) : 144 bytes (128+8+8)
中間加密資料 (EncryptionData) : 總長度 - 1152 - 144
檔案雜湊長度 : 16 bytes
接收時間 : 23 bytes (固定格式:yyyy-MM-dd HH:mm:ss-ms)
簽名長度 : 128 bytes
總計 : 167 bytes
public static byte[] GetTimeNow() {
DateTime now = DateTime.Now;
UTF8Encoding utf = new UTF8Encoding();
string month = now.Month < 10 ? "0" + now.Month : now.Month.ToString();
string day = now.Day < 10 ? "0" + now.Day : now.Day.ToString();
string ms;
if (now.Millisecond < 10) ms = "00" + now.Millisecond;
else if (now.Millisecond < 100) ms = "0" + now.Millisecond;
else ms = now.Millisecond.ToString();
string full = $"{now.Year}-{month}-{day} {now.ToLongTimeString()}-{ms}";
// 例:2004-11-09 13:04:28-108
return utf.GetBytes(full); // 固定 23 位元組
}
int length = (int)fs.Length - 1296; // 1152 + 144
byte[] Encrypt_Two = new byte[length];
Buffer.BlockCopy(fileContent, 1152, Encrypt_Two, 0, length);
byte[] Encrypt_One = new byte[1152];
fs.Read(Encrypt_One, 0, 1152); // 從開頭讀取
// 讀取中間段
int length = (int)fs.Length - 1296;
byte[] Encrypt_Two = new byte[length];
fs.Position = 1152; // 移動至偏移量
fs.Read(Encrypt_Two, 0, length);
注意:fs.Read(buffer, offset, count) 中 offset 是陣列寫入起始位置,count 是讀取位元組數,不可寫成 fs.Read(Encrypt_Two, length, length) 否則會報錯。
程式將所有功能封裝於靜態類別,測試需三組金鑰對:傳送者 (A)、接收者 (B)、時間戳服務器 (DTS)。
預設金鑰存放於 Encryption Demo\bin\Release 目錄下三個資料夾,亦可透過介面按鈕「產生一組金鑰」自行建立。
金鑰產生介面
步驟一:開啟檔案並提交至 DTS
步驟二:加密處理(需正確選擇金鑰檔)
步驟三:解密還原
若需更換演算法(如 AES/Rijndael、SHA-512),必須重新計算所有位元組偏移量。原始碼註解較簡略,歡迎進一步優化。