python - 将 Lua 中的替换密码移植到 Python

标签 python string lua byte

我正在移植一个替换密码函数,它在 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

这个想法似乎很简单——将所有 ASCII 符号替换为它们在 dtable 变量中的位置对应物。

我用了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,只是根据常识在下面做出有根据的猜测。在这种特定情况下,字节串的解释似乎已关闭。

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

最佳答案

两种语言对字符串文字 "\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 中的替换密码移植到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53976135/

相关文章:

python - 带有python中键值对列表的配置文件

c# - 尝试在c#中的字符串中的字符之间添加空格

javascript - 我的代码没有正确比较两个不同的字符串

python - BeautifulSoup 无法加载网页时如何处理

python - 将 Airflow 触发的 DAG 标记为失败/成功会影响 DAG 的所有运行

python - 这段代码可以转为使用生成器而不是列表吗?

c++ - 如何在编译时隐藏DLL文件中的字符串?

Lua C API : How to get a function name?

lua - redis.call/lua 参数的动态个数

lua - 通过 Lua 创建交互式 GTK 界面