V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
0clickjacking0
V2EX  ›  Python

关于 python3 中 chr(183)和 PHP 中的 chr(183)分别进行 base64 编码后为什么结果不一样

  •  
  •   0clickjacking0 · 2019-07-19 14:44:14 +08:00 · 2001 次点击
    这是一个创建于 1715 天前的主题,其中的信息可能已经有所发展或是发生改变。

    关于 python3 中 chr(183)和 php 中的 chr(183)分别进行 base64 编码后为什么结果不一样,我个人猜测可能是因为 python3 中的字符串不能直接进行 base64 编码,需要转换成 bytes 类型后才可以,可能是转换时候出现了问题,想问各位 v 友知道是什么情况吗

    # -*- coding: utf-8 -*-
    import base64
    a = chr(183)
    print(a)
    print(base64.b64encode(bytes(a,encoding='utf-8')))
    # 输出结果 b'wrc='
    
    <?php
    var_dump(base64_encode(chr(183)));
    //输出结果 string(4) "tw=="
    
    7 条回复    2019-07-19 15:52:10 +08:00
    lcdtyph
        1
    lcdtyph  
       2019-07-19 14:50:12 +08:00 via iPhone
    因为你 py 的代码先 encode 了一次,导致 b7 前面加上了一字节的 utf8 前缀
    0clickjacking0
        2
    0clickjacking0  
    OP
       2019-07-19 14:53:00 +08:00
    @lcdtyph 那请问该如何避免这种情况
    lcdtyph
        3
    lcdtyph  
       2019-07-19 15:10:25 +08:00
    @0clickjacking0 #2

    base64.b64encode(bytes([183]))
    0clickjacking0
        4
    0clickjacking0  
    OP
       2019-07-19 15:26:33 +08:00
    @lcdtyph 问题是我这里 183 的结果是(ord('y') + 10) ^ ord('4')得出的,而且不止这一个,我要做的是把`system`这个字符串的每一位字母取出+10,也就是平移 10 个单位,然后`system`的每一位与 key = 'a4b0a0'的每一位异或后得到的值进行 base64 编码
    kimchan
        5
    kimchan  
       2019-07-19 15:39:50 +08:00
    base64.b64encode(bytes(a,encoding='latin-1'))
    kimchan
        6
    kimchan  
       2019-07-19 15:42:24 +08:00   ❤️ 2
    是由于两边编码不一致的原因引起的. 你在 php 那边. 先对 chr(183)进行 utf8_encode 一下的话. 在 base64 编码后的就是 b'wrc=' (猜想的, 未验证)
    0clickjacking0
        7
    0clickjacking0  
    OP
       2019-07-19 15:52:10 +08:00
    @kimchan 确实是这样的,感谢老哥,我已经解决了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3348 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:43 · PVG 18:43 · LAX 03:43 · JFK 06:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.