Exemplo n.º 1
0
 def __init__(self, key: RSA.RsaKey = None):
     if not key:
         self.key = RSA.generate(4096, Random.new().read)
     elif key and isinstance(key, RSA.RsaKey) and key.has_private():
         self.key: RSA.RsaKey = key
     else:
         raise TypeError('key must be private RSA key')
Exemplo n.º 2
0
    def unpack(self,
               raw: Union[bytes, bytearray],
               key: RSA.RsaKey = None) -> Packet:
        if isinstance(raw, (bytes, bytearray)):
            if isinstance(raw, bytes):
                raw = bytearray(raw)

            header: Header = self.unpack_header(raw[:HEADER_SIZE])

            if header.checksum != hashlib.blake2s(raw[HEADER_SIZE:]).digest():
                raise PacketError('Data is corrupted (Bad checksum)')

            if header.flags.encrypted:
                cipher: PKCS1_OAEP.PKCS1OAEP_Cipher = PKCS1_OAEP.new(
                    key if key and key.has_private() else self.key, SHA3_256)
                chunk: int = header.flags.cluster
                decrypted = bytearray()

                try:
                    for i in (raw[HEADER_SIZE:][i:i + chunk]
                              for i in range(0,
                                             raw.__len__() -
                                             HEADER_SIZE, chunk)):
                        decrypted.extend(cipher.decrypt(i))
                except ValueError:
                    raise DamageError(f'Encrypted data is damaged')

            header.flags.size = len(
                decrypted) if header.flags.encrypted else len(
                    raw[HEADER_SIZE:])

            return Packet(
                header,
                decrypted if header.flags.encrypted else raw[HEADER_SIZE:],
                bytes(raw[44:76]) if header.flags.encrypted else None)
        else:
            raise TypeError('Raw must be bytes or bytearray')
Exemplo n.º 3
0
 def from_rsa_obj(cls, rsa: RSA.RsaKey):
     if not rsa.has_private():
         return XeCrypt_RSA(n=rsa._n, e=rsa._e)
     else:
         return XeCrypt_RSA(n=rsa._n, e=rsa._e, d=rsa._d, p=rsa._p, q=rsa._q, u=rsa._u)