對每個字符進行定值偏移(EXP = 1235),加密時 char + EXP,解密時 char - EXP。屬於對稱加密,適合簡單配置文件、游戲數據文件的輕量級混淆。
public class DoChar {
private static final int EXP = 1235; // 偏移量,可配置化
public static void main(String[] args) {
DoChar doChar = new DoChar();
String str = "這是測試內容: abcd 123456 =-+";
System.out.println("原內容:" + str);
String encrypted = doChar.encrypt(str);
System.out.println("加密後:" + encrypted);
String decrypted = doChar.reencrypt(encrypted);
System.out.println("解密後:" + decrypted);
}
// 加密
public String encrypt(String str) {
StringBuffer buf = new StringBuffer();
char[] cs = str.toCharArray(); // 大字符串比 charAt() 效率高
for (int i = 0; i < cs.length; i++) {
char a = (char) ((int) cs[i] + EXP);
buf.append(a);
}
return buf.toString();
}
// 解密
public String reencrypt(String str) {
StringBuffer buf = new StringBuffer();
char[] cs = str.toCharArray();
for (int i = 0; i < cs.length; i++) {
char a = (char) ((int) cs[i] - EXP);
buf.append(a);
}
return buf.toString();
}
}
原內容:這是測試內容: abcd 123456 =-+
加密後:钬欂爞邨噘悌???????????????????
解密後:這是測試內容: abcd 123456 =-+
charAt() 重複邊界檢查與方法調用開銷StringBuilder 更快EXP < 65535 - 最大字符碼點⚠️ 此算法極不安全,僅適合:
生產環境敏感數據必須使用成熟加密庫:AES-GCM、ChaCha20-Poly1305、RSA-OAEP 等,並妥善管理金鑰。
byte[]),處理二進制文件EXP