[关闭]
@Lin-- 2020-01-02T12:39:11.000000Z 字数 5988 阅读 375

ComSec作业7-Hash-Project for SHA3

ComSec


实现一个命令行程序完成以下功能:对任意的磁盘文件,产生该文件的128或者256比特的hash值。要求如下:
1、不能直接调用Hash函数的库,要自己实现SHA3函数。
2、用命令参数控制得到的hash值存为文件或者是拷贝到粘贴板。
3、严格遵照SHA3的标准。
此作业作为“计算机安全项目”的一部分。

SHA3.py

  1. '''
  2. # File : SHA3.py
  3. # Author : Hongpei Lin
  4. # Date : 20191204
  5. # Purpose : Hash Function,input data n(any bits), output hash value l(any bits you want)
  6. '''
  7. import hashlib
  8. import numpy as np
  9. import codecs
  10. #Padding Function
  11. #Input data bits n and block unit length(n:string type;r:int type),and len(n)%8=0
  12. #Output data bits n' that is r|n'(string type)
  13. def Padding(n,r):
  14. mod=len(n)%r
  15. pad_count=r-mod
  16. if pad_count==8:
  17. n=n+"01100001"
  18. else:
  19. n=n+"011"+"0"*(pad_count-4)+"1"
  20. return n
  21. #Block Function, block the data n, get blocks of n
  22. #Input n:string type,r:int type
  23. #output: list type, which value is string type
  24. def Block(n,r):
  25. BlockList=[]
  26. index=0
  27. length_n=len(n)
  28. while index<length_n:
  29. s=n[index:index+r]
  30. news=""
  31. si=0
  32. while si<r:
  33. news+=s[si:si+64][::-1]
  34. si=si+64
  35. BlockList.append(news)
  36. index+=r
  37. return BlockList
  38. #n=1600bit, build a matrix 5*5*64;
  39. #in this matrix, I let it be a 25*64 matrix; sign row=index/5;colunm=index%5 in mind
  40. def Build_Matrix(n):
  41. n_list=[]
  42. index=0
  43. while index<len(n):
  44. n_list.append(n[index:index+64])
  45. index+=64
  46. return n_list
  47. #0 step in f Function
  48. #theta function,input 25*64matrix, oupput 25*64, both are string in list.
  49. def theta(M):
  50. T=["" for i in range(25)]
  51. for j in range(64):#all lanes compute in the same time
  52. sigma0=[0,0,0,0,0]#sigma(a[(x-1),y',z])
  53. sigma1=[0,0,0,0,0]#sigma(a[(x+1),y',(z-1)]
  54. for i in range(5):
  55. sigma0[i]=int(M[(i-1)%25][j])^int(M[(i-6)%25][j])^int(M[(i-11)%25][j])^int(M[(i-16)%25][j])^int(M[(i-21)%25][j])
  56. sigma1[i]=int(M[(i+1)%25][(j+1)%64])^int(M[(i+6)%25][(j+1)%64])^int(M[(i+11)%25][(j+1)%64])^int(M[(i+16)%25][(j+1)%64])^int(M[(i+21)%25][(j+1)%64])
  57. for i in range(25):
  58. T[i]=T[i]+str(int(M[i][j])^int(sigma0[i%5])^int(sigma1[i%5]))
  59. return T
  60. T_Table=[0,1,62,28,27,36,44,6,55,20,3,10,43,25,39,41,45,15,21,8,18,2,61,56,14]
  61. #1 step in f Function
  62. #rho function:shift in every lane
  63. #input a 25*64 matrix and T table, output a new matrix 25*64
  64. def rho(M,table):
  65. for i in range(25):
  66. s=M[i]
  67. M[i]=s[table[i]:]+s[:table[i]]
  68. return M
  69. #2 step in f Function
  70. #pi function:lane confusion
  71. #input a 25*64 matrix and T table, output a new matrix 25*64
  72. def pi(M):
  73. v_Matrix=np.array([[0, 1], [2, 3]])
  74. New_Matrix=[""for i in range(25)]
  75. for i in range(25):
  76. x,y=i%5,i//5#x=colunm;y=row
  77. Initial_Matrix=np.array([[x],[y]])
  78. N_Matrix=v_Matrix.dot(Initial_Matrix)
  79. index=int(N_Matrix[0][0]%5+(N_Matrix[1][0]%5)*5)
  80. New_Matrix[index]=New_Matrix[index]+M[i]
  81. return New_Matrix
  82. #3 step in f Function
  83. #chi function:bits transformation
  84. #input a 25*64 matrix output a new matrix 25*64
  85. def chi(M):
  86. T=["" for i in range(25)]
  87. for j in range(64):
  88. for i in range(25):
  89. row=i//5
  90. x_1,x_2=i+1,i+2#x_1=x+1,x_2=x+2 in a same row
  91. if not x_1<(row+1)*5:
  92. x_1=x_1-5
  93. if not x_2<(row+1)*5:
  94. x_2=x_2-5
  95. T[i]=T[i]+str(int(M[i][j])^(int(M[x_1][j])^1)&int(M[x_2][j]))
  96. return T
  97. #4 step in f function
  98. #iota function:transformation of first lane in every round
  99. #input a 25*64 matrix and RC and ordinal round, output a new matrix 25*64
  100. RC=[1,int('8082',16),int('800000000000808A',16),int('8000000080008000',16),
  101. int('808b',16),int('0000000080000001',16),int('8000000080008081',16),int('8000000000008009',16),
  102. int('8a',16),int('88',16),int('0000000080008009',16),int('000000008000000A',16),
  103. int('000000008000808B',16),int('800000000000008B',16),int('8000000000008089',16),int('8000000000008003',16),
  104. int('8000000000008002',16),int('8000000000000080',16),int('000000000000800A',16),int('800000008000000A',16),
  105. int('8000000080008081',16),int('8000000000008080',16),int('0000000080000001',16),int('8000000080008008',16)]
  106. def iota(M,Rc,i):
  107. M[0]=bin(int(M[0],2)^Rc[i])[2:]
  108. pad_count=64-len(M[0])#padding, let string len=64
  109. zero="0"*pad_count
  110. M[0]=zero+M[0]
  111. return M
  112. #f function, input 1600bits string,output 1600bits string
  113. def f(s):
  114. s_Matrix=Build_Matrix(s)
  115. for i in range(24):#24 rounds
  116. s_Matrix=iota(chi(pi(rho(theta(s_Matrix),T_Table))),RC,i)
  117. news=""
  118. for i in s_Matrix:
  119. news+=i
  120. return news
  121. def absorbing(s,r):
  122. s=Padding(s,r)#padding
  123. P_list=Block(s,r)#block
  124. c="0"*(1600-r)
  125. news="0"*1600#initial s
  126. for i in range(len(P_list)):
  127. P_list[i]=P_list[i]+c
  128. news=bin(int(P_list[i],2)^int(news,2))[2:]
  129. pad_count=1600-len(news)#padding , let string len=1600
  130. zero="0"*pad_count
  131. news=zero+news
  132. news=f(news)
  133. return news
  134. def squeezing(s,r,l):
  135. b=s[:r]
  136. i64,i8=0,0
  137. templist=[]
  138. while i64<len(b):
  139. temp_b=b[i64:i64+64]
  140. i8state=i8+64
  141. while i8state>i8:
  142. templist.append(b[i8state-8:i8state])
  143. i8state-=8
  144. i8+=64
  145. i64+=64
  146. news=""
  147. for i in templist:
  148. news+=i
  149. if not l>r:
  150. return news[:l]
  151. BlockCount=l//r+1
  152. while BlockCount:
  153. b=f(b)
  154. templist=[]
  155. i64,i8=0,0
  156. while i64<len(b):
  157. temp_b=b[i64:i64+64]
  158. i8state=i8+64
  159. while i8state>i8:
  160. templist.append(b[i8state-8:i8state])
  161. i8state-=8
  162. i8+=64
  163. i64+=64
  164. for i in templist:
  165. news+=i
  166. BlockCount-=1
  167. return news[:l]
  168. def HashSHA3(s,l):
  169. s=absorbing(s,1600-l-l)
  170. s=squeezing(s,1600-l-l,l)
  171. s=hex(int(s,2))[2:]
  172. while len(s)<l//4:
  173. s="0"+s
  174. return s
  175. def MakeSHA3(filename,l):
  176. fr=codecs.open(filename,"r",encoding='utf-8')
  177. msg=fr.read()
  178. fr.close()
  179. msgstream=""
  180. for i in msg:
  181. temp=bin(ord(i))[2:]
  182. while not temp%8==0:
  183. temp="0"+temp
  184. msgstream+=temp
  185. hashvalue=HashSHA3(msgstream,l)
  186. fw=codecs.open("HashFile.txt","w",encoding='utf-8')
  187. fw.write(hashvalue)
  188. fw.close()
  189. return True

SHA3CMD.py

  1. '''
  2. # File : SHA3CMD.py
  3. # Author : Hongpei Lin
  4. # Date : 20191211
  5. # Purpose : Hash software, input a filname, output a hash value, and write it in another file
  6. '''
  7. import sys
  8. import getopt
  9. import SHA3
  10. import codecs
  11. def __main__(argv):
  12. Hashlen=256
  13. filename=""
  14. try:
  15. opts,args=getopt.getopt(argv,"hf:l:",["help","file=","len="])
  16. except getopt.GetoptError:
  17. print("ERROR:SHA3CMD.py -l <224/256/384/512 or others> -f <filename>")
  18. print(" or:SHA3CMD.py --len=<224/256/384/512 or others> --file=<filename>")
  19. sys.exit(2)
  20. for opt,arg in opts:
  21. if opt in ("-h","--help"):
  22. print("Please input in these format")
  23. print("SHA3CMD.py -l <224/256/384/512 or other number> -f <filename>")
  24. print("SHA3CMD.py -len=<224/256/384/512 or other number> --file=<filename>")
  25. sys.exit()
  26. elif opt in ("-l","--len"):
  27. try:
  28. Hashlen=eval(arg)
  29. except NameError as err:
  30. print("Please input in these format")
  31. print("ERROR:SHA3CMD.py -l <224/256/384/512 or other number> -f <filename>")
  32. print(" or:SHA3CMD.py -len=<224/256/384/512 or other number> --file=<filename>")
  33. sys.exit()
  34. elif opt in ("-f","--file"):
  35. filename=arg
  36. if SHA3.MakeSHA3(filename,Hashlen):
  37. print("Hash Successfully!\n Hash reslut has been writen in HashFile.txt")
  38. else:
  39. print("Sorry! I have some BUGS!")
  40. if __name__=="__main__":
  41. __main__(sys.argv[1:])
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注