zoukankan      html  css  js  c++  java
  • Python Hashlib笔记

    #python3.4
    hashlib module - A common interface to many hash functions.
    hash.digest() - Return the digest of the data passed to the update() method so far. This is a bytes object of size digest_size which may contain bytes in the whole range from 0 to 255.
    hash.hexdigest() - Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.


    注1:python 3 由于默认是 Unicode

    因此 update(arg) 中的 arg如果是字符串时,需要用b开头,例如 b"hello world!!"。


    注2:digest 和 hexdigest 的区别

    MD5为例,及校验和为128bit数据,对应16Byte 数据。但这个16Byte无法用ASCII直接表示(存储、通信等)。
    因此 使用 hexdigest 将 128bit分为 32个4bit数据,4bit数据用hex(0~9,A~F)的ASCII表示。这样对很多通信协议就好用了,也风方便 人来阅读及比较。

    举例:

    >>>import hashlib
    >>>hashlib.md5(b"hello").digest()
    b']A@*xbcK*vxb9qx9dx91x10x17xc5x92'
    >>>hashlib.md5(b"hello").hexdigest()
    '5d41402abc4b2a76b9719d911017c592'

    1、将 hexdigest拆分如下:
    5d 41 40 2a bc 4b 2a 76 b9 71 9d 91 10 17 c5 92

    2、每2为hex转换为 hex( 其中 大于0x80的无法转换,0x0~0x7F中有些也需要转移。可得
    b ' ] A @ * xbc K * v xb9 q x9d x91 x10 x17 xc5 x92。 和 digest( 就对起来了)。

    注3:HASH主要函数

    MD5 -- 128bit,SHA-1 -- 160bit, SHA-256 -- 256bit, SHA-512 -- 512bit;

    python 3.6开始 支持 SHA3相关算法。

    >>> hashlib.md5(b"").hexdigest()
    md5= d41d8cd98f00b204e9800998ecf8427e

    >>> hashlib.sha1(b"").hexdigest()
    sha1= da39a3ee5e6b4b0d3255bfef95601890afd80709

    >>> hashlib.sha256(b"").hexdigest()
    'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'

    >>> hashlib.sha512(b"").hexdigest()
    cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e 

     ============== 备注

    A、Windows下校验 文件 hash值 ( MD5,SHA1,SHA256,SHA512 必须是大写):

    certutil -hashfile filename.ext MD5
    certutil -hashfile filename.ext SHA1
    certutil -hashfile filename.ext SHA256

    B、Linux下校验 文件hash值

    参见:《【笔记】shell下的主要工具 中

    md5sum,sha1sum,sha256sum 等命令

  • 相关阅读:
    606. Construct String from Binary Tree
    557. Reverse Words in a String III
    551. Student Attendance Record I
    541. Reverse String II
    521. Longest Uncommon Subsequence I
    520. Detect Capital
    459. Repeated Substring Pattern
    人脸检测源码facedetection
    人脸检测的model类facemodel
    人脸检测解析json的工具类face_test
  • 原文地址:https://www.cnblogs.com/yvivid/p/6780843.html
Copyright © 2011-2022 走看看