4

python中的md5以及base64加密

 2 years ago
source link: https://www.hi-roy.com/posts/python%E4%B8%AD%E7%9A%84md5%E4%BB%A5%E5%8F%8Abase64%E5%8A%A0%E5%AF%86/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python中的md5以及base64加密

2015-02-05

最近要和某公司进行系统对接,对方使用C#给出了这样一个加密函数:

public static string MD5ToBase64String(string str)
{
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] temp = System.Text.Encoding.UTF8.GetBytes(str);
    byte[] MD5 = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));//MD5
    string result = Convert.ToBase64String(MD5, 0, MD5.Length);//Base64
    return result;
    }

首先把字符串变成字节的形式,然后再对其MD5加密,最后再BASE64加密。首先注意在Python2中中文编码是个很容易出错的地方,所以要先把字符串变成unicode形式,然后再分别对其进行encode:

import hashlib
import base64
def getcode(unicxml):
    '''根据拼接后的XML生成校验码
       XML需要是unicode
    '''
    temp = unicxml.encode("utf-8")
    md5 = hashlib.md5()
    md5.update(temp)
    md5str = md5.digest()  # 16位
    b64str = base64.b64encode(md5str)
    return b64str

从流程上看算法应该是一样的,但不知为什么得出的base64码却始终不能通过验证。不得已情况下搭建了.net开发环境后发现C#中md5加密是16位,所以在python中不要使用md5.hexdigest生成32位密文。

Roy avatar
About Roy
野生程序猿,略懂Python,略懂Golang,略懂云计算,略懂大数据,略懂拳击游泳钓鱼,略懂钢琴吉他摄影。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK