You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
guet10086/hash_algorithm.py

79 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import binascii
import hashlib
from pyDes import *
from passlib.hash import lmhash
from Crypto.Hash import MD4
# def DesEncrypt(str, Des_Key):
# k = des(Des_Key, ECB, pad=None)
# EncryptStr = k.encrypt(str)
# return binascii.b2a_hex(EncryptStr)
# def Zero_padding(str):
# b = []
# l = len(str)
# num = 0
# for n in range(l):
# if (num < 8) and n % 7 == 0:
# b.append(str[n:n + 7] + '0')
# num = num + 1
# return ''.join(b) p
def LM_Hash(plaintext):
"""
注释部分为轮子代码实现,但是调用库执行效率高点,就不用了
"""
# test_str = plaintext
# # 用户的密码转换为大写,并转换为16进制字符串
# test_str = test_str.upper().encode('utf-8').hex()
# str_len = len(test_str)
# # print("str_len = ",str_len)
# # 密码不足14字节将会用0来补全
# if str_len < 28: test_str = test_str.ljust(28, '0')
# # 固定长度的密码被分成两个7byte部分
# t_1 = test_str[0:len(test_str) // 2]
# t_2 = test_str[len(test_str) // 2:]
# # 每部分转换成比特流并且长度位56bit长度不足使用0在左边补齐长度
# t_1 = bin(int(t_1, 16)).lstrip('0b').rjust(56, '0')
# t_2 = bin(int(t_2, 16)).lstrip('0b').rjust(56, '0')
# # 再分7bit为一组末尾加0组成新的编码
# t_1 = Zero_padding(t_1)
# t_2 = Zero_padding(t_2)
# # print (t_1,t_2)
# t_1 = hex(int(t_1, 2))
# t_2 = hex(int(t_2, 2))
# t_1 = t_1[2:]
# t_2 = t_2[2:]
# if '0' == t_2:
# t_2 = "0000000000000000"
# t_1 = binascii.a2b_hex(t_1)
# t_2 = binascii.a2b_hex(t_2)
# # 上步骤得到的8byte二组分别作为DES key为"KGS!@#$%"进行加密。
# LM_1 = DesEncrypt("KGS!@#$%", t_1)
# LM_2 = DesEncrypt("KGS!@#$%", t_2)
# # 将二组DES加密后的编码拼接得到最终LM HASH值。
# LM = LM_1 + LM_2
LM2 = lmhash.hash(plaintext)
# return LM
return LM2.encode('utf-8')
# print(LM)
def NTLM_Hash(plaintext):
#,nthash.hash(plaintext).encode('utf-8')
return binascii.hexlify(MD4.new(plaintext.encode("utf-16le")).digest())
def MD5_Hash(plaintext):
return binascii.hexlify(hashlib.md5(plaintext.encode('utf-8')).digest())
def SHA1_Hash(plaintext):
return binascii.hexlify(hashlib.sha1(plaintext.encode('utf-8')).digest())
def SHA256_Hash(plaintext):
return binascii.hexlify(hashlib.sha256(plaintext.encode('utf-8')).digest())
# b = '123456'
# a = NTLM_Hash(b)
# c = LM_Hash(b)
# print(a,c,type(a),type(c))