使用 VBScript 實作簡單的 **XOR 流式加密**,支援任意二進位檔案 (圖片、EXE、壓縮檔),密鑰為字串循環使用。檔案大小建議 < 100KB,純教學/輕量混淆用途。
Key = "www-enun-net" ' 密鑰勿純數字
WScript.Echo Now & ", 加密: "
MyData = ReadBin("test.jpg")
EnData = Encoder(MyData)
WriteBin "E_test.jpg", EnData
WScript.Echo Now & ", 加密完成"
WScript.Echo Now & ", 解密: "
MyData = ReadBin("E_test.jpg")
UnData = Uncoder(MyData)
WriteBin "U_test.jpg", UnData
WScript.Echo Now & ", 解密完成"
' ===== 二進位檔案讀取 → Hex 字串 =====
Function ReadBin(fileName)
Dim stream, xmlDoc, node
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
Set node = xmlDoc.CreateElement("binary")
node.DataType = "bin.hex"
Set stream = CreateObject("ADODB.Stream")
stream.Type = 1: stream.Open
stream.LoadFromFile fileName
node.NodeTypedValue = stream.Read
stream.Close
ReadBin = node.Text
Set node = Nothing: Set stream = Nothing: Set xmlDoc = Nothing
End Function
' ===== Hex 字串 → 二進位檔案寫入 =====
Function WriteBin(fileName, hexStr)
Dim stream, xmlDoc, node
Set xmlDoc = CreateObject("Microsoft.XMLDOM")
Set node = xmlDoc.CreateElement("binary")
node.DataType = "bin.hex"
node.Text = hexStr
Set stream = CreateObject("ADODB.Stream")
stream.Type = 1: stream.Open
stream.Write node.NodeTypedValue
stream.SaveToFile fileName, 2 ' adSaveCreateOverWrite
stream.Close
Set stream = Nothing: Set node = Nothing: Set xmlDoc = Nothing
End Function
' ===== XOR 加密 (Hex 字串層面) =====
Function Encoder(data)
Dim keyBytes(), k, m, i, j
ReDim keyBytes(Len(Key)-1)
For n = 0 To Len(Key)-1
keyBytes(n) = Asc(Mid(Key, n+1, 1))
Next
data = UCase(data)
For i = 1 To Len(data) Step 2
m = CLng("&H" & Mid(data, i, 2))
j = ((i-1)/2) Mod Len(Key)
Encoder = Encoder & Right("0" & Hex(m Xor keyBytes(j)), 2)
Next
End Function
' ===== XOR 解密 (對稱運算) =====
Function Uncoder(data)
Dim keyBytes(), k, m, i, j
ReDim keyBytes(Len(Key)-1)
For n = 0 To Len(Key)-1
keyBytes(n) = Asc(Mid(Key, n+1, 1))
Next
data = UCase(data)
For i = 1 To Len(data) Step 2
m = CLng("&H" & Mid(data, i, 2))
j = ((i-1)/2) Mod Len(Key)
Uncoder = Uncoder & Chr(m Xor keyBytes(j))
Next
End Function
| 環節 | 技術 | 說明 |
|---|---|---|
| 二進位讀寫 | ADODB.Stream + XMLDOM.bin.hex | VBScript 原生不支援二進位字串,透過 XML 資料類型轉換 |
| 加密單位 | Byte (Hex 兩字元) | 每次處理 1 Byte,對應密鑰字串循環 |
| XOR 對稱性 | Enc = Plain XOR Key, Plain = Enc XOR Key | 加密解密邏輯完全相同 |
| 密鑰處理 | 字串各字元 ASCII 值 | 避免純數字密鑰導致低位元固定 |
System.Security.Cryptography (AES-GCM)。此腳本展示 VBScript 處理二進位資料與位元運算的技巧,**切勿用於真實機密資料保護**。