異或運算 (^) 滿足 自逆性:A ^ B ^ B = A。即:加密與解密使用完全相同的操作。
明文: 01101001 (105 'i') 密鑰: 00110000 (48 '0') 密文: 01011001 (89 'Y') 解密: 01011001 ^ 00110000 = 01101001 → 'i'
public class XorCipher {
private final int key; // 0-255 單字節密鑰
public XorCipher(int key) {
this.key = key & 0xFF;
}
/** 加密/解密統一入口 */
public String transform(String data) {
if (data == null) return null;
char[] chars = data.toCharArray();
for (int i = 0; i < chars.length; i++) {
chars[i] = (char) (chars[i] ^ key);
}
return new String(chars);
}
/** 字節數組版本 (適合二進制數據) */
public byte[] transform(byte[] data) {
byte[] out = new byte[data.length];
for (int i = 0; i < data.length; i++) {
out[i] = (byte) (data[i] ^ key);
}
return out;
}
}
// 使用
XorCipher cipher = new XorCipher(0x3A); // 密鑰 58
String encrypted = cipher.transform("Hello World");
String decrypted = cipher.transform(encrypted);
System.out.println(encrypted); // 亂碼
System.out.println(decrypted); // Hello World
public class MultiByteXorCipher {
private final byte[] keyBytes;
public MultiByteXorCipher(String key) {
this.keyBytes = key.getBytes(StandardCharsets.UTF_8);
}
public byte[] transform(byte[] data) {
byte[] out = new byte[data.length];
for (int i = 0; i < data.length; i++) {
out[i] = (byte) (data[i] ^ keyBytes[i % keyBytes.length]);
}
return out;
}
}
| 弱點 | 攻擊手段 | 後果 |
|---|---|---|
| 密鑰重複 (單字節/短密鑰) | 頻率分析、已知明文攻擊 | 幾秒破解 |
| 無完整性校驗 | 比特翻轉攻擊 | 竄改數據無感知 |
| 無隨機性 (IV/Nonce) | 相同明文產生相同密文 | 模式洩露、重放攻擊 |
| 密鑰管理缺失 | 硬編碼、傳輸明文 | 密鑰洩露即崩潰 |
// AES-GCM (認證加密,推薦)
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
GCMParameterSpec spec = new GCMParameterSpec(128, nonce); // 12字節 nonce
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] cipherText = cipher.doFinal(plainText);
// 輸出: cipherText + nonce + authTag (或合併存儲)
異或加密以 自逆性 著稱,代碼極簡 (data[i] ^ key),但 缺乏擴散性、混淆性、完整性、前向保密 等現代密碼學基本屬性。理解其數學本質有助於掌握流密碼、分組密碼模式、認證加密等高級主題。切記:任何業務敏感數據,請直接使用 AES-GCM / ChaCha20-Poly1305 等經標準化驗證的認證加密算法。