def show(self): self.generateKey(512) self.outputPublicKey('PublickeyCipher') self.outputPrivateKey('PublickeyCipher') self.inputKey('PublickeyCipher\\private.txt') print(b2i('hello'.encode('utf-8'))) x = self.Encrypt('hello'.encode('utf-8')) print(x) y = self.Decrypt(x) print(y)
def aBlockEncode(self, message128): if len(message128) != 16: print('分组消息长度错误。') message128 = b2i(message128) X = cutNumber2List(message128, 128, 32) for i in range(32): X.append(self.F(X[i], X[i + 1], X[i + 2], X[i + 3], self.rk[i])) Y = X[32::] Y = Y[::-1] Y = mergeList2Number(Y, 32) Y = i2b(Y, 128 // 8) return Y
def generateKey(self, key128): if len(key128) != 16: raise ('初始密钥长度错误。') key128 = b2i(key128) MK = cutNumber2List(key128, 128, 32) K = [] for i in range(4): K.append(MK[i] ^ self.FK[i]) for i in range(32): K.append(K[i] ^ self.T2(K[i + 1] ^ K[i + 2] ^ K[i + 3] ^ self.CK[i])) self.rk.append(K[i + 4])
def generateKey(self, key64): self.key = [] if len(key64) != 8: raise ('初始密钥长度错误。') bits = byte2bit(key64) if self.checkKey(bits) == False: return False CD = self.doPC_1(key64) CD = b2i(CD) C, D = CD >> 28, CD & 0xFFFFFFF for i in range(16): C = aCycleLeftMove(C, 28, self.SHIFT[i]) D = aCycleLeftMove(D, 28, self.SHIFT[i]) self.key.append(self.doPC_2(i2b((C << 28) | D, 56 // 8)))
def aBlockHash(self, a, b, c, d, m): A, B, C, D = a, b, c, d groups = [b2i(m[i:i + 4][::-1]) for i in range(0, len(m), 4)] for i in range(4): for j in range(16): AA, BB = A, B fout = self.fun[i](B, C, D) A, C, D = D, B, C B = addm(AA, fout) B = addm(B, groups[self.mindex[i][j]]) B = addm(B, self.T[i * 16 + j]) B = a32CycleLeftMove(B, self.lshift[i][j % 4]) B = addm(B, BB) A = addm(A, a) B = addm(B, b) C = addm(C, c) D = addm(D, d) return A, B, C, D
def lm_hash(passwd): # 用户的密码转换为大写,并转换为16进制字符串 passwd = passwd.upper().encode('utf-8') pswd = '' for i in passwd: pswd += hex(i)[2:].rjust(2, '0') passwd = pswd str_len = len(passwd) # 密码不足14字节将会用0来补全 if str_len < 28: passwd = passwd.ljust(28, '0') # 固定长度的密码被分成两个7byte部分 t_1 = passwd[0:14] t_2 = passwd[14:] # 每部分转换成比特流,并且长度位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) t_1 = hex(int(t_1, 2)) t_2 = hex(int(t_2, 2)) t_1 = t_1[2:].rjust(16, '0') t_2 = t_2[2:].rjust(16, '0') t_1 = i2b(int(t_1, 16), 8) t_2 = i2b(int(t_2, 16), 8) a = DES() a.generateKey(t_1) LM_1 = a.aBlockEncode(magic) a.generateKey(t_2) LM_2 = a.aBlockEncode(magic) LM = hex(b2i(LM_1 + LM_2))[2:].rjust(32, '0').upper() return LM
def Decrypt(self, messageBytes): if self.mode != 'private': raise ('请载入一个私钥。') return i2b(speed(b2i(messageBytes), self.d, self.n))
def Encrypt(self, messageBytes): if b2i(messageBytes) >= self.n: print('消息过长无法加密。') return i2b(speed(b2i(messageBytes), self.e, self.n))