TDIB.EncryptDecrypt 以對稱演算法對影像像素資料進行加密/解密,同一方法雙向操作(再次呼叫即解密)。本文提供單鍵加密解密的最小範例。

unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DIB, StdCtrls;
type
TForm1 = class(TForm)
DXPaintBox1: TDXPaintBox;
Button1: TButton; // 載入圖片
Button2: TButton; // 加密/解密
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var Form1: TForm1;
implementation {$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
const ImgPath1 = 'C:\Temp\DX.jpg';
begin
DXPaintBox1.DIB.LoadFromFile(ImgPath1);
DXPaintBox1.Width := DXPaintBox1.DIB.Width;
DXPaintBox1.Height := DXPaintBox1.DIB.Height;
DXPaintBox1.Repaint;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
// EncryptDecrypt(Key: Integer)
DXPaintBox1.DIB.EncryptDecrypt(0); // 金鑰 0
DXPaintBox1.Repaint;
end;
end.
⚠️ 此方法屬於**混淆**而非加密。專業逆向工程可輕易破解。真正需要機密性請使用 AES-GCM、ChaCha20-Poly1305 等經驗證的加密庫,對整個檔案流加密而非僅像素資料。
procedure EncryptDIBEx(DIB: TDIB; Password: string);
var Key: Integer; Hash: Integer; i: Integer;
begin
// 簡易密碼派生
Hash := 0; for i := 1 to Length(Password) do Hash := Hash * 31 + Ord(Password[i]);
Key := Hash xor $AA55AA55;
// 分塊加密(不同區域用不同金鑰變體)
DIB.EncryptDecrypt(Key);
// 可進一步:按 64x64 區塊,Key = Key xor (BlockX * 17 + BlockY * 23)
end;