【问题标题】:Porting a substitution cipher in Lua to Python将 Lua 中的替换密码移植到 Python
【发布时间】:2025-11-17 21:50:02
【问题描述】:

我正在移植一个替换密码函数,它可以解扰(解码)Lua 中的给定字符串。

function unscramble(str)
  local res = ""
  local dtable = "7,Jsg(E<\fIvBT@3_{|k\005Ww0#P\000\015\031rmG]~\030}\"xut\017X\004\016\006`+\t\001)l*\aq%ULh.6 \b\025;OQ\003\\\002\029ZN\0235\014[$e1K\027d\v4Y!^\rVi8fMc'>b:RjHA-CznS\021\028a\026\022F9o\n\018\019?yp\020=/&D2\024"
  for i = 1, #str do
    local b = str:byte(i)
    if b > 0 and b <= 127 then
      res = res .. string.char(dtable:byte(b))
    else
      res = res .. string.char(b)
    end
  end
  return res
end

这个想法似乎很简单 - 用 dtable 变量中的对应位置替换所有 ASCII 符号。

我用https://www.tutorialspoint.com/execute_lua_online.php来验证

print(unscramble("dM22r"))

Hello

我在 Python 中的最佳表现是

def unscramble(str):
    res = ''
    dtable = b"7,Jsg(E<\fIvBT@3_{|k\005Ww0#P\000\015\031rmG]~\030}\"xut\017X\004\016\006`+\t\001)l*\aq%ULh.6 \b\025;OQ\003\\\002\029ZN\0235\014[$e1K\027d\v4Y!^\rVi8fMc'>b:RjHA-CznS\021\028a\026\022F9o\n\018\019?yp\020=/&D2\024"
    for b in str:
        res += chr(dtable[b-1]) if 0 < b < 128 else chr(b)
    return res

结果

print(unscramble(b"dM22r"))

j$llF

好吧,它不起作用。问题是我根本不了解 Lua,我只是根据常识在下面做出有根据的猜测。在这种特定情况下,字节串的解释似乎是错误的。

有人能指出我正确的方向吗?

【问题讨论】:

    标签: python string lua byte


    【解决方案1】:

    两种语言对字符串文字 "\123" 的解析方式不同。 Python 将转义序列解释为八进制值为 123(十进制 83)的字符,但 Lua 将其视为十进制值为 123 的字符。您需要正确编码字节:

    bytes([
        0x37, 0x2c, 0x4a, 0x73, 0x67, 0x28, 0x45, 0x3c, 0x0c, 0x49, 0x76, 0x42, 0x54, 0x40, 0x33, 0x5f,
        0x7b, 0x7c, 0x6b, 0x05, 0x57, 0x77, 0x30, 0x23, 0x50, 0x00, 0x0f, 0x1f, 0x72, 0x6d, 0x47, 0x5d,
        0x7e, 0x1e, 0x7d, 0x22, 0x78, 0x75, 0x74, 0x11, 0x58, 0x04, 0x10, 0x06, 0x60, 0x2b, 0x09, 0x01,
        0x29, 0x6c, 0x2a, 0x07, 0x71, 0x25, 0x55, 0x4c, 0x68, 0x2e, 0x36, 0x20, 0x08, 0x19, 0x3b, 0x4f,
        0x51, 0x03, 0x5c, 0x02, 0x1d, 0x5a, 0x4e, 0x17, 0x35, 0x0e, 0x5b, 0x24, 0x65, 0x31, 0x4b, 0x1b,
        0x64, 0x0b, 0x34, 0x59, 0x21, 0x5e, 0x0d, 0x56, 0x69, 0x38, 0x66, 0x4d, 0x63, 0x27, 0x3e, 0x62,
        0x3a, 0x52, 0x6a, 0x48, 0x41, 0x2d, 0x43, 0x7a, 0x6e, 0x53, 0x15, 0x1c, 0x61, 0x1a, 0x16, 0x46,
        0x39, 0x6f, 0x0a, 0x12, 0x13, 0x3f, 0x79, 0x70, 0x14, 0x3d, 0x2f, 0x26, 0x44, 0x32, 0x18
    ])
    

    或者:

    b'7,Jsg(E<\x0cIvBT@3_{|k\x05Ww0#P\x00\x0f\x1frmG]~\x1e}"xut\x11X\x04\x10\x06`+\t\x01)l*\x07q%ULh.6 \x08\x19;OQ\x03\\\x02\x1dZN\x175\x0e[$e1K\x1bd\x0b4Y!^\rVi8fMc\'>b:RjHA-CznS\x15\x1ca\x1a\x16F9o\n\x12\x13?yp\x14=/&D2\x18'
    

    【讨论】:

    • 感谢您的洞察力!如何在 Python 中编码正确的字节(使用 Lua 字符串)?
    • @Pranasas:这是我的两个代码 sn-ps。您不能按原样使用您的字符串,因为 Python 无法解析 Lua 字符串(例如,'\129' 被视为'\12' + '9' == '\n9')。