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
ge2009
V2EX  ›  Python

请教这段 C#的代码怎么改写成 Python

  •  
  •   ge2009 · 2018-01-20 16:34:42 +08:00 · 3646 次点击
    这是一个创建于 2260 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教这段 C#的代码怎么改写成 Python

    public class Encrypt
    {
    	public static string DoEncrypt(string ls_input)
    	{
    		MD5 mD = new MD5CryptoServiceProvider();
    		ls_input = string.Format("aaa{0}bbb", ls_input);
    		byte[] bytes = Encoding.Unicode.GetBytes(ls_input);
    		byte[] array = mD.ComputeHash(bytes);
    		string text = null;
    		for (int i = 0; i < array.Length; i++)
    		{
    			text += array[i].ToString("x");
    		}
    		return string.Format("bkSystem_{0}", text);
    	}
    }
    
    
    

    我自己写了一段,不过加密出来的值和 C#生成的值不一样,还请帮忙改下

    import hashlib
    
    data = '[{"lxdh":"134859393","content":"testbk"}]'
    
    def encrypt(input):
        is_input = 'aaa%sbbb' %input
        print (is_input)
        is_input = hashlib.md5(is_input.encode('utf-8')).hexdigest()
        is_input = 'bkSystem_' + is_input
    
        print(is_input)
    
    
    encrypt(data)
    
    
    
    
    8 条回复    2018-01-22 11:14:30 +08:00
    huntzhan
        1
    huntzhan  
       2018-01-20 17:13:20 +08:00
    不帮
    jalena
        2
    jalena  
       2018-01-20 17:19:20 +08:00
    不帮
    geelaw
        3
    geelaw  
       2018-01-20 17:30:14 +08:00   ❤️ 4
    byte[] bytes = Encoding.Unicode.GetBytes(ls_input);

    is_input.encode('utf-8')

    是什么让你觉得 Unicode = UTF-8 ?在 Windows 语境下,Unicode 是 UTF16LE。
    ge2009
        4
    ge2009  
    OP
       2018-01-20 22:14:55 +08:00
    @geelaw 嗯,看来是 Windows 上 Unicode 和 Python 上转化的区别,不过好像 UTF16LE 也是不对的,不知道该用什么字符集合适
    ge2009
        5
    ge2009  
    OP
       2018-01-20 23:15:49 +08:00
    @geelaw 非常感谢,确实像你说的一样,我把 utf-8 改成 utf-16LE 就已经编码一致了,再一次感谢.
    JacketPC
        6
    JacketPC  
       2018-01-21 11:07:24 +08:00   ❤️ 1
    UTF-8 ~~哦。。楼上有人答了啊。。
    ge2009
        7
    ge2009  
    OP
       2018-01-21 16:34:57 +08:00
    @JacketPC 嗯,是的
    ge2009
        8
    ge2009  
    OP
       2018-01-22 11:14:30 +08:00
    @JacketPC
    @geelaw
    不好意思,我再请教下,我加密出来的东西好像基本一致,就是有时候会和 c#生成的多出来一至两个 0 是什么情况?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3386 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:39 · PVG 18:39 · LAX 03:39 · JFK 06:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.