Ejemplo n.º 1
0
def pyca_tests():
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.primitives.asymmetric import rsa, padding

    Cipher(
        algorithms.TripleDES(key),
        modes.CBC(iv))  # Noncompliant {{Use secure mode and padding scheme.}}
    #                                   ^^^^^^^^^^^^^
    Cipher(algorithms.Blowfish(key), modes.GCM(iv))  # Compliant
    Cipher()  # Compliant
    args = []
    Cipher(algorithms.Blowfish(key), *args)  # Compliant
    Cipher(algorithms.Blowfish(key), modes.ECB())  # Noncompliant
    Cipher(algorithms.AES(key), modes.CBC(iv))  # Noncompliant
    Cipher(mode=modes.CBC(iv), algorithm=algorithms.AES(key))  # Noncompliant
    Cipher(algorithms.AES(key), modes.OFB(iv))  # Compliant
    Cipher(algorithms.AES(key), modes.ECB())  # Noncompliant

    private_key = rsa.generate_private_key()
    public_key = private_key.public_key()
    ciphertext = public_key.encrypt(message, padding.OAEP())

    private_key.decrypt(ciphertext, padding.OAEP())  # Compliant
    public_key.encrypt(message, padding.PKCS1v15())  # Noncompliant
    #                             ^^^^^^^^^^^^^^^^^^
    public_key.encrypt(padding=padding.PKCS1v15(),
                       plaintext=message)  # Noncompliant
    private_key.decrypt(ciphertext, padding.PKCS1v15())  # Noncompliant
    private_key.decrypt(padding=padding.PKCS1v15(),
                        ciphertext=ciphertext)  # Noncompliant
    print(padding.PKCS1v15())  # OK
Ejemplo n.º 2
0
def decryptChunk(chunk, bfKey):
    ''' Decrypt a given encrypted chunk with a blowfish key. '''
    cipher = Cipher(algorithms.Blowfish(bfKey),
                    modes.CBC(bytes([i for i in range(8)])), default_backend())
    decryptor = cipher.decryptor()
    decChunk = decryptor.update(chunk) + decryptor.finalize()
    return decChunk
Ejemplo n.º 3
0
    def __init__(self,
                 cipher_mode=None,
                 initialization_vector=None,
                 key=None,
                 **kwargs):
        """Initializes a decrypter.

    Args:
      cipher_mode (Optional[str]): cipher mode.
      initialization_vector (Optional[bytes]): initialization vector.
      key (Optional[bytes]): key.
      kwargs (dict): keyword arguments depending on the decrypter.

    Raises:
      ValueError: when key is not set or the cipher mode is not supported.
    """
        if not key:
            raise ValueError('Missing key.')

        if cipher_mode not in self._ENCRYPTION_MODES:
            raise ValueError(
                'Unsupported cipher mode: {0!s}'.format(cipher_mode))

        algorithm = algorithms.Blowfish(key)

        super(BlowfishDecrypter,
              self).__init__(algorithm=algorithm,
                             cipher_mode=cipher_mode,
                             initialization_vector=initialization_vector,
                             **kwargs)
Ejemplo n.º 4
0
def cryptography_blowfish(keysize=32, data_size=1024, mode_str=""):
    plaintext = get_random_bytes(data_size * 1024)
    key = get_random_bytes(keysize)
    algorithm = algorithms.Blowfish(key)
    mode = eval(mode_str)
    cipher = Cipher(algorithm, mode=mode(), backend=default_backend())
    encryptor = cipher.encryptor()
    _ = encryptor.update(plaintext)
Ejemplo n.º 5
0
class TestBlowfishModeECB(object):
    test_ECB = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "Blowfish"),
        ["bf-ecb.txt"],
        lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)),
        lambda **kwargs: modes.ECB(),
    )
Ejemplo n.º 6
0
class TestBlowfishModeCFB:
    test_cfb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "Blowfish"),
        ["bf-cfb.txt"],
        lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)),
        lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)),
    )
Ejemplo n.º 7
0
def test_blowfish(msg: str) -> int:
    key = os.urandom(16)
    iv = os.urandom(8)
    cipher = Cipher(algorithms.Blowfish(key), modes.CBC(iv))
    encryptor = cipher.encryptor()
    ct = encryptor.update(bytes(msg, 'utf-8')) + encryptor.finalize()
    decryptor = cipher.decryptor()
    decrypted_message = decryptor.update(ct) + decryptor.finalize()
    return getsizeof(ct)
Ejemplo n.º 8
0
def DBlowFish(path,key,iv):
    f=open(os.path.join(path+"/Segments","1.txt"),"rb")
    content=f.read()
    f.close()
    backend = default_backend()
    cipher = Cipher(algorithms.Blowfish(key), modes.CBC(iv), backend=backend)
    decryptor = cipher.decryptor()
    content=decryptor.update(content) + decryptor.finalize()
    f=open(os.path.join(path+"/temp/Segments","1.txt"),"wb")
    f.write(content)
    f.close()
Ejemplo n.º 9
0
 def encryptAuth(self):
     """Encrypt the authentification credentials to store in the database"""
     bs = int(algorithms.Blowfish.block_size / 8)
     backend = default_backend()
     iv = os.urandom(bs)
     cipher = Cipher(algorithms.Blowfish(self.db.passw.encode('utf-8')), modes.CBC(iv), backend=backend)
     encryptor = cipher.encryptor()
     conf=json.dumps(self.auth).encode('utf-8')
     #padd with spaces to be a multiple of bs
     plen = bs - divmod(len(conf), bs)[1]
     pad = b' '*plen
     self.userentry.auth = iv + encryptor.update(conf+pad) + encryptor.finalize()
Ejemplo n.º 10
0
 def decryptAuth(self):
     """Decrypt the authenficiation credentials as stored in the database"""
     if self.userentry.auth:
         bs=int(algorithms.Blowfish.block_size/8)
         backend = default_backend()
         iv = self.userentry.auth[0:bs]
         encr=self.userentry.auth[bs:]
         cipher = Cipher(algorithms.Blowfish(self.db.passw.encode('utf-8')), modes.CBC(iv), backend=backend)
         decryptor = cipher.decryptor()
         self.auth=json.loads(decryptor.update(encr) + decryptor.finalize())
     else:
         self.auth={}
Ejemplo n.º 11
0
async def dl_and_decrypt_track(url, SNG_ID, filename):
    SNG_ID = str(SNG_ID).encode('ascii')
    blowfish_key = get_blowfish_key(SNG_ID)
    async with aiofiles.open(filename, 'wb') as filestream:
        r = await request_get(url)  # pylint: disable=no-member
        async for i, chunk in asyncenumerate(r.content.iter_chunked(2048)):
            if i % 3 or len(chunk) < 2048:
                await filestream.write(chunk)
            else:
                cipher = Cipher(algorithms.Blowfish(blowfish_key),
                                modes.CBC(bytes([i for i in range(8)])),
                                default_backend())
                decryptor = cipher.decryptor()
                chunk = decryptor.update(chunk) + decryptor.finalize()
                await filestream.write(chunk)
Ejemplo n.º 12
0
def BlowFish(key, iv):
    f = open(os.path.join(os.getcwd() + "\Segments", "1.txt"), "r")
    content = f.read()
    f.close()
    content = content.encode()
    b = len(content)
    if (b % 8 != 0):
        while (b % 8 != 0):
            content += " ".encode()
            b = len(content)
    backend = default_backend()
    cipher = Cipher(algorithms.Blowfish(key), modes.CBC(iv), backend=backend)
    encryptor = cipher.encryptor()
    cont = encryptor.update(content) + encryptor.finalize()
    open(os.path.join(os.getcwd() + "\Segments", "1.txt"), "w").close()
    f = open(os.path.join(os.getcwd() + "\Segments", "1.txt"), "wb")
    f.write(cont)
    f.close()
Ejemplo n.º 13
0
def downloadTrack(filename, ext, url, bfKey):
    ''' Download and decrypts a track. Resumes download for tmp files.'''
    if os.path.isfile(filename + '.tmp'):
        print(f"Resuming download: {filename}{ext}...")
        filesize = os.stat(filename + '.tmp').st_size  # size downloaded file
        # reduce filesize to a multiple of 2048 for seamless decryption
        filesize = filesize - (filesize % 2048)
        i = filesize / 2048
        req = resumeDownload(url, filesize)
    else:
        print(f"Downloading: {filename}{ext}...")
        filesize = 0
        i = 0
        req = requests_retry_session().get(url, stream=True)
        if req.headers['Content-length'] == '0':
            print("Empty file, skipping...\n")
            return False
        # make dirs if they do not exist yet
        fileDir = os.path.dirname(filename + ext)
        if not os.path.isdir(fileDir):
            os.makedirs(fileDir)

    # Decrypt content and write to file
    with open(filename + '.tmp', 'ab') as fd:
        fd.seek(filesize)  # jump to end of the file in order to append to it
        # Only every third 2048 byte block is encrypted.
        for chunk in req.iter_content(2048):
            if i % 3 > 0:
                fd.write(chunk)
            elif len(chunk) < 2048:
                fd.write(chunk)
                break
            else:
                cipher = Cipher(algorithms.Blowfish(bfKey),
                                modes.CBC(bytes([i for i in range(8)])),
                                default_backend())
                decryptor = cipher.decryptor()
                decdata = decryptor.update(chunk) + decryptor.finalize()
                fd.write(decdata)
            i += 1
    os.rename(filename + '.tmp', filename + ext)
    return True
Ejemplo n.º 14
0
def decrypt_text(encrypted_text, key, iv):
    """Decrypts encrypted text using Blowfish and CBC.

    Example::

        # use the same key and iv used in encrypting the text
        text = decrypt_text(enc_text, key, iv)
    """
    cipher = Cipher(algorithms.Blowfish(key),
                    modes.CBC(iv),
                    backend=default_backend())
    decryptor = cipher.decryptor()

    # CBC requires padding
    unpadder = padding.PKCS7(algorithms.Blowfish.block_size).unpadder()
    padded_data = decryptor.update(encrypted_text) + decryptor.finalize()

    # decrypt the encrypted text
    text = unpadder.update(padded_data) + unpadder.finalize()
    return text
def pycaExamples():
    import os
    from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
    from cryptography.hazmat.backends import default_backend

    key = os.urandom(16)
    iv = os.urandom(16)

    tdes4 = Cipher(algorithms.TripleDES(key),
                   mode=None,
                   backend=default_backend()
                   )  # Noncompliant {{Use a strong cipher algorithm.}}
    #              ^^^^^^^^^^^^^^^^^^^^
    bf3 = Cipher(algorithms.Blowfish(key),
                 mode=None,
                 backend=default_backend()
                 )  # Noncompliant {{Use a strong cipher algorithm.}}
    #            ^^^^^^^^^^^^^^^^^^^
    rc42 = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()
                  )  # Noncompliant {{Use a strong cipher algorithm.}}
Ejemplo n.º 16
0
 def get_cipher(self):
     if self.method.startswith('aes'):
         return Cipher(algorithms.AES(self.key), modes.CFB(self.iv),
                       default_backend())
     if self.method.startswith('bf'):
         return Cipher(algorithms.Blowfish(self.key), modes.CFB(self.iv),
                       default_backend())
     if self.method.startswith('camellia'):
         return Cipher(algorithms.Camellia(self.key), modes.CFB(self.iv),
                       default_backend())
     if self.method.startswith('cast5'):
         return Cipher(algorithms.CAST5(self.key), modes.CFB(self.iv),
                       default_backend())
     if self.method.startswith('seed'):
         return Cipher(algorithms.SEED(self.key), modes.CFB(self.iv),
                       default_backend())
     if self.method.startswith('idea'):
         return Cipher(algorithms.IDEA(self.key), modes.CFB(self.iv),
                       default_backend())
     if self.method.startswith('rc4'):
         return Cipher(algorithms.ARC4(self.key), None, default_backend())
     raise ValueError('crypto method %s not supported!' % self.method)
Ejemplo n.º 17
0
async def decrypt_track(track_buffer, info, out_filename):
    SNG_ID = str(info['SNG_ID']).encode('ascii')
    blowfish_key = get_blowfish_key(SNG_ID)
    async with aiofiles.open(out_filename, 'wb') as decrypted_stream:
        chunk_size = 2048
        progress = 0
        file_length = len(track_buffer)

        while progress < file_length:
            if (file_length - progress) < 2048:
                chunk_size = file_length - progress

            chunk = track_buffer[progress:progress + chunk_size]
            if progress % (chunk_size * 3) == 0 and chunk_size == 2048:
                cipher = Cipher(algorithms.Blowfish(blowfish_key),
                                modes.CBC(bytes([i for i in range(8)])),
                                default_backend())
                decryptor = cipher.decryptor()
                chunk = decryptor.update(chunk) + decryptor.finalize()

            await decrypted_stream.write(chunk)
            progress += chunk_size
Ejemplo n.º 18
0
def encrypt_text(text, key, iv):
    """Encrypts plain text using Blowfish and CBC.

    Example::

        import os
        # keep the same key and iv for decrypting the text
        key = os.urandom(32)
        iv = os.urandom(8)
        enc_text = encrypt_text("secret-text", key, iv)
    """
    cipher = Cipher(algorithms.Blowfish(key),
                    modes.CBC(iv),
                    backend=default_backend())
    encryptor = cipher.encryptor()

    # CBC requires padding
    padder = padding.PKCS7(algorithms.Blowfish.block_size).padder()
    padded_data = padder.update(text) + padder.finalize()

    # encrypt the text
    encrypted_text = encryptor.update(padded_data) + encryptor.finalize()
    return encrypted_text
Ejemplo n.º 19
0
# for complete details.

import binascii
import os

import pytest

from cryptography.hazmat.primitives.ciphers import algorithms, modes

from .utils import generate_encrypt_test
from ...utils import load_nist_vectors


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.Blowfish(b"\x00" * 56), modes.ECB()),
    skip_message="Does not support Blowfish ECB",
)
class TestBlowfishModeECB:
    test_ecb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "Blowfish"),
        ["bf-ecb.txt"],
        lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)),
        lambda **kwargs: modes.ECB(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.Blowfish(b"\x00" * 56), modes.CBC(b"\x00" * 8)),
# cf. https://github.com/PyCQA/bandit/blob/b78c938c0bd03d201932570f5e054261e10c5750/examples/ciphers.py

from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import modes
from cryptography.hazmat.backends import default_backend
from struct import pack

# ruleid:insecure-cipher-algorithm-rc4
cipher = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
ct = encryptor.update(b"a secret message")

# ruleid:insecure-cipher-algorithm-blowfish
cipher = Cipher(algorithms.Blowfish(key), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
ct = encryptor.update(b"a secret message")

# ruleid:insecure-cipher-algorithm-idea
cipher = Cipher(algorithms.IDEA(key), mode=None, backend=default_backend())
encryptor = cipher.encryptor()
ct = encryptor.update(b"a secret message")

# ok
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ct = encryptor.update(b"a secret message") + encryptor.finalize()
Ejemplo n.º 21
0
def blowfish_decrypt(ciphertext, key, mode, unpadder=pad.pkcs7_unpad_8):
    return symmetric_decrypt(ciphertext, algorithms.Blowfish(key), mode, unpadder=unpadder)
Ejemplo n.º 22
0
 def decrypt(key, ciphertext):
     cipher = Cipher(algorithms.Blowfish(key),
                     mode=None,
                     backend=default_backend())
     decryptor = cipher.decryptor()
     return decryptor.update(ciphertext)
Ejemplo n.º 23
0
from __future__ import absolute_import, division, print_function

import binascii
import os

import pytest

from cryptography.hazmat.primitives.ciphers import algorithms, modes

from .utils import generate_encrypt_test
from ...utils import load_nist_vectors


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.Blowfish("\x00" * 56), modes.ECB()
    ),
    skip_message="Does not support Blowfish ECB",
)
@pytest.mark.cipher
class TestBlowfishModeECB(object):
    test_ECB = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "Blowfish"),
        ["bf-ecb.txt"],
        lambda key, **kwargs: algorithms.Blowfish(binascii.unhexlify(key)),
        lambda **kwargs: modes.ECB(),
    )


@pytest.mark.supported(
Ejemplo n.º 24
0
 def encrypt(key, plaintext):
     cipher = Cipher(algorithms.Blowfish(key),
                     mode=None,
                     backend=default_backend())
     encryptor = cipher.encryptor()
     return encryptor.update(plaintext)
Ejemplo n.º 25
0
def blowfish_encrypt(plaintext, key, mode, padder=pad.pkcs7_pad_8):
    return symmetric_encrypt(plaintext, algorithms.Blowfish(key), mode, padder=padder)
Ejemplo n.º 26
0
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

key = os.urandom(16)
iv = os.urandom(16)

tdes4 = Cipher(algorithms.TripleDES(key), mode=None, backend=default_backend()) # Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack
bf3 = Cipher(algorithms.Blowfish(key), mode=None, backend=default_backend()) # Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks
rc42 = Cipher(algorithms.ARC4(key), mode=None, backend=default_backend()) # Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security)
Ejemplo n.º 27
0
    def download_track(self,
                       track,
                       download_dir,
                       quality=None,
                       fallback=True,
                       filename=None,
                       renew=False,
                       with_metadata=True,
                       with_lyrics=True,
                       tag_separator=", ",
                       **kwargs):
        """Downloads the given track

        Arguments:
            track {dict} -- Track dictionary, similar to the {info} value that is returned {using get_track()}
            download_dir {str} -- Directory (without {filename}) where the file is to be saved.

        Keyword Arguments:
            quality {str} -- Use values from {constants.track_formats}, will get the default quality if None or an invalid is given. (default: {None})
            filename {str} -- Filename with or without the extension (default: {None})
            renew {bool} -- Will renew the track object (default: {False})
            with_metadata {bool} -- If true, will write id3 tags into the file. (default: {True})
            with_lyrics {bool} -- If true, will find and save lyrics of the given track. (default: {True})
            tag_separator {str} -- Separator to separate multiple artists (default: {", "})
        """

        if with_lyrics:
            if "LYRICS" in track:
                lyric_data = track["LYRICS"]
            else:
                try:
                    if "DATA" in track:
                        lyric_data = self.get_track_lyrics(
                            track["DATA"]["SNG_ID"])["info"]
                    else:
                        lyric_data = self.get_track_lyrics(
                            track["SNG_ID"])["info"]
                except APIRequestError:
                    with_lyrics = False

        if "DATA" in track:
            track = track["DATA"]

        tags = self.get_track_tags(track, separator=tag_separator)

        url, quality_key = self.get_track_download_url(track,
                                                       quality,
                                                       fallback=fallback,
                                                       renew=renew,
                                                       **kwargs)
        blowfish_key = util.get_blowfish_key(track["SNG_ID"])

        # quality = self._select_valid_quality(track, quality)

        quality = track_formats.TRACK_FORMAT_MAP[quality_key]

        title = tags["title"]
        ext = quality["ext"]

        if not filename:
            filename = title + ext

        if not str(filename).endswith(ext):
            filename += ext

        filename = util.clean_filename(filename)

        download_dir = path.normpath(download_dir)
        download_path = path.join(download_dir, filename)

        util.create_folders(download_dir)

        print("Starting download of:", title)

        res = self.session.get(url, cookies=self.get_cookies(), stream=True)
        chunk_size = 2048
        total_filesize = int(res.headers["Content-Length"])
        current_filesize = 0
        i = 0

        pbar = tqdm(res.iter_content(chunk_size),
                    total=total_filesize,
                    unit="B",
                    unit_scale=True,
                    unit_divisor=1024,
                    leave=False,
                    desc=title)
        with open(download_path, "wb") as f:
            f.seek(current_filesize)

            for chunk in pbar:
                chunk_len = len(chunk)
                if i % 3 > 0:
                    f.write(chunk)
                elif len(chunk) < chunk_size:
                    f.write(chunk)
                    pbar.update(chunk_len)
                    break
                else:
                    cipher = Cipher(algorithms.Blowfish(blowfish_key),
                                    modes.CBC(bytes([i for i in range(8)])),
                                    default_backend())

                    decryptor = cipher.decryptor()
                    dec_data = decryptor.update(chunk) + decryptor.finalize()
                    f.write(dec_data)
                    chunk_len = len(dec_data)
                i += 1
                current_filesize += chunk_size
                pbar.update(chunk_len)

        pbar.close()
        if with_metadata:
            if ext.lower() == ".flac":
                self._write_flac_tags(download_path, track, tags=tags)
            else:
                self._write_mp3_tags(download_path, track, tags=tags)

        if with_lyrics:
            lyrics_path = path.join(download_dir, filename[:-len(ext)])
            self.save_lyrics(lyric_data, lyrics_path)

        print("Track downloaded to:", download_path)
Ejemplo n.º 28
0
def int_dec_rnd(et: bytes, key, iv):
    cipher = Cipher(algorithms.Blowfish(key), modes.CBC(iv), backend=backend)
    decryptor = cipher.decryptor()
    pt = decryptor.update(et) + decryptor.finalize()
    return pt
Ejemplo n.º 29
0
def int_enc_rnd(int64: bytes, key, iv):
    cipher = Cipher(algorithms.Blowfish(key), modes.CBC(iv), backend=backend)
    encryptor = cipher.encryptor()
    ct = encryptor.update(int64) + encryptor.finalize()
    return ct
Ejemplo n.º 30
0
 def __init__(self, key):
     self.blowfish = Cipher(
         algorithms.Blowfish(key), mode=modes.ECB(),
         backend=default_backend()
     ).decryptor()