Example #1
0
    def _fromString_PRIVATE_OPENSSH(cls, data, passphrase):
        """
        Return a private key object corresponding to this OpenSSH private key
        string.  If the key is encrypted, passphrase MUST be provided.
        Providing a passphrase for an unencrypted key is an error.

        The format of an OpenSSH private key string is::
            -----BEGIN <key type> PRIVATE KEY-----
            [Proc-Type: 4,ENCRYPTED
            DEK-Info: DES-EDE3-CBC,<initialization value>]
            <base64-encoded ASN.1 structure>
            ------END <key type> PRIVATE KEY------

        The ASN.1 structure of a RSA key is::
            (0, n, e, d, p, q)

        The ASN.1 structure of a DSA key is::
            (0, p, q, g, y, x)

        @type data: L{bytes}
        @param data: The key data.

        @type passphrase: L{bytes} or C{None}
        @param passphrase: The passphrase the key is encrypted with, or C{None}
        if it is not encrypted.

        @return: A new key.
        @rtype: L{twisted.conch.ssh.keys.Key}
        @raises BadKeyError: if
            * a passphrase is provided for an unencrypted key
            * the ASN.1 encoding is incorrect
        @raises EncryptedKeyError: if
            * a passphrase is not provided for an encrypted key
        """
        lines = data.strip().split(b'\n')
        kind = lines[0][11:14]
        if lines[1].startswith(b'Proc-Type: 4,ENCRYPTED'):
            if not passphrase:
                raise EncryptedKeyError('Passphrase must be provided '
                                        'for an encrypted key')

            # Determine cipher and initialization vector
            try:
                _, cipherIVInfo = lines[2].split(b' ', 1)
                cipher, ivdata = cipherIVInfo.rstrip().split(b',', 1)
            except ValueError:
                raise BadKeyError('invalid DEK-info %r' % (lines[2], ))

            if cipher == b'AES-128-CBC':
                algorithmClass = algorithms.AES
                keySize = 16
                if len(ivdata) != 32:
                    raise BadKeyError('AES encrypted key with a bad IV')
            elif cipher == b'DES-EDE3-CBC':
                algorithmClass = algorithms.TripleDES
                keySize = 24
                if len(ivdata) != 16:
                    raise BadKeyError('DES encrypted key with a bad IV')
            else:
                raise BadKeyError('unknown encryption type %r' % (cipher, ))

            # Extract keyData for decoding
            iv = bytes(
                bytearray([
                    int(ivdata[i:i + 2], 16) for i in range(0, len(ivdata), 2)
                ]))
            ba = md5(passphrase + iv[:8]).digest()
            bb = md5(ba + passphrase + iv[:8]).digest()
            decKey = (ba + bb)[:keySize]
            b64Data = base64.decodestring(b''.join(lines[3:-1]))

            decryptor = Cipher(algorithmClass(decKey),
                               modes.CBC(iv),
                               backend=default_backend()).decryptor()
            keyData = decryptor.update(b64Data) + decryptor.finalize()

            removeLen = ord(keyData[-1:])
            keyData = keyData[:-removeLen]
        else:
            b64Data = b''.join(lines[1:-1])
            keyData = base64.decodestring(b64Data)

        try:
            decodedKey = berDecoder.decode(keyData)[0]
        except PyAsn1Error as e:
            raise BadKeyError('Failed to decode key (Bad Passphrase?): %s' %
                              (e, ))

        if kind == b'RSA':
            if len(decodedKey) == 2:  # Alternate RSA key
                decodedKey = decodedKey[0]
            if len(decodedKey) < 6:
                raise BadKeyError('RSA key failed to decode properly')

            n, e, d, p, q, dmp1, dmq1, iqmp = [
                long(value) for value in decodedKey[1:9]
            ]
            if p > q:  # Make p smaller than q
                p, q = q, p
            return cls(
                rsa.RSAPrivateNumbers(
                    p=p,
                    q=q,
                    d=d,
                    dmp1=dmp1,
                    dmq1=dmq1,
                    iqmp=iqmp,
                    public_numbers=rsa.RSAPublicNumbers(e=e, n=n),
                ).private_key(default_backend()))
        elif kind == b'DSA':
            p, q, g, y, x = [long(value) for value in decodedKey[1:6]]
            if len(decodedKey) < 6:
                raise BadKeyError('DSA key failed to decode properly')
            return cls(
                dsa.DSAPrivateNumbers(
                    x=x,
                    public_numbers=dsa.DSAPublicNumbers(
                        y=y,
                        parameter_numbers=dsa.DSAParameterNumbers(
                            p=p, q=q,
                            g=g))).private_key(backend=default_backend()))
        else:
            raise BadKeyError("unknown key type %s" % (kind, ))
Example #2
0
        md = hashlib.sha256(md_in).digest()

        # generate expected C value from P bitstring
        #
        # Y4096 || M4096 || Rb4096 || M_prime32 || LENGTH32 || MD256 || 0x08*8
        p = number_as_bytes(Y, 4096) + \
            number_as_bytes(M, 4096) + \
            number_as_bytes(rinv, 4096) + \
            md + \
            struct.pack('<II', mprime, length) + \
            b'\x08' * 8

        assert len(p) == 12672 / 8

        cipher = Cipher(algorithms.AES(aes_key),
                        modes.CBC(iv),
                        backend=default_backend())
        encryptor = cipher.encryptor()
        c = encryptor.update(p) + encryptor.finalize()

        f.write('        .expected_c = %s,\n' % bytes_as_char_array(c))
        f.write('        .hmac_key_idx = %d,\n' % (hmac_key_idx))

        f.write(
            '        // results of message array encrypted with these keys\n')
        f.write('        .expected_results = {\n')
        mask = (1 << key_size) - 1  # truncate messages if needed
        for m in messages:
            f.write('        // Message %d\n' % messages.index(m))
            f.write('      %s,' %
                    (number_as_bignum_words(pow(m & mask, Y, M))))
Example #3
0
def AES():
    #the messeage that will be encrypted with AES
    test = (input("Enter plaintext: "))
    a = test
    #test = "a super duper secret message"
    test = test.encode()

    #if lenght of message is not 16 use padder
    if (len(test) % 16 != 0):
        padder = padding.PKCS7(128).padder()
        padded = padder.update(test)
        padded
        padded += padder.finalize()

    else:
        padded = test

    print("your plaintext before encryption: ", a)
    #AES encryption
    backend = default_backend()
    key = os.urandom(32)
    iv = os.urandom(16)
    print("Your key is: " + str(key))
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
    encryptor = cipher.encryptor()
    ct = encryptor.update(padded) + encryptor.finalize()
    print("encrypted message: " + str(ct))
    decryptor = cipher.decryptor()
    ct = decryptor.update(ct) + decryptor.finalize()

    #if length of message is not 16 use the unpadder
    if (len(test) != 16):
        unpadder = padding.PKCS7(128).unpadder()
        data = unpadder.update(padded)
        data
        data += unpadder.finalize()
        print("the decrypted message: ", data)

    #if not print
    else:
        print("the decrypted message: ", ct)

    print(
        "AES is an encryption a symmetric block cipher developed by the national institute of standards and technology(NIST) is the successor to DES. "
    )
    x = (int(input("For more information about AES enter 1: ")))
    if (x == 1):
        y = 3  #abitrary y to start loop
        while not (y == 0 or y == 1):
            y = (int(
                input(
                    "Enter 0 for information about encryption and 1 for decryption: "
                )))
            if (y == 0):
                print(
                    "To encrypt AES, it will take plaintext and a key which run through the algorithm and output a ciphertext. AES takes the plaintext and splits it into 128 bit blocks. Each block is then XOR’d together with an expanded key that has the same bits as the block. The block is then run through N number of rounds depending on key size. Each round has four transformations (substitutions, transposition, mixColumns and XOR with key) excluding the final round which only has substitution, transposition and XOR. Substitution uses a S-box to perform a byte-to-byte substitution of the block. The transposition step shifts the bytes in each row by a certain offset. The mixColumns function takes four bytes as input and outputs new four bytes. The final step XOR is where the block is XOR’d and the output is then run through these steps for N number of times expect the final round does substitution, transposition and XOR. After the block is finished this process will be repeated until all blocks are finished."
                )
                n = int(
                    input(
                        "Would you like to restart? Enter 0 for No or 1 for Yes"
                    ))
                if (n == 1):
                    y = 2
                    continue
                else:
                    break
            elif (y == 1):
                print(
                    "Decrypting AES is not the same as encrypting. To decrypt the ciphertext we will be using the same key but in the rounds instead of substitutions, transposition and mixColumns we will be using inverse substitutions, transposition and mixColumns. Inverse substitution affects the contents of the bytes but doesn’t alter the byte sequence and doesn’t depend on it perform the transformation. Inverse transposition affects the sequence of bytes but not the byte content and doesn’t depend on it to perform its transformation. So the ciphertext is entered the key is XOR’d in then we start the rounds. Each round will four transformations inverse substitution, transposition, mixColumns and XOR. Then at the final round only three transformations inverse substitution, transposition and XOR is carried out and the plaintext will be outputted. It will repeat this process until the whole plaintext is completed. "
                )
                n = int(
                    input(
                        "Would you like to restart? Enter 0 for No or 1 for Yes: "
                    ))
                if (n == 1):
                    y = 2
                    continue
                else:
                    break
            else:
                print("Invalid input, please re-enter 0 or 1")
Example #4
0
from cryptography.hazmat.primitives.ciphers import algorithms, Cipher, modes
import os

key = os.urandom(256 // 8)
iv = os.urandom(16)

algorithm = algorithms.AES(key)
cipher = Cipher(algorithm, mode=modes.CBC(iv))

# ------------------------------------------------------------------------------
# encrypt/decrypt
# ------------------------------------------------------------------------------

# following https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#cryptography.hazmat.primitives.ciphers.Cipher

print("encrypt/decrypt")

secret_message = b"secret message"

padding_len = 16 - (len(secret_message) % 16)
padding = b"\0" * padding_len

encryptor = cipher.encryptor()
print(padding_len)
encrypted = encryptor.update(
    secret_message
)  # $ CryptographicOperation CryptographicOperationAlgorithm=AES CryptographicOperationInput=secret_message
encrypted += encryptor.update(
    padding
)  # $ CryptographicOperation CryptographicOperationAlgorithm=AES CryptographicOperationInput=padding
encrypted += encryptor.finalize()
import sys
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

# Cipher block size, expressed in bytes.
block = algorithms.AES.block_size/8

# Read the IV and the ciphertext from a file.
filename = raw_input('Type the file to decrypt: ')
with open(filename, 'rb') as f:
    iv = f.read(block)
    ciphertext = f.read()
if len(ciphertext) % block != 0:
    sys.exit('The file must be multiple of ' + str(block) + ' bytes.')

# Read the key in hexadecimal digits from keyboard.
key_hex = raw_input('Type the key in ' + str(2*block) + ' hexadecimal digits: ')
key = binascii.unhexlify(key_hex)

# Decrypt the ciphertext.
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), default_backend())
ctx = cipher.decryptor()
plaintext = ctx.update(ciphertext) + ctx.finalize()

# Write the decrypted text in the output file.
with open(filename + '.dec', 'wb') as f:
    f.write(plaintext)
print('Decrypted file: ' + filename + '.dec')
    skip_message="Does not support IDEA ECB",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeECB(object):
    test_ecb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "IDEA"),
        ["idea-ecb.txt"],
        lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
        lambda **kwargs: modes.ECB(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.IDEA(b"\x00" * 16), modes.CBC(b"\x00" * 8)),
    skip_message="Does not support IDEA CBC",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestIDEAModeCBC(object):
    test_cbc = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "IDEA"),
        ["idea-cbc.txt"],
        lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
        lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
Example #7
0
    def download_track(self, track, download_dir, quality=None, fallback=True, filename=None, renew=False,
                       with_metadata=True, with_lyrics=True, tag_separator=", ", show_messages=True,
                       progress_handler: BaseProgressHandler = None, **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:
            try:
                lyrics_data = track.get(
                    "lyrics", self.get_track_lyrics(track["id"])["info"])
            except Exception:
                with_lyrics = False

        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["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)

        if show_messages:
            print("Starting download of:", title)

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

        data_iter = res.iter_content(chunk_size)
        if show_messages:
            if not progress_handler:
                progress_handler = DefaultProgressHandler()
            if show_messages:
                progress_handler.initialize(data_iter, title, quality_key, total_filesize,
                                            chunk_size, track_id=track["id"])

        with open(download_path, "wb") as f:
            f.seek(0)

            for chunk in data_iter:
                current_chunk_size = len(chunk)

                if i % 3 > 0:
                    f.write(chunk)
                elif len(chunk) < chunk_size:
                    f.write(chunk)
                    if show_messages:
                        progress_handler.update(
                            track_id=track["id"], current_chunk_size=current_chunk_size)
                    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)

                    current_chunk_size = len(dec_data)

                i += 1
                if show_messages:
                    progress_handler.update(
                        track_id=track["id"], current_chunk_size=current_chunk_size)

        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(lyrics_data, lyrics_path)

        if show_messages:
            print("Track downloaded to:", download_path)
        if show_messages:
            progress_handler.close(
                track_id=track["id"], total_filesize=total_filesize)
        return download_path
Example #8
0
def unpadded_encrypt(data):
    iv = os.urandom(16)
    enc = Cipher(algorithms.AES(key), modes.CBC(iv),
                 default_backend()).encryptor()
    return iv, enc.update(data) + enc.finalize()
Example #9
0
 def update_aes(self, key: bytes) -> None:
     """Update AES."""
     self.aes = Cipher(algorithms.AES(key),
                       modes.CBC(self.iv),
                       backend=default_backend())
Example #10
0
    def _download(self, url, file_name):
        cookies = self.kwargs.get("cookies", None)
        start_time = time.time()
        m3u8 = M3U8(self.http.request("get", url, cookies=cookies).text)
        key = None

        def random_iv():
            return os.urandom(16)

        file_d = output(file_name[0], self.config, file_name[1])
        if file_d is None:
            return

        hls_time_stamp = self.kwargs.pop("hls_time_stamp", False)
        decryptor = None
        size_media = len(m3u8.media_segment)
        eta = ETA(size_media)
        total_duration = 0
        duration = 0
        max_duration = 0
        for index, i in enumerate(m3u8.media_segment):
            if "duration" in i["EXTINF"]:
                duration = i["EXTINF"]["duration"]
                max_duration = max(max_duration, duration)
                total_duration += duration
            item = get_full_url(i["URI"], url)

            if not self.config.get("silent"):
                if self.config.get("live"):
                    progressbar(
                        size_media, index + 1, "".join([
                            "DU: ",
                            str(timedelta(seconds=int(total_duration)))
                        ]))
                else:
                    eta.increment()
                    progressbar(size_media, index + 1,
                                "".join(["ETA: ", str(eta)]))

            data = self.http.request("get", item, cookies=cookies)
            if data.status_code == 404:
                break
            data = data.content
            if m3u8.encrypted:
                headers = {}
                if self.keycookie:
                    keycookies = self.keycookie
                else:
                    keycookies = cookies
                if self.authorization:
                    headers["authorization"] = self.authorization

                # Update key/decryptor
                if "EXT-X-KEY" in i:
                    keyurl = get_full_url(i["EXT-X-KEY"]["URI"], url)
                    if keyurl and keyurl[:4] == "skd:":
                        raise HLSException(keyurl,
                                           "Can't decrypt beacuse of DRM")
                    key = self.http.request("get",
                                            keyurl,
                                            cookies=keycookies,
                                            headers=headers).content
                    iv = binascii.unhexlify(i["EXT-X-KEY"]["IV"][2:].zfill(
                        32)) if "IV" in i["EXT-X-KEY"] else random_iv()
                    backend = default_backend()
                    cipher = Cipher(algorithms.AES(key),
                                    modes.CBC(iv),
                                    backend=backend)
                    decryptor = cipher.decryptor()

                if decryptor:
                    data = decryptor.update(data)
                else:
                    raise ValueError(
                        "No decryptor found for encrypted hls steam.")

            file_d.write(data)

            if self.config.get(
                    "capture_time"
            ) > 0 and total_duration >= self.config.get("capture_time") * 60:
                break

            if (size_media == (index + 1)) and self.config.get("live"):
                sleep_int = (start_time + max_duration * 2) - time.time()
                if sleep_int > 0:
                    time.sleep(sleep_int)

                size_media_old = size_media
                while size_media_old == size_media:
                    start_time = time.time()

                    if hls_time_stamp:
                        end_time_stamp = (datetime.utcnow() - timedelta(
                            minutes=1, seconds=max_duration * 2)).replace(
                                microsecond=0)
                        start_time_stamp = end_time_stamp - timedelta(
                            minutes=1)

                        base_url = url.split(".m3u8")[0]
                        url = "{}.m3u8?in={}&out={}?".format(
                            base_url, start_time_stamp.isoformat(),
                            end_time_stamp.isoformat())

                    new_m3u8 = M3U8(
                        self.http.request("get", url, cookies=cookies).text)
                    for n_m3u in new_m3u8.media_segment:
                        if not any(d["URI"] == n_m3u["URI"]
                                   for d in m3u8.media_segment):
                            m3u8.media_segment.append(n_m3u)

                    size_media = len(m3u8.media_segment)

                    if size_media_old == size_media:
                        time.sleep(max_duration)

        file_d.close()
        if not self.config.get("silent"):
            progress_stream.write("\n")
        self.finished = True
Example #11
0
 def test_cbc(self):
     with pytest.raises(TypeError):
         modes.CBC([1] * 16)
Example #12
0
def cipher(key):
    key = pad(key)
    return Cipher(algorithms.AES(key),
                  modes.CBC(key),
                  backend=default_backend())
Example #13
0
async def download_coroutine(session, url, output, key, media_sequence,
                             output_offset, tasks):
    if key.iv is not None:
        iv = str(key.iv)[2:]
    else:
        iv = "%032x" % media_sequence
    backend = default_backend()
    decode_hex = codecs.getdecoder("hex_codec")
    aes = Cipher(algorithms.AES(key.key_value),
                 modes.CBC(decode_hex(iv)[0]),
                 backend=backend)
    decryptor = aes.decryptor()
    output_offset.part_offset[str(media_sequence)] = 0
    async with session.get(url) as response:
        filename = output
        output_offset.part_size[str(
            media_sequence)] = response.headers['Content-Length']
        with open(filename, 'ab') as f_handle:
            while True:
                chunk = await response.content.read(blocksize)
                output_offset.offset += len(chunk)
                output_offset.part_offset[str(media_sequence)] += len(chunk)
                total_size = 0
                for part_size in output_offset.part_size.values():
                    total_size += int(part_size)
                if not tasks[0].done():
                    output_offset.progress_bar_print[0] = progress_bar_(
                        output_offset.offset,
                        output_offset.offset + 1,
                        size_adj(output_offset.offset, 'harddisk'),
                        '    @ ' + str(
                            size_adj(
                                output_offset.offset /
                                (time.process_time() - output_offset.start_t),
                                'internet')),
                        text_end_lenght=17,
                        center_bgc='',
                        defult_bgc='')
                else:
                    output_offset.progress_bar_print[0] = progress_bar_(
                        output_offset.offset,
                        total_size,
                        size_adj(output_offset.offset, 'harddisk') + '/' +
                        size_adj(total_size, 'harddisk'),
                        '%' +
                        str(round(output_offset.offset * 100 / total_size)) +
                        ' @ ' + str(
                            size_adj(
                                output_offset.offset /
                                (time.process_time() - output_offset.start_t),
                                'internet')),
                        text_end_lenght=17)
                output_offset.progress_bar_print[tasks.index(
                    asyncio.Task.current_task())] = progress_bar_(
                        output_offset.part_offset[str(media_sequence)],
                        int(response.headers['Content-Length']),
                        'Part#' + str(media_sequence),
                        '%' + str(
                            round(
                                output_offset.part_offset[str(media_sequence)]
                                * 100 /
                                int(response.headers['Content-Length']), 2)) +
                        ' ',
                        text_end_lenght=17)
                if not output_offset.printing:
                    output_offset.printing = True
                    print('\n'.join(output_offset.progress_bar_print) +
                          '\033[A' * len(output_offset.progress_bar_print) +
                          '\x0d')
                    output_offset.printing = False
                if not chunk:
                    break
                f_handle.write(decryptor.update(chunk))
            decryptor.finalize()
        return await response.release()
def decrypt(self,token,ttl=None):

  current_time=int(time.time())

  print("=======================================")

  #check if token in bytes
  if not isinstance(token,bytes):
    raise TypeError("token must be bytes")

   #lets first decode the base64 token
  try:
      data=base64.urlsafe_b64decode(token)
  except (TypeError,binascii.Error):
      raise InvalidToken


  print("Decoded Token")
  print("======================================")
    #print data
  print(binascii.hexlify(bytearray(data)))  

  print("++++++++++Analysis++++++++")


  print("=============================")
    
  if not data or six.indexbytes(data,0) !=0x80:
      raise InvalidToken

  try:
     timestamp,=struct.unpack(">Q",data[1:9])
     print("Time stamp:\t",timestamp)

  except struct.error:
     raise InvalidToken

  if ttl is not None:

    if timestamp + ttl < current_time: 
             raise InvalidToken
    if current_time + _MAX_CLOCK_SKEW < timestamp:
              raise InvalidToken

  h=HMAC(self._signing_key,hashes.SHA256(),backend=self._backend)
  h.update(data[:-32])

  try:
        h.verify(data[-32:])
  except InvalidSignature:
        raise InvalidToken

  iv = data[9:25]

  chipertext = data[25:-32]

  decryptor = Cipher(algorithms.AES(self._encryption_key), modes.CBC(iv),self._backend).decryptor()

  plaintext_padded = decryptor.update(chipertext)

  try:
        plaintext_padded += decryptor.finalize()
  except ValueEror:
        raise InvalidToken

  unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()

  unpadded = unpadder.update(plaintext_padded)

  try:
        unpadded += unpadder.finalize()
  except ValueEror:
        raise InvalidToken

  print("++++++++++++++++++++++++++++++++++++++++++")
  print("Decoded Value")
  print("===========================================")
  print(unpadded)

  return unpadded
Example #15
0
# Decryption
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()

print("-- ECB --")
print("Ciphertext is:", ciphertext)
print("Plaintext is:", plaintext)

### Task 1 ###
# Now it's your turn! CBC uses a similar interface to ECB, except that it requires both a key, and an iv
# Initialise these randomly now. Make the key 32 bytes and the IV 16 bytes.
key = os.urandom(32)
iv = os.urandom(16)

# Now fill in the code here to encrypt the same message as ECB, remember to use the CBC.
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
ciphertext = encryptor.update(message) + encryptor.finalize()
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()

print("-- CBC --")
print("Ciphertext is:", ciphertext)
print("Plaintext is:", plaintext)

### Task 2 ###
# Last we'll look at CTR mode. This mode converts a block cipher into
# a stream cipher. This means that CTR mode neatly handles messages that
# are not a multiple of the block length without needing padding.

# Here is just such a message, that's already been encrypted:
Example #16
0
 def test_creates_decryptor(self, backend):
     cipher = Cipher(algorithms.AES(binascii.unhexlify(b"0" * 32)),
                     modes.CBC(binascii.unhexlify(b"0" * 32)), backend)
     assert isinstance(cipher.decryptor(), interfaces.CipherContext)
 def _ouvrir_cipher(self):
     backend = default_backend()
     self._cipher = Cipher(algorithms.AES(self._password),
                           modes.CBC(self._iv),
                           backend=backend)
Example #18
0
File: crypto.py Project: zwunix/st2
def cryptography_symmetric_encrypt(encrypt_key, plaintext):
    """
    Encrypt the provided plaintext using AES encryption.

    NOTE 1: This function return a string which is fully compatible with Keyczar.Encrypt() method.

    NOTE 2: This function is loosely based on keyczar AESKey.Encrypt() (Apache 2.0 license).

    The final encrypted string value consists of:

    [message bytes][HMAC signature bytes for the message] where message consists of
    [keyczar header plaintext][IV bytes][ciphertext bytes]

    NOTE: Header itself is unused, but it's added so the format is compatible with keyczar format.

    """
    assert isinstance(encrypt_key,
                      AESKey), 'encrypt_key needs to be AESKey class instance'
    assert isinstance(plaintext, (six.text_type, six.string_types, six.binary_type)), \
        'plaintext needs to either be a string/unicode or bytes'

    aes_key_bytes = encrypt_key.aes_key_bytes
    hmac_key_bytes = encrypt_key.hmac_key_bytes

    assert isinstance(aes_key_bytes, six.binary_type)
    assert isinstance(hmac_key_bytes, six.binary_type)

    if isinstance(plaintext, (six.text_type, six.string_types)):
        # Convert data to bytes
        data = plaintext.encode('utf-8')
    else:
        data = plaintext

    # Pad data
    data = pkcs5_pad(data)

    # Generate IV
    iv_bytes = os.urandom(KEYCZAR_AES_BLOCK_SIZE)

    backend = default_backend()
    cipher = Cipher(algorithms.AES(aes_key_bytes),
                    modes.CBC(iv_bytes),
                    backend=backend)
    encryptor = cipher.encryptor()

    # NOTE: We don't care about actual Keyczar header value, we only care about the length (5
    # bytes) so we simply add 5 0's
    header_bytes = b'00000'

    ciphertext_bytes = encryptor.update(data) + encryptor.finalize()
    msg_bytes = header_bytes + iv_bytes + ciphertext_bytes

    # Generate HMAC signature for the message (header + IV + ciphertext)
    h = hmac.HMAC(hmac_key_bytes, hashes.SHA1(), backend=backend)
    h.update(msg_bytes)
    sig_bytes = h.finalize()

    result = msg_bytes + sig_bytes

    # Convert resulting byte string to hex notation ASCII string
    result = binascii.hexlify(result).upper()

    return result
Example #19
0
 def _get_cipher(self):
     backend = default_backend()
     return Cipher(algorithms.AES(self._enckey),
                   modes.CBC(self._enckey),
                   backend=backend)
Example #20
0
def cipher_aes_cbc(key, init_vec):
    return Cipher(algorithms.AES(key), modes.CBC(init_vec), default_backend())
Example #21
0
 def GetDecryptor(self):
     return ciphers.Cipher(algorithms.AES(self.key),
                           modes.CBC(self.iv),
                           backend=openssl.backend).decryptor()
Example #22
0
SUBID_RANGE_START = 2**31
# theoretical max limit is UINT32_MAX-1 ((2 ** 32) - 2)
# We use a smaller value to keep the topmost subid interval unused.
SUBID_RANGE_MAX = (2**32) - (2 * SUBID_COUNT)
SUBID_RANGE_SIZE = SUBID_RANGE_MAX - SUBID_RANGE_START
# threshold before DNA plugin requests a new range
SUBID_DNA_THRESHOLD = 500

# moved from ipaserver/install/krainstance.py::KRAInstance to avoid duplication
# as per https://pagure.io/freeipa/issue/8795
KRA_TRACKING_REQS = {
    'auditSigningCert cert-pki-kra': 'caAuditSigningCert',
    'transportCert cert-pki-kra': 'caTransportCert',
    'storageCert cert-pki-kra': 'caStorageCert',
}

ALLOWED_NETBIOS_CHARS = string.ascii_uppercase + string.digits + '-'

# vault data wrapping algorithms
VAULT_WRAPPING_3DES = 'des-ede3-cbc'
VAULT_WRAPPING_AES128_CBC = 'aes-128-cbc'
VAULT_WRAPPING_SUPPORTED_ALGOS = (
    # new default and supported since pki-kra >= 10.4
    VAULT_WRAPPING_AES128_CBC, )
VAULT_WRAPPING_DEFAULT_ALGO = VAULT_WRAPPING_AES128_CBC

# Add 3DES for backwards compatibility if supported
if backend.cipher_supported(algorithms.TripleDES(b"\x00" * 8),
                            modes.CBC(b"\x00" * 8)):
    VAULT_WRAPPING_SUPPORTED_ALGOS += (VAULT_WRAPPING_3DES, )
Example #23
0
def aes_cbcmac(key, input):
    encryptor = Cipher(algorithms.AES(key), modes.CBC(b'\0'*16), backend=default_backend()).encryptor()
    return (encryptor.update(input) + encryptor.finalize())[-16:]
Example #24
0
def testEnvelope(envFile, pubFile, privFile, expectedFile):

    # fetch your private and public key from files
    privKeyL, privN, d = readPrivateKey(privFile)

    pubKeyL, pubN, e = readPublicKey(pubFile)

    #private and public n and bitwise length of n should be equal
    assert privN == pubN
    assert privKeyL == pubKeyL

    #reconstruct private key to work with Crypto
    private_key = RSA.construct((privN, e, d))

    fileName, simConf, rsaConf, data, cryptKey, mode, iv = readEnvelope(
        envFile)

    assert fileName == expectedFile

    pubMethod, pubKeyLength = rsaConf

    simMethod, simKeyLength = simConf

    assert pubMethod == 'RSA'
    assert pubKeyLength == pubKeyL

    decryptor = PKCS1_OAEP.new(private_key)
    secretKey = decryptor.decrypt(cryptKey)

    assert len(secretKey) * 8 == simKeyLength

    if simMethod == 'AES':

        simMethod = algorithms.AES(secretKey)

    elif simMethod == 'DES':

        simMethod = algorithms.TripleDES(secretKey)

    else:
        raise Exception("Invalid symetric algorithm: " + simMethod)

    if mode == 'CBC':
        mode = modes.CBC(iv)
    elif mode == 'ECB':
        mode = modes.ECB()
    elif mode == 'OFB':
        mode = modes.OFB(iv)
    elif mode == 'CFB':
        mode = modes.CFB(iv)
    else:
        raise Exception("Invalid mode: " + mode)

    cipher = Cipher(algorithm=simMethod, mode=mode, backend=default_backend())

    decryptor = cipher.decryptor()

    dt = decryptor.update(data) + decryptor.finalize()

    unpadder = pad.PKCS7(128).unpadder()

    msg = unpadder.update(dt) + unpadder.finalize()

    realData = open(expectedFile, "rb").read()

    assert msg == realData
    print("ENVELOPE TEST SUCCESSFUL!")
 def update_aes(self, key):
     self.aes = Cipher(algorithms.AES(key), modes.CBC(self.iv),
                       backend=default_backend())
Example #26
0
import binascii
import os

import pytest

from cryptography.hazmat.backends.interfaces import CipherBackend
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.TripleDES(b"\x00" * 8), modes.CBC(b"\x00" * 8)),
    skip_message="Does not support TripleDES CBC",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestTripleDESModeCBC(object):
    test_KAT = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "3DES", "CBC"),
        [
            "TCBCinvperm.rsp",
            "TCBCpermop.rsp",
            "TCBCsubtab.rsp",
            "TCBCvarkey.rsp",
            "TCBCvartext.rsp",
        ],
        lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)),
Example #27
0
# The book can be downloaded from https://leanpub.com/cryptop
# Online Crypto Playgroud https://8gwifi.org
# Author Anish Nath

backend = default_backend()

iv = os.urandom(16)

# This AES key very short performing PKCS Padding
mykey = "myshortkey"
message = "Hello 8gwifi.org"

padder = padding.ANSIX923(128).padder()
padded_data = padder.update(mykey)

padded_data += padder.finalize()

#AES-128 CBC Mode Encyption
cipher = Cipher(algorithms.AES(padded_data), modes.CBC(iv), backend=backend)
e = cipher.encryptor()
ct = e.update(message) + e.finalize()

#AES-128 CBC Mode Decryption
# GCM tag used for authenticating the message.
cipher = Cipher(algorithms.AES(padded_data), modes.CBC(iv), backend=backend)
d = cipher.decryptor()

clear = d.update(ct) + d.finalize()

assert clear, message
    def decrypt_tls_pkt(self, tls_pkt, **kargs):
        # scapy screws up and changes the first byte if it can't decrypt it
        # from 22 to 23 (handshake to application). Check if this happens and fix
        packet_type = tls_pkt.type
        tls_pkt_bytes = raw(tls_pkt)
        tls_pkt_bytes = struct.pack("!B", packet_type) + tls_pkt_bytes[1:]

        print('type:', tls_pkt.type)
        # STUDENT TODO
        """
        1. The beginning of this function, already provided, extracts the data from scapy
        2. Do the TLS decryption process on tls_pkt_bytes
        3. Technically, you don't have to do the hmac. wget will do it right
        4. But if you check the hmac, you'll know your implementation is correct!
        5. return ONLY the decrypted plaintext data
        6. NOTE: When you do the HMAC, don't forget to re-create the header with the plaintext len!
        """
        # need to account for message header
        type_val = struct.pack('!b', tls_pkt_bytes[0])
        version_val = tls_pkt_bytes[1:3]
        ciphertext_len = tls_pkt_bytes[3:5]
        print('length of ciphertext:',
              int.from_bytes(ciphertext_len, byteorder='big'))
        tls_pkt_bytes = tls_pkt_bytes[5:]

        # get IV and create decryptor object
        iv = tls_pkt_bytes[:16]
        aes = algorithms.AES(self.read_enc)
        mode = modes.CBC(iv)
        cipher = Cipher(aes, mode, default_backend())
        decryptor = cipher.decryptor()

        # decrypt ciphertext
        ciphertext = tls_pkt_bytes[16:]
        decrypted_pkt = (decryptor.update(ciphertext) + decryptor.finalize())
        # print(type(decrypted_pkt[-1]))
        # padding = int.from_bytes(decrypted_pkt[-1], byteorder='big')
        padding = decrypted_pkt[-1]
        # remove padding from decrypted packet
        # print('padding bytes:',decrypted_pkt[(-1 * padding - 1):])
        decrypted_pkt = decrypted_pkt[:(-1 * padding - 1)]
        # print('decrypted packet:', decrypted_pkt)

        # extract plaintext + hmac from decrypted ciphertext (remove padding)
        plaintext_bytes = decrypted_pkt[:-1 * self.mac_key_size]
        # get hmac value from plaintext + hmac
        hashed_val = decrypted_pkt[-1 * self.mac_key_size:]

        # compare hmac sent in packet to our own computed hmac
        hmac = crypto_hmac.HMAC(self.read_mac, hashes.SHA1(),
                                default_backend())
        hmac.update(
            struct.pack('!q', self.read_seq_num) + type_val + version_val +
            struct.pack('!h', len(plaintext_bytes)) + plaintext_bytes)
        new_hashed_val = hmac.finalize()
        if new_hashed_val != hashed_val:
            # print('sequence num:', self.read_seq_num)
            # print('type_val:', type_val)
            # print('version_val', version_val)
            # print('len plaintext bytes:', len(plaintext_bytes))
            # print('plaintext:', plaintext_bytes)
            # print(struct.pack('q', self.read_seq_num) + type_val + version_val + struct.pack('h', len(plaintext_bytes)) + plaintext_bytes)
            # print('new hashed val:', new_hashed_val, 'len:', len(new_hashed_val))
            # print('old hashed val:', hashed_val, 'len:', len(hashed_val))
            raise ValueError("Hashes are not equal!")
        self.read_seq_num += 1

        return plaintext_bytes
    def download_part(self, url, output, key, media_sequence, tasks):
        if key.iv is not None:
            iv = str(key.iv)[2:]
        else:
            iv = "%032x" % media_sequence
        backend = default_backend()
        decode_hex = codecs.getdecoder("hex_codec")
        aes = Cipher(algorithms.AES(key.key_value),
                     modes.CBC(decode_hex(iv)[0]),
                     backend=backend)
        decryptor = aes.decryptor()
        self.part_offset[str(media_sequence)] = 0
        with self.session.get(url, stream=True) as response:
            response.raise_for_status()
            filename = output
            self.part_size[str(
                media_sequence)] = response.headers['Content-Length']
            with open(filename, 'ab') as f_handle:
                for chunk in response.iter_content(chunk_size=blocksize):
                    self.offset += len(chunk)
                    self.part_offset[str(media_sequence)] += len(chunk)
                    total_size = 0

                    finished_calculating_ = True
                    for i in threading.enumerate():
                        if i.name == 'compute_total_size_thread_':
                            finished_calculating_ = finished_calculating_ and not i.is_alive(
                            )
                    if not finished_calculating_:
                        self.progress_bar_print[0] = progress_bar_(
                            self.offset,
                            self.offset + 1,
                            size_adj(self.offset, 'harddisk'),
                            '    @ ' + str(
                                size_adj(
                                    self.offset /
                                    (time.process_time() - self.start_t),
                                    'internet')),
                            text_end_lenght=17,
                            center_bgc='',
                            defult_bgc='')
                    else:
                        for part_size in self.part_size.values():
                            total_size += int(part_size)
                        self.progress_bar_print[0] = progress_bar_(
                            self.offset,
                            total_size,
                            size_adj(self.offset, 'harddisk') + '/' +
                            size_adj(total_size, 'harddisk'),
                            '%' + str(round(self.offset * 100 / total_size)) +
                            ' @ ' + str(
                                size_adj(
                                    self.offset /
                                    (time.process_time() - self.start_t),
                                    'internet')),
                            text_end_lenght=17)
                    self.progress_bar_print[
                        self.tasks1.index(threading.currentThread()) +
                        1] = progress_bar_(
                            self.part_offset[str(media_sequence)],
                            int(response.headers['Content-Length']),
                            'Part#' + str(media_sequence),
                            '%' + str(
                                round(
                                    self.part_offset[str(media_sequence)] * 100
                                    / int(response.headers['Content-Length']),
                                    2)) + ' ',
                            text_end_lenght=17)
                    if not self.printing:
                        self.printing = True
                        print('\n'.join(self.progress_bar_print) +
                              '\033[A' * len(self.progress_bar_print) + '\x0d')
                        self.printing = False
                    if chunk:
                        f_handle.write(decryptor.update(chunk))
                decryptor.finalize()
            return filename
Example #30
0
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

if __name__ == '__main__':
    des_list = [
        '048ccd1fb6067ee0e304dc2025b96f4b',
        '296b66f3e332ab4c27501ca175c3b34d',
        '048ccd1fb6067ee0d4ca5da7e899def6',
        'bad5ede188bd1df1db8b06031867621a',
        '048ccd1fb6067ee0d6bd98bdb9a1a9b8a3f09b75107ca0da',
        'f316e31f45811c72c4e04380eac44e13',
        '47e046fb250a0b95cade3eff4ebda29c93157b2fc01c2430',
        '296b66f3e332ab4c27501ca175c3b34d',
    ]

    key = bytearray.fromhex('0ba950d08830c8079bded71b852934453db8f4ffff1f5842')
    algorithm = algorithms.TripleDES(key)
    cipher = Cipher(algorithm,
                    mode=modes.CBC(bytearray.fromhex('821fd38b9a7c0247')),
                    backend=default_backend())

    for string in des_list:
        decryptor = cipher.decryptor()
        print(decryptor.update(bytearray.fromhex(string)))