Ejemplo n.º 1
0
def create_esub(text, key, iv=None):
    """Produce a 192bit Encrypted Subject. The first 64 bits are the
    Initialization vector used in the Blowfish CFB Mode.  The Subject text
    is MD5 hashed and then encrypted using an MD5 hash of the Key."""
    texthash = md5(text.encode("utf-8")).digest()
    keyhash = md5(key.encode("utf-8")).digest()
    if iv is None:
        iv = generate_iv(8)
    crypt1 = Blowfish.new(keyhash,
                          Blowfish.MODE_OFB, iv).encrypt(texthash)[:8]
    crypt2 = Blowfish.new(keyhash,
                          Blowfish.MODE_OFB, crypt1).encrypt(texthash[8:])
    return (iv + crypt1 + crypt2).hex()
Ejemplo n.º 2
0
    def decrypt_file(self,
                     in_file_name,
                     out_file_name=None,
                     chunk_size=1024 * 64):
        """Decrypts the file

        Args:
            in_file_name (str): File to decrypt
            out_file_name (str or None): Name of decrypted file (default is in_file_name without extension,
                if in_file_name has no extension, than in_file_name + .decrypted) [optional]
            chunk_size (int or None): The number of bytes that will be read at a time (default is 65536) [optional]
        """
        if not out_file_name:
            out_file_name = os.path.splitext(in_file_name)[0]
            if out_file_name == in_file_name:
                out_file_name += '.decrypted'

        with open(in_file_name, 'rb') as in_file:
            with open(out_file_name, 'wb') as out_file:
                orig_size = struct.unpack('<Q',
                                          in_file.read(
                                              struct.calcsize('Q')))[0]

                while True:
                    nonce, tag, chunk = [
                        in_file.read(x) for x in (16, 8, chunk_size)
                    ]
                    if len(chunk) == 0:
                        break
                    cipher = Blowfish.new(key=self.__key,
                                          mode=Blowfish.MODE_EAX,
                                          nonce=nonce)

                    out_file.write(cipher.decrypt_and_verify(chunk, tag))
                out_file.truncate(orig_size)
Ejemplo n.º 3
0
    def encrypt_file(self,
                     in_file_name,
                     out_file_name=None,
                     chunk_size=1024 * 64):
        """Encrypts the file

        Args:
            in_file_name (str): File to encrypt
            out_file_name (str or None): Name of encrypted file (default is in_file_name + .enc) [optional]
            chunk_size (int or None): The number of bytes that will be read at a time (default is 65536) [optional]
        """
        if not out_file_name:
            out_file_name = in_file_name + '.enc'

        file_size = os.path.getsize(in_file_name)

        with open(in_file_name, 'rb') as in_file:
            with open(out_file_name, 'wb') as out_file:
                out_file.write(struct.pack('<Q', file_size))

                while True:
                    chunk = in_file.read(chunk_size)
                    if len(chunk) == 0:
                        break
                    elif len(chunk) % 16 != 0:
                        chunk += b' ' * (16 - len(chunk) % 16)
                    cipher = Blowfish.new(key=self.__key,
                                          mode=Blowfish.MODE_EAX)
                    ciphertext, tag = cipher.encrypt_and_digest(chunk)
                    [
                        out_file.write(x)
                        for x in (cipher.nonce, tag, ciphertext)
                    ]
Ejemplo n.º 4
0
def decrypt(key, ciphertext, iv=None):
    "Decrypts data"

    if len(ciphertext) % 8 != 0:
        raise base.FormatError

    cipher = Blowfish.new(key)
    cbc = iv
    plaintext = ""

    for cipherblock in [
            ciphertext[i * 8:(i + 1) * 8] for i in range(len(ciphertext) / 8)
    ]:

        plainblock = decrypt_block(cipher, cipherblock)

        if cbc != None:
            plainblock = "".join([
                chr(ord(plainblock[i]) ^ ord(cbc[i]))
                for i in range(len(plainblock))
            ])
            cbc = cipherblock

        plaintext += plainblock

    return plaintext
Ejemplo n.º 5
0
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = Blowfish.new(b'4'*16, Blowfish.MODE_ECB)

        pt = b'5' * 16
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        import sys
        if sys.version[:3] != '2.6':
            output = memoryview(bytearray(16))
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)
        
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(7)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
Ejemplo n.º 6
0
def encrypt(key, plaintext, iv=None):
    "Encrypts data"

    if len(plaintext) % 8 != 0:
        raise base.FormatError

    cipher = Blowfish.new(key)
    cbc = iv
    ciphertext = ""

    for plainblock in [
            plaintext[i * 8:(i + 1) * 8] for i in range(len(plaintext) / 8)
    ]:

        if cbc != None:
            plainblock = "".join([
                chr(ord(plainblock[i]) ^ ord(cbc[i]))
                for i in range(len(plainblock))
            ])

        cipherblock = encrypt_block(cipher, plainblock)
        ciphertext += cipherblock

        if cbc != None:
            cbc = cipherblock

    return ciphertext
Ejemplo n.º 7
0
    def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = Blowfish.new(b'4'*16, Blowfish.MODE_ECB)

        pt = b'5' * 16
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        import sys
        if sys.version[:3] != '2.6':
            output = memoryview(bytearray(16))
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)
        
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(7)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
Ejemplo n.º 8
0
def shared_key_decrypt(ciphertext, key):
    alg = key['alg']
    mode = key['mode']
    k = key['key']
    decrypt_kwargs = {'mode': BLOCK_MODES[alg][mode]}
    preamble_length = BLOCK_SIZES[alg]
    if mode in IV_MODES:
        #print("SYM_DECRYPT: Generating an IV", flush = True)
        decrypt_kwargs['iv'] = ciphertext[0:BLOCK_SIZES[alg]]
    elif mode == 'ctr':
        #print('SYM_DECRYPT: Generating a Counter', flush = True)
        preamble_length = preamble_length // 2
        n = ciphertext[0:(BLOCK_SIZES[alg] // 2)]
        decrypt_kwargs['nonce'] = n
    if alg == 'aes':
        #print('SYM_DECRYPT: USING AES')
        decrypter = AES.new(k, **decrypt_kwargs)
    elif alg == 'des3':
        #print('SYM_DECRYPT: USING DES3')
        decrypter = DES3.new(k, **decrypt_kwargs)
    elif alg == 'blowfish':
        #print('SYM_DECRYPT: USING Blowfish')
        decrypter = Blowfish.new(k, **decrypt_kwargs)
    serial_pt = decrypter.decrypt(ciphertext[preamble_length:])
    if mode in PAD_MODES:
        serial_pt = unpad(serial_pt, BLOCK_SIZES[alg])
    if serial_pt[0]:
        return pickle.loads(serial_pt[1:])
    else:
        return serial_pt[1:]
    return pt
Ejemplo n.º 9
0
def decrypt(ciphertext, password, magic=None):
    "Decrypts a data stream"

    # decrypt data
    if len(ciphertext) % 8 != 0:
        raise base.FormatError

    key = SHA.new(password.encode()).digest()  # nosec
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, IV)  # nosec

    plaintext = cipher.decrypt(ciphertext)

    # check magic string
    if magic != None:
        if plaintext[:len(magic)] != magic:
            raise base.PasswordError

        else:
            plaintext = plaintext[len(magic):]

    # remove padding
    padchar = plaintext[-1]
    npadchar = padchar

    if (npadchar > 0):
        if plaintext[-npadchar:] != bytes([padchar] * npadchar):
            raise base.FormatError

        plaintext = plaintext[:-npadchar]
    return plaintext
Ejemplo n.º 10
0
def encrypt(key, plaintext, iv=None):
    "Encrypts data"

    if len(plaintext) % 8 != 0:
        raise base.FormatError

    cipher = Blowfish.new(key, Blowfish.MODE_ECB)  # nosec
    cbc = iv
    ciphertext = b""

    for plainblock in [
            plaintext[i * 8:(i + 1) * 8] for i in range(len(plaintext) // 8)
    ]:

        if cbc != None:
            plainblock = bytes(
                [plainblock[i] ^ cbc[i] for i in range(len(plainblock))])

        cipherblock = encrypt_block(cipher, plainblock)
        ciphertext += cipherblock

        if cbc != None:
            cbc = cipherblock

    return ciphertext
Ejemplo n.º 11
0
    def decrypt(self, ciphertext):
        """Decrypts the encrypted text

        Args:
            ciphertext (str): Encrypted text to decrypt

        Returns:
            str: Decrypted text
        """
        with open(self.__private_key_loc, 'rb') as private_key_file:
            private_key = RSA.import_key(
                private_key_file.read(),
                passphrase=self.__private_key_passphrase)
        cipher_rsa = PKCS1_OAEP.new(private_key)

        ciphertext = base64.b64decode(ciphertext)
        session_key = cipher_rsa.decrypt(
            ciphertext[:private_key.size_in_bytes()])
        nonce = ciphertext[private_key.size_in_bytes(
        ):private_key.size_in_bytes() + 16]
        tag = ciphertext[private_key.size_in_bytes() +
                         16:private_key.size_in_bytes() + 24]

        ciphertext = ciphertext[private_key.size_in_bytes() + 24:]
        cipher_blowfish = Blowfish.new(key=session_key,
                                       mode=Blowfish.MODE_EAX,
                                       nonce=nonce)
        plaintext = cipher_blowfish.decrypt_and_verify(ciphertext, tag)
        return _unpad(plaintext).decode()
Ejemplo n.º 12
0
def _cypherer(seed):
    if isinstance(seed, str):
        seed = seed.encode('utf-8')
    try:
        return _CYPHERERS[seed]
    except KeyError:
        _CYPHERERS[seed] = Blowfish.new(seed, Blowfish.MODE_ECB)
        return _CYPHERERS[seed]
Ejemplo n.º 13
0
def run_Blowfish():
    key = Random.get_random_bytes(16)
    nonce = Random.get_random_bytes(16)

    print("=================")
    print("Encrypting with Blowfish")
    print("Key: ", to_hex(key))
    print("Nonce: ", to_hex(nonce))

    cipher = Blowfish.new(key, Blowfish.MODE_EAX, nonce)

    ciphertext = cipher.encrypt(data)

    #print("Cleartext: ", to_hex(data))
    #print("Ciphertext: ", to_hex(ciphertext))

    file_out = open("blowfish.bin", "wb")
    [file_out.write(x) for x in (cipher.nonce, ciphertext)]
    file_out.close()

    file_in = open("blowfish.bin", "rb")
    decrypt_nonce, decrypt_ciphertext = [file_in.read(x) for x in (16, -1)]
    file_in.close()

    print("=================")
    print("Decrypting with Blowfish")
    print("Key: ", to_hex(key))
    print("Nonce: ", to_hex(decrypt_nonce))
    #print("Ciphertext: ", to_hex(decrypt_ciphertext))

    decipher = Blowfish.new(key, Blowfish.MODE_EAX, decrypt_nonce)
    cleartext = decipher.decrypt(decrypt_ciphertext)

    #print("Cleartext: ", to_hex(cleartext))
    print("=================")

    if cleartext == data:
        print("Decryption successful\n")
    else:
        print("Decryption failed\n")

    return
Ejemplo n.º 14
0
    def encrypt(self, plaintext):
        """Encrypts the plaintext

        Args:
            plaintext (str): Plaintext to encrypt

        Returns:
            str: Encrypted text
        """
        plaintext = _pad(plaintext.encode(), AES.block_size)
        cipher = Blowfish.new(key=self.__key, mode=Blowfish.MODE_EAX)
        ciphertext, tag = cipher.encrypt_and_digest(plaintext)
        return base64.b64encode(cipher.nonce + tag + ciphertext).decode()
Ejemplo n.º 15
0
    def decrypt(self, key: bytes, data: bytes) -> bytes:
        """
        Decrypts buffer using Blowfish algorithm in ECB mode.

        :param key: Cryptographic key (4 to 56 bytes)
        :type key: bytes
        :param data: Buffer to be decrypted
        :type data: bytes
        :return: Decrypted data
        :rtype: bytes
        """
        cipher = BlowfishCipher.new(key, BlowfishCipher.MODE_ECB)
        return cipher.decrypt(data)
Ejemplo n.º 16
0
    def export_data(self, entrystore, password):
        "Exports data from an entrystore"

        # set up encryption engine
        salt = "".join( [ random.choice(string.ascii_lowercase) for i in range(8) ] )
        password = MD5.new(salt + password).digest()

        cipher = Blowfish.new(password)


        # generate data
        xml = "<?xml version=\"1.0\" ?>\n"
        xml += "<FPM full_version=\"00.58.00\" min_version=\"00.58.00\" display_version=\"00.58.00\">\n"
        xml += "    <KeyInfo salt=\"%s\" vstring=\"%s\" />\n" % ( salt, self.__encrypt(cipher, "FIGARO") )
        xml += "    <LauncherList></LauncherList>\n"
        xml += "    <PasswordList>\n"

        iter = entrystore.iter_children(None)

        while iter is not None:
            e = entrystore.get_entry(iter)

            if type(e) != entry.FolderEntry:
                e = e.convert_generic()

                xml += "        <PasswordItem>\n"
                xml += "            <title>%s</title>\n" % e.name
                xml += "            <url>%s</url>\n" % e.get_field(entry.HostnameField).value
                xml += "            <user>%s</user>\n" % e.get_field(entry.UsernameField).value
                xml += "            <password>%s</password>\n" % e.get_field(entry.PasswordField).value
                xml += "            <notes>%s</notes>\n" % e.description

                path = entrystore.get_path(iter)

                if len(path) > 1:
                    xml += "            <category>%s</category>\n" % entrystore.get_entry(entrystore.get_iter(path[0])).name

                else:
                    xml += "            <category></category>\n"

                xml += "            <launcher></launcher>\n"
                xml += "        </PasswordItem>\n"

            iter = entrystore.iter_traverse_next(iter)


        xml += "    </PasswordList>\n"
        xml += "</FPM>\n"


        return xml
Ejemplo n.º 17
0
    def decrypt_pass(cls):
        if cls.key_pass:
            try:
                cipher = Blowfish.new(cls.key_pass.encode(), Blowfish.MODE_CBC, settings.iv)
                cls.p_un_sup = cipher.decrypt(settings.p_un_sup).decode().split('1111')[0]

                cipher = Blowfish.new(cls.key_pass.encode(), Blowfish.MODE_CBC, settings.iv)
                cls.p_sw = cipher.decrypt(settings.p_sw).decode().split('1111')[0]

                cipher = Blowfish.new(cls.key_pass.encode(), Blowfish.MODE_CBC, settings.iv)
                cls.my_key = cipher.decrypt(settings.my_key).decode().split('1111')[0]

                cipher = Blowfish.new(cls.key_pass.encode(), Blowfish.MODE_CBC, settings.iv)
                cls.my_key_e = cipher.decrypt(settings.my_key_e).decode().split('1111')[0]

                cipher = Blowfish.new(cls.key_pass.encode(), Blowfish.MODE_CBC, settings.iv)
                cls.p_mb_sec = cipher.decrypt(settings.p_mb_sec).decode().split('1111')[0]

            except Exception as e:
                print(f"Error while encoded passwords. {e}")
                cls.key_pass = None
            finally:
                return True
Ejemplo n.º 18
0
 def decrypt_track(self, track_id, input, output):
     response = open(input, 'rb')
     outfile = open(output, 'wb')
     blowfish_key = str.encode(self._get_blowfish_key(str(track_id)))
     i = 0
     while True:
         chunk = response.read(2048)
         if not chunk:
             break
         if (i % 3) == 0 and len(chunk) == 2048:
             chunk = Blowfish.new(
                 blowfish_key, Blowfish.MODE_CBC,
                 b"\x00\x01\x02\x03\x04\x05\x06\x07").decrypt(chunk)
         outfile.write(chunk)
         i += 1
Ejemplo n.º 19
0
def login(senha1):
    from Cryptodome.Cipher import Blowfish
    from Cryptodome import Random
    from struct import pack

    BF = Blowfish.block_size
    Chave = b'Alohomora'
    CDS = Random.new().read(BF)
    cipher = Blowfish.new(Chave, Blowfish.MODE_CBC, CDS)
    plaintext = senha1
    plen = BF - divmod(len(plaintext), BF)[1]
    padding = [plen] * plen
    padding = pack('b' * plen, *padding)
    msg = CDS + cipher.encrypt(plaintext + padding)
    print(repr(msg))
Ejemplo n.º 20
0
def senha(senha2):
    from Cryptodome.Cipher import Blowfish
    from struct import pack

    BF = Blowfish.block_size
    Chave = b'Alohomora'
    texto_encriptado = senha2
    CDS = texto_encriptado[:BF]
    texto_encriptado = texto_encriptado[BF:]

    cipher = Blowfish.new(Chave, Blowfish.MODE_CBC, CDS)
    msg = cipher.decrypt(texto_encriptado)

    last_byte = msg[-1]
    msg = msg[:-(last_byte if type(last_byte) is int else ord(last_byte))]
    print(repr(msg))
Ejemplo n.º 21
0
def encrypt(plaintext, password):
    "Encrypts a data stream"

    # right-pad data
    padlen = 8 - len(plaintext) % 8

    if padlen == 0:
        padlen = 8

    plaintext += chr(padlen) * padlen

    # encrypt data
    key = SHA.new(password).digest()
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, IV)

    return cipher.encrypt(plaintext)
Ejemplo n.º 22
0
def generate_testhash(password, random):
    "Generates a testhash based on a password and a random string"

    key = SHA(random + b"\x00\x00" + password.encode()).digest()
    cipher = Blowfish.new(key, Blowfish.MODE_ECB)  # nosec

    for i in range(1000):
        random = encrypt_block(cipher, random)

    h = SHA()
    h.init(0, 0, 0, 0, 0)
    h.update(random)
    h.update(b"\x00\x00")
    testhash = h.digest()

    return testhash
Ejemplo n.º 23
0
def encrypt(plaintext, password):
    "Encrypts a data stream"

    # right-pad data
    padlen = 8 - len(plaintext) % 8

    if padlen == 0:
        padlen = 8

    plaintext += bytes([padlen] * padlen)

    # encrypt data
    key = SHA.new(password.encode()).digest()  # nosec
    cipher = Blowfish.new(key, Blowfish.MODE_CBC, IV)  # nosec

    return cipher.encrypt(plaintext)
Ejemplo n.º 24
0
    def decrypt(self, ciphertext):
        """Decrypts the encrypted text

        Args:
            ciphertext (str): Encrypted text to decrypt

        Returns:
            str: Decrypted text
        """
        ciphertext = base64.b64decode(ciphertext)
        nonce = ciphertext[:16]
        tag = ciphertext[16:24]
        ciphertext = ciphertext[24:]
        cipher = Blowfish.new(key=self.__key,
                              mode=Blowfish.MODE_EAX,
                              nonce=nonce)
        plaintext = cipher.decrypt_and_verify(ciphertext, tag)
        return _unpad(plaintext).decode()
Ejemplo n.º 25
0
 def stream_track(self, track_id, url, stream):
     try:
         request = requests.get(url,
                                headers=self.http_headers,
                                stream=True,
                                timeout=30,
                                verify=False)
     except:
         time.sleep(2)
         return self.stream_track(track_id, url, stream)
     request.raise_for_status()
     blowfish_key = str.encode(self._get_blowfish_key(str(track_id)))
     i = 0
     for chunk in request.iter_content(2048):
         if (i % 3) == 0 and len(chunk) == 2048:
             chunk = Blowfish.new(
                 blowfish_key, Blowfish.MODE_CBC,
                 b"\x00\x01\x02\x03\x04\x05\x06\x07").decrypt(chunk)
         stream.write(chunk)
         i += 1
Ejemplo n.º 26
0
    def __decrypt_data(self, dirty_data):
        previous_block = None  # type: str
        blowfish = Blowfish.new(TYPE_TO_KEY[self._type], Blowfish.MODE_ECB)
        decrypted_data = BytesIO()

        for index, chunk in self.__chunkify_string(dirty_data):
            # FIXME: what this chunk is used for??
            if index == 0:
                continue

            decrypted_block, = struct.unpack('q', blowfish.decrypt(chunk))
            if previous_block:
                # get two blocks, each 8 bytes long and xor them
                # then pack them back to bytes
                decrypted_block ^= previous_block
            previous_block = decrypted_block

            decrypted_data.write(struct.pack('q', decrypted_block))

        return decrypted_data.getvalue()
Ejemplo n.º 27
0
    def encrypt_file(self,
                     in_file_name,
                     out_file_name=None,
                     chunk_size=1024 * 64):
        """Encrypts the file

        Args:
            in_file_name (str): File to encrypt
            out_file_name (str or None): Name of encrypted file (default is in_file_name + .enc) [optional]
            chunk_size (int or None): The number of bytes that will be read at a time (default is 65536) [optional]
        """
        if not out_file_name:
            out_file_name = in_file_name + '.enc'

        file_size = os.path.getsize(in_file_name)
        session_key = Random.get_random_bytes(32)

        with open(self.__public_key_loc, 'rb') as public_key_file:
            cipher_rsa = PKCS1_OAEP.new(
                RSA.import_key(public_key_file.read(),
                               passphrase=self.__public_key_passphrase))
        with open(in_file_name, 'rb') as in_file:
            with open(out_file_name, 'wb') as out_file:
                out_file.write(struct.pack('<Q', file_size))
                out_file.write(cipher_rsa.encrypt(session_key))

                while True:
                    chunk = in_file.read(chunk_size)
                    if len(chunk) == 0:
                        break
                    elif len(chunk) % 16 != 0:
                        chunk += b' ' * (16 - len(chunk) % 16)
                    cipher_blowfish = Blowfish.new(key=session_key,
                                                   mode=Blowfish.MODE_EAX)
                    ciphertext, tag = cipher_blowfish.encrypt_and_digest(chunk)
                    [
                        out_file.write(x)
                        for x in (cipher_blowfish.nonce, tag, ciphertext)
                    ]
def pycryptodomexExamples():
    from Cryptodome.Cipher import DES, DES3, ARC2, ARC4, Blowfish, AES
    from Cryptodome.Random import get_random_bytes

    key = b'-8B key-'
    DES.new(key,
            DES.MODE_OFB)  # Noncompliant {{Use a strong cipher algorithm.}}
    # ^^^^^^^

    key = DES3.adjust_key_parity(get_random_bytes(24))
    cipher = DES3.new(
        key, DES3.MODE_CFB)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^

    key = b'Sixteen byte key'
    cipher = ARC2.new(
        key, ARC2.MODE_CFB)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^

    key = b'Very long and confidential key'
    cipher = ARC4.new(key)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^

    key = b'An arbitrarily long key'
    cipher = Blowfish.new(
        key,
        Blowfish.MODE_CBC)  # Noncompliant {{Use a strong cipher algorithm.}}
    #        ^^^^^^^^^^^^

    key = b'Sixteen byte key'
    cipher = AES.new(key, AES.MODE_CCM)  # Compliant

    cipher = UnknownFlyingValue.new(
        key, UnknownMode.CBC)  # Compliant, doesn't matter

    # Force the engine to generate an ambiguous symbol, for code coverage only.
    ambiguous = "" if 42 * 42 < 1700 else (lambda x: x * x)
    cipher = ambiguous.new(key, Unknown.Mode)
Ejemplo n.º 29
0
    def encrypt(self, plaintext):
        """Encrypts the plaintext

        Args:
            plaintext (str): Plaintext to encrypt

        Returns:
            str: Encrypted text
        """
        plaintext = _pad(plaintext.encode(), AES.block_size)
        session_key = Random.get_random_bytes(32)

        with open(self.__public_key_loc, 'rb') as public_key_file:
            cipher_rsa = PKCS1_OAEP.new(
                RSA.import_key(public_key_file.read(),
                               passphrase=self.__public_key_passphrase))

        cipher_blowfish = Blowfish.new(key=session_key, mode=Blowfish.MODE_EAX)
        ciphertext, tag = cipher_blowfish.encrypt_and_digest(plaintext)

        return base64.b64encode(
            cipher_rsa.encrypt(session_key) + cipher_blowfish.nonce + tag +
            ciphertext).decode()
Ejemplo n.º 30
0
def decrypt(key, ciphertext, iv=None):
    "Decrypts data"

    if len(ciphertext) % 8 != 0:
        raise base.FormatError

    cipher = Blowfish.new(key, Blowfish.MODE_ECB)  # nosec
    cbc = iv
    plaintext = b""

    for cipherblock in [
            ciphertext[i * 8:(i + 1) * 8] for i in range(len(ciphertext) // 8)
    ]:

        plainblock = decrypt_block(cipher, cipherblock)

        if cbc != None:
            plainblock = bytes(
                [plainblock[i] ^ cbc[i] for i in range(len(plainblock))])
            cbc = cipherblock

        plaintext += plainblock

    return plaintext
Ejemplo n.º 31
0
def shared_key_encrypt(plaintext, key, iv):
    status = 0
    if not isinstance(plaintext, bytes):
        serial_pt = b'\1' + pickle.dumps(plaintext)
    else:
        serial_pt = b'\0' + plaintext
    alg = key['alg']
    mode = key['mode']
    k = key['key']
    encrypt_kwargs = {'mode': BLOCK_MODES[alg][mode]}
    if mode in PAD_MODES:
        #print('SYM_ENCRYPT: Padding Plaintext', flush = True)
        serial_pt = pad(serial_pt, BLOCK_SIZES[alg])
    if mode in IV_MODES and iv != None:
        encrypt_kwargs['iv'] = iv
    if alg == 'aes':
        #print('SYM_ENCRYPT: USING AES')
        encrypter = AES.new(k, **encrypt_kwargs)
    elif alg == 'des3':
        #print('SYM_ENCRYPT: USING DES3')
        encrypter = DES3.new(k, **encrypt_kwargs)
    elif alg == 'blowfish':
        #print('SYM_ENCRYPT: USING Blowfish')
        encrypter = Blowfish.new(k, **encrypt_kwargs)
    else:
        status = NO_ALG
    if mode in IV_MODES:
        preamble = encrypter.iv
    elif mode == 'ctr':
        preamble = encrypter.nonce
    else:
        status = NO_MODE
    if status in ErrorCodes:
        print('SA ERROR: Encryption failed!')
    else:
        return preamble + encrypter.encrypt(serial_pt)
Ejemplo n.º 32
0
cipher = pycrypto_arc4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')
cipher = pycryptodomex_arc4.new(tempkey)
msg = nonce + cipher.encrypt(b'Open the pod bay doors, HAL')

iv = Random.new().read(bs)
key = b'An arbitrarily long key'
plaintext = b'docendo discimus '
plen = bs - divmod(len(plaintext),bs)[1]
padding = [plen]*plen
padding = pack('b'*plen, *padding)
bs = pycrypto_blowfish.block_size
cipher = pycrypto_blowfish.new(key, pycrypto_blowfish.MODE_CBC, iv)
msg = iv + cipher.encrypt(plaintext + padding)
bs = pycryptodomex_blowfish.block_size
cipher = pycryptodomex_blowfish.new(key, pycryptodomex_blowfish.MODE_CBC, iv)
msg = iv + cipher.encrypt(plaintext + padding)

key = b'-8B key-'
plaintext = b'We are no longer the knights who say ni!'
nonce = Random.new().read(pycrypto_des.block_size/2)
ctr = Counter.new(pycrypto_des.block_size*8/2, prefix=nonce)
cipher = pycrypto_des.new(key, pycrypto_des.MODE_CTR, counter=ctr)
msg = nonce + cipher.encrypt(plaintext)
nonce = Random.new().read(pycryptodomex_des.block_size/2)
ctr = Counter.new(pycryptodomex_des.block_size*8/2, prefix=nonce)
cipher = pycryptodomex_des.new(key, pycryptodomex_des.MODE_CTR, counter=ctr)
msg = nonce + cipher.encrypt(plaintext)

key = b'Super secret key'
plaintext = b'Encrypt me'