def decrypt_with_iv(self, key, iv, encrypted_data): if self.grep11ServerStub == 0: return None # no ZHSM, defaulting to the software AES ep11key = self.ep11key(key) print("pyep11.AES.decrypt: key=" + key.hex()) cipherInitInfo = server_pb2.DecryptInitRequest( Mech=pkcs11_pb2.Mechanism(Mechanism=ep11.CKM_AES_CBC_PAD, Parameter=iv), Key=ep11key) cipherState = self.grep11ServerStub.DecryptInit(cipherInitInfo) cipherData = server_pb2.DecryptUpdateRequest(State=cipherState.State, Ciphered=encrypted_data) cipherState = self.grep11ServerStub.DecryptUpdate(cipherData) plaintext = cipherState.Plain[:] cipherData.State = cipherState.State cipherData.Ciphered = b'' cipherState = self.grep11ServerStub.DecryptFinal(cipherData) plaintext = plaintext + cipherState.Plain[:] print("Decrypted message " + plaintext.hex()) print("Encrypted message " + encrypted_data.hex()) return plaintext
def encrypt_with_iv(self, key, iv, data): if self.grep11ServerStub == 0: return None # no ZHSM, defaulting to the software AES ep11key = self.ep11key(key) print("pyep11.AES.encrypt: key=" + key.hex()) cipherInitInfo = server_pb2.EncryptInitRequest( Mech=pkcs11_pb2.Mechanism(Mechanism=ep11.CKM_AES_CBC_PAD, Parameter=iv), Key=ep11key) cipherState = self.grep11ServerStub.EncryptInit(cipherInitInfo) # print("cipherState.StateOut: " + cipherState.StateOut.hex()) # print("cipherState.DataOut: " + cipherState.DataOut.hex()) cipherData = server_pb2.EncryptUpdateRequest(State=cipherState.State, Plain=data) # print("total size: " + str(len(plain[:].decode()))) # print("first size: " + str(len(cipherData.DataIn.decode())) + " " + cipherData.DataIn.decode()) cipherState = self.grep11ServerStub.EncryptUpdate(cipherData) # print("cipherState.StateOut: " + cipherState.StateOut.hex()) # print("cipherState.DataOut: " + cipherState.DataOut.hex()) ciphertext = cipherState.Ciphered[:] cipherData.State = cipherState.State cipherData.Plain = b'' # print("third size: " + str(len(cipherData.DataIn.decode())) + " " + cipherData.DataIn.decode()) cipherState = self.grep11ServerStub.EncryptFinal(cipherData) # print("cipherState.StateOut: " + cipherState.StateOut.hex()) # print("cipherState.DataOut: " + cipherState.DataOut.hex()) ciphertext = ciphertext + cipherState.Ciphered[:] print("Original message " + data.hex()) print("Encrypted message " + ciphertext.hex()) return ciphertext
def ep11key(self, grep11ServerStub, key): print("pyep11.ep11key: key=" + key.hex()) if len(key) not in (16, 24, 32): raise ValueError('Invalid key size') self.dbopen() try: self.cursor.execute("SELECT ep11key FROM keystore WHERE key=?", (key, )) result = self.cursor.fetchall() if len(result) == 0: r = server_pb2.GenerateKeyRequest(Mech=pkcs11_pb2.Mechanism( Mechanism=ep11.CKM_AES_KEY_GEN)) r.Template[ep11.CKA_VALUE_LEN] = (16).to_bytes( 8, byteorder=endian) r.Template[ep11.CKA_WRAP] = (0).to_bytes(1, byteorder=endian) r.Template[ep11.CKA_UNWRAP] = (0).to_bytes(1, byteorder=endian) r.Template[ep11.CKA_ENCRYPT] = (1).to_bytes(1, byteorder=endian) r.Template[ep11.CKA_DECRYPT] = (1).to_bytes(1, byteorder=endian) r.Template[ep11.CKA_EXTRACTABLE] = (0).to_bytes( 1, byteorder=endian) r.Template[ep11.CKA_TOKEN] = (1).to_bytes(1, byteorder=endian) generateKeyStatus = grep11ServerStub.GenerateKey(r) ep11key = generateKeyStatus.Key encoded = str(binascii.hexlify(ep11key)) print("ep11key generated key=" + key.hex() + " ep11key=" + ep11key.hex()) # INSERT self.cursor.execute( "INSERT INTO keystore VALUES (:key, :ep11key)", { 'key': key, 'ep11key': ep11key }) elif len(result) == 1: ep11key = result[0][0] print("ep11key found key=" + key.hex() + " ep11key=" + ep11key.hex()) else: print("ep11key found multiple keys unexpectedly\n") sys.exit(-1) except sqlite3.Error as e: print('sqlite3.Error occurred:', e.args[0]) sys.exit(-1) self.dbclose() return ep11key
def decrypt_with_iv(self, key, iv, encrypted_data): # return None if there is no ZHSM if not self.channel: print("no grpc channel configured") return None grep11ServerStub = server_pb2_grpc.CryptoStub(self.channel) try: ep11key = self.ep11key(grep11ServerStub, key) print("pyep11.AES.decrypt: key=" + key.hex()) request = server_pb2.DecryptSingleRequest( Mech=pkcs11_pb2.Mechanism(Mechanism=ep11.CKM_AES_CBC_PAD, Parameter=iv), Key=ep11key, Ciphered=encrypted_data) cipherState = grep11ServerStub.DecryptSingle(request) plaintext = cipherState.Plain[:] if len(plaintext) < 128: print("Decrypted message " + str(plaintext)) else: print("Decrypted message " + "..........................") #print("Decrypted message " + plaintext.hex()) #print("Encrypted message " + encrypted_data.hex()) return plaintext except grpc.RpcError as rpc_error: print( f'decrypt_with_iv: RPC failed with code {rpc_error.code()}: {rpc_error}' ) print('grpc error code=' + str(rpc_error._state.code) + ' ' + str(type(rpc_error._state.code))) raise HpcsError() except Exception as e: exc_type, exc_obj, tb = sys.exc_info() lineno = tb.tb_lineno print('Unexpected error: ' + str(e) + ' ' + str(type(e)) + ' at ' + str(lineno)) raise HpcsError()
def encrypt_with_iv(self, key, iv, data): # return None if there is no ZHSM if not self.channel: return None grep11ServerStub = server_pb2_grpc.CryptoStub(self.channel) try: ep11key = self.ep11key(grep11ServerStub, key) print("pyep11.AES.encrypt: key=" + key.hex()) request = server_pb2.EncryptSingleRequest( Mech=pkcs11_pb2.Mechanism(Mechanism=ep11.CKM_AES_CBC_PAD, Parameter=iv), Key=ep11key, Plain=data) cipherState = grep11ServerStub.EncryptSingle(request) ciphertext = cipherState.Ciphered[:] if len(data) < 128: print("Original message " + str(data)) else: print("Original message " + "..........................") #print("Original message " + data.hex()) #print("Encrypted message " + ciphertext.hex()) return ciphertext except grpc.RpcError as rpc_error: print( f'encrypt_with_iv: RPC failed with code {rpc_error.code()}: {rpc_error}' ) print('grpc error code=' + str(rpc_error._state.code) + ' ' + str(type(rpc_error._state.code))) return None except Exception as e: exc_type, exc_obj, tb = sys.exc_info() lineno = tb.tb_lineno print('Unexpected error: ' + str(e) + ' ' + str(type(e)) + ' at ' + str(lineno)) return None
def ep11key(self, key): self.dbopen() try: self.cursor.execute("SELECT ep11key FROM keystore WHERE key=?", (key, )) result = self.cursor.fetchall() # print(result) if len(result) == 0: temp = [ pkcs11_pb2.Attribute(Type=ep11.CKA_VALUE_LEN, Value=(16).to_bytes( 8, byteorder=endian)), pkcs11_pb2.Attribute(Type=ep11.CKA_WRAP, Value=(0).to_bytes(1, byteorder=endian)), pkcs11_pb2.Attribute(Type=ep11.CKA_UNWRAP, Value=(0).to_bytes(1, byteorder=endian)), pkcs11_pb2.Attribute(Type=ep11.CKA_ENCRYPT, Value=(1).to_bytes(1, byteorder=endian)), pkcs11_pb2.Attribute(Type=ep11.CKA_DECRYPT, Value=(1).to_bytes(1, byteorder=endian)), pkcs11_pb2.Attribute(Type=ep11.CKA_EXTRACTABLE, Value=(0).to_bytes(1, byteorder=endian)), pkcs11_pb2.Attribute(Type=ep11.CKA_TOKEN, Value=(1).to_bytes(1, byteorder=endian)) ] generateKeyInfo = server_pb2.GenerateKeyInfo( Mech=pkcs11_pb2.Mechanism(Mechanism=ep11.CKM_AES_KEY_GEN), Template=temp) generateKeyStatus = self.grep11ServerStub.GenerateKey( generateKeyInfo) ep11key = generateKeyStatus.Key encoded = str(binascii.hexlify(ep11key)) print("ep11key generated key=" + key.hex() + " ep11key=" + ep11key.hex()) # INSERT self.cursor.execute( "INSERT INTO keystore VALUES (:key, :ep11key)", { 'key': key, 'ep11key': ep11key }) elif len(result) == 1: # ep11key = int(result[0][0], 16) ep11key = result[0][0] # ep11key = binascii.unhexlify(bytes(encoded)) print("ep11key found key=" + key.hex() + " ep11key=" + ep11key.hex()) else: print("ep11key found multiple keys unexpectedly\n") sys.exit(-1) except sqlite3.Error as e: print('sqlite3.Error occurred:', e.args[0]) self.dbclose() return ep11key # cls.keyStore[key]