Python中的Sha1是否接受整数?

1 投票
1 回答
1534 浏览
提问于 2025-04-17 11:15

如何在hashlib.sha1(int)中使用整数。请看下面的代码,我把IP当作字符串,然后转换成整数,但hash.sha1不接受整数...

 import hashlib
 import socket
 import struct
  class blommy(object):
   def __init__(self):
    self.bitarray= [0]*2048

  def hashes(self,ip):
    #convert decimal dotted quad string to long integer"
    intip= struct.unpack('>L',socket.inet_aton(ip))[0]
    index = [0, 1]
    hbyte = hashlib.sha1(intip) # how to take sha1 of integer??
    index[0] = ord(hbyte[0])| ord(hbyte[1])<< 8
    index[1] = ord(hbyte[2])| ord(hbyte[3])<< 8

需要把这段C代码转换成Python。请给点建议,上面的部分代码已经写好了。如果我把IP当作整数使用,就无法计算sha1,即使我用socket转换IP,sha1也不接受,这有什么建议吗?请看下面的评论。

//fixed parameters
k = 2

m = 256*8

  //the filter
  byte[m/8] bloom   ## 

 function insertIP(byte[] ip) {

byte[20] hash = sha1(ip)

int index1 = hash[0] | hash[1] << 8 # how to in python?
int index2 = hash[2] | hash[3] << 8

// truncate index to m (11 bits required)
index1 %= m  ## ?
index2 %= m  ## ?

// set bits at index1 and index2
bloom[index1 / 8] |= 0x01 << index1 % 8   ## ??
bloom[index2 / 8] |= 0x01 << index2 % 8   ## ??
}

 // insert IP 192.168.1.1 into the filter:
    insertIP(byte[4] {192,168,1,1})

1 个回答

0

你的问题的答案是否定的,你可以计算字符串的哈希值,但不能直接计算整数的哈希值。你可以试试下面的做法:

hashlib.sha1(str(1234)).digest()

这样可以把你的整数转换成字符串,然后再计算它的哈希值。

撰写回答