def _to_bin(dct): for k in dct.keys(): if strng.is_text(dct[k]): dct[k] = dct[k].encode(encoding) if keys_to_bin: return {(k.encode(encoding) if strng.is_text(k) else k): v for k, v in dct.items()} return dct
def dict_keys_to_bin(dct, encoding='utf-8', errors='strict'): """ Returns dict where all keys are converted to binary strings. Only works for keys in a "root" level of the dict. """ return {(k.encode(encoding, errors=errors) if strng.is_text(k) else k): v for k, v in dct.items()}
def __init__( self, CreatorID=None, BackupID='', BlockNumber=0, SessionKey='', SessionKeyType=None, LastBlock=True, Data=b'', EncryptKey=None, DecryptKey=None, EncryptedSessionKey=None, EncryptedData=None, Length=None, Signature=None, ): self.CreatorID = CreatorID if not self.CreatorID: self.CreatorID = my_id.getLocalID() if not isinstance(self.CreatorID, id_url.ID_URL_FIELD): self.CreatorID = id_url.field(self.CreatorID) self.BackupID = strng.to_text(BackupID) self.BlockNumber = BlockNumber self.LastBlock = bool(LastBlock) self.SessionKeyType = SessionKeyType or key.SessionKeyType() if EncryptedSessionKey: # this block to be decrypted after receiving self.EncryptedSessionKey = EncryptedSessionKey else: # this block to be encrypted before sending if callable(EncryptKey): self.EncryptedSessionKey = EncryptKey(SessionKey) elif strng.is_text(EncryptKey): self.EncryptedSessionKey = my_keys.encrypt( EncryptKey, SessionKey) elif strng.is_bin(EncryptKey): self.EncryptedSessionKey = my_keys.encrypt( strng.to_text(EncryptKey), SessionKey) else: self.EncryptedSessionKey = key.EncryptLocalPublicKey( SessionKey) if EncryptedData and Length is not None: self.Length = Length self.EncryptedData = EncryptedData else: self.Length = len(Data) self.EncryptedData = key.EncryptWithSessionKey( SessionKey, Data, session_key_type=self.SessionKeyType) if Signature: self.Signature = Signature else: self.Signature = None self.Sign(signing_key=EncryptKey) self.DecryptKey = DecryptKey if _Debug: lg.out(_DebugLevel, 'new data in %s' % self)
def SessionKey(self): """ Return original SessionKey from ``EncryptedSessionKey`` using one of the methods depend on the type of ``DecryptKey`` parameter passed in the __init__() + ``crypt.key.DecryptLocalPrivateKey()`` if DecryptKey is None + ``my_keys.decrypt()`` if DecryptKey is a string with key_id + ``DecryptKey()`` if this is a callback method """ if callable(self.DecryptKey): return self.DecryptKey(self.EncryptedSessionKey) elif strng.is_text(self.DecryptKey): return my_keys.decrypt(self.DecryptKey, self.EncryptedSessionKey) elif strng.is_bin(self.DecryptKey): return my_keys.decrypt(strng.to_text(self.DecryptKey), self.EncryptedSessionKey) return key.DecryptLocalPrivateKey(self.EncryptedSessionKey)
def _to_text(v): if strng.is_bin(v): v = v.decode(encoding, errors=enc_errors) if not strng.is_text(v): v = strng.to_text(v) return v