cipher method

String cipher(
  1. String text,
  2. int shift, {
  3. bool decrypt = false,
})

恺撒密码加/解密算法

  • shift: 加密位移量,通常由 passphrase 的长度决定

该方法仅对 ASCII 可打印字符 (32~126) 生效,跳过中文/emoji 等字符

Implementation

String cipher(String text, int shift, {bool decrypt = false}) {
  const int base = 32;
  const int range = 95;

  final actualShift = decrypt ? -shift : shift;

  return String.fromCharCodes(text.runes.map((int code) {
    if (code >= base && code <= base + range - 1) {
      return ((code - base + actualShift) % range + range) % range + base;
    } else {
      return code;
    }
  }));
}