关于SHA1的知识点,好多文章介绍的很详细,我在这里分享一下直接用python实现的SHA1算法,和大家一起交流学习
首先和大家介绍一下sha1:
SHA-1(英语:Secure Hash Algorithm 1,中文名:安全散列算法1)是一种密码散列函数。SHA-1可以生成一个被称为消息摘要的160位(20字节)散列值,散列值通常的呈现形式为40个十六进制数。
一下是代码段
#初始化变量
K = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6]
A = 0x67452301
B = 0xEFCDAB89
C = 0x98BADCFE
D = 0x10325476
E = 0xC3D2E1F0
A0 = 0x67452301
B0 = 0xEFCDAB89
C0 = 0x98BADCFE
D0 = 0x10325476
E0 = 0xC3D2E1F0
'''字节转换,字节(8bit)->字(32bit)'''
def CharToWord( context,i):
return ((ord(context[i]) & 0x000000ff) << 24) | ((ord(context[i + 1]) & 0x000000ff) << 16) | ((ord(context[i + 2]) & 0x000000ff) << 8) | (ord(context[i + 3]) & 0x000000ff)
'''填充补位获得原始明文'''
def SHA1_fill(plaintext, group, length):
print("补位后的明文:")
text1 = list(plaintext)
for n in range(length//8, 56):
text1.append(chr(0))
plaintext=''.join(text1)
temp = length // 32
len1 = length
while len1 > 0:
len1 = len1//32
if len1:
for j in range(0, temp):
group[j] = CharToWord(plaintext, 4 * j)
print(hex(group[j]))
else:
text = list(plaintext)
b = 0x80
text.insert(length // 8, chr(b))
plaintext = ''.join(text)
group[temp] = CharToWord(plaintext, temp * 4)
print(hex(group[temp]))
break
group[15] = length
for i in range(temp + 1,16):
print(hex(group[i]).ljust(10, '0'))
'''f函数'''
def f(B ,C ,D , t):
if t >=0 and t <= 19:
return (B & C) ^ (~B & D)
if t >= 20 and t <= 39:
return B ^ C ^ D
if t >= 40 and t <= 59:
return (B & C) ^ (B & D) ^ (C & D)
if t >= 60 and t <= 79:
return B ^ C ^ D
'''获得 Kt'''
def GETK(t):
if t >= 0 and t <= 19:
return K[0]
if t >= 20 and t <= 39:
return K[1]
if t >= 40 and t <= 59:
return K[2]
if t >= 60 and t <= 79:
return K[3]
'''获得 Wt ,这里要特别注意mod(2**32)'''
def GETW(w):
for i in range(16,80):
w[i] = (((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) << 1) | ((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) >> 31)) % 2**32
'''步函数,注意mod(2**32)'''
def Step(t,w):
global A
global B
global C
global D
global E
T = (((A << 5) | (A >> 27)) + f(B, C, D, t) + E + w[t] + GETK(t)) % 2**32
E = D
D = C
C = ((B << 30) | (B >> 2)) % 2**32
B = A
A = T
'''获得密文'''
def GetCipher(cipher):
cipher[0] = (A0 + A) % 2**32
cipher[1] = (B0 + B) % 2**32
cipher[2] = (C0 + C) % 2**32
cipher[3] = (D0 + D) % 2**32
cipher[4] = (E0 + E) % 2**32
print("密文为:")
for j in range(0, 5):
print(hex(cipher[j])[2:], end='')
print()
def SHA1(context, cipher):
len1 = len(context) * 8
group = []
for i in range(80):
group.append(0)
SHA1_fill(context, group, len1)
GETW(group)
for t in range(80):
Step(t, group)
GetCipher(cipher)
m = input("请输入长度小于56的明文:")
c = []
for i in range(0, 5):
c.append(0)
SHA1(m, c)
'''以下为python自带sha1函数,以便对照'''
import hashlib
print("自带函数哈希后密文:")
b = hashlib.sha1()
b.update(m.encode())
sha1 = b.hexdigest()
print(sha1)
以下是运行结果:
上述代码如果有什么 不足之处还请大佬们见谅,还有什么待完善之处,欢迎大家批评指正!