Exemple #1
0
 def test1(self):
     padded = pad(b(""), 4)
     self.assertTrue(padded == uh(b("04040404")))
     padded = pad(b(""), 4, 'pkcs7')
     self.assertTrue(padded == uh(b("04040404")))
     back = unpad(padded, 4)
     self.assertTrue(back == b(""))
Exemple #2
0
 def test1(self):
     padded = pad(b(""), 4)
     self.failUnless(padded == uh(b("04040404")))
     padded = pad(b(""), 4, 'pkcs7')
     self.failUnless(padded == uh(b("04040404")))
     back = unpad(padded, 4)
     self.failUnless(back == b(""))
Exemple #3
0
    def load_encrypted_keydata(self, keydata):
        """Load a key from encrypted keydata (in PEM format)."""
        lines = keydata.strip().replace(' ', '').splitlines()
        if not lines[1].startswith('Proc-Type:4,ENCRYPTED'):
            raise TypeError('Unsupported encryption')

        dek = lines[2].split(':')
        if len(dek) != 2 or dek[0] != 'DEK-Info':
            raise ValueError('PEM encryption method not supported')

        algo, salt = dek[1].split(',')
        salt = salt.decode('hex')

        if algo == 'DES-CBC':
            key = PBKDF1(self.passphrase, salt, 8, 1, MD5)
            obj = DES.new(key, DES.MODE_CBC, salt)

        elif algo == 'DES-EDE3-CBC':
            key = PBKDF1(self.passphrase, salt, 16, 1, MD5)
            key+= PBKDF1(key + passphrase, salt, 8, 1, MD5)
            obj = DES3.new(key, DES3.MOE_CBC, salt)

        elif algo == 'AES-128-CBC':
            key = PBKDF1(self.passphrase, salt[:8], 16, 1, MD5)
            obj = AES.new(key, AES.MODE_CBC, salt)

        else:
            raise TypeError('%s: cipher not supported' % (algo,))

        lines = lines[3:-1]
        data = base64.b64decode(''.join(lines))
        return unpad(obj.decrypt(data), obj.block_size)
Exemple #4
0
    def decrypt(self, file_path):
        if not os.path.exists(file_path):
            raise ValueError('Input file path not exists: %s ', file_path)

        with open(file_path, 'rb') as f:
            data_to_decrypt = f.read()
        return unpad(self.cipher.decrypt(data_to_decrypt), self.multiple_of_byte)
Exemple #5
0
 def decrypt(self, encrypt_string):
     if self.use_urlsafe:
         encrypt_byte_string = base64.urlsafe_b64decode(bytes(map(ord, encrypt_string)))
     else:
         encrypt_byte_string = base64.b64decode(bytes(map(ord, encrypt_string)))
     pad_byte_string = self.cipher.decrypt(encrypt_byte_string)
     string = unpad(pad_byte_string, self.multiple_of_byte).decode('utf-8')
     return string
Exemple #6
0
    def decrypt(data, passphrase):
        """Decrypt a piece of data using a passphrase and *PBES1*.

        The algorithm to use is automatically detected.

        :Parameters:
          data : byte string
            The piece of data to decrypt.
          passphrase : byte string
            The passphrase to use for decrypting the data.
        :Returns:
          The decrypted data, as a binary string.
        """

        encrypted_private_key_info = decode_der(DerSequence, data)
        encrypted_algorithm = decode_der(
                                DerSequence,
                                encrypted_private_key_info[0]
                                )
        encrypted_data = decode_der(
                            DerOctetString,
                            encrypted_private_key_info[1]
                            ).payload

        pbe_oid = decode_der(DerObjectId, encrypted_algorithm[0]).value
        cipher_params = {}
        if pbe_oid == "1.2.840.113549.1.5.3":
            # PBE_MD5_DES_CBC
            hashmod = MD5
            ciphermod = DES
        elif pbe_oid == "1.2.840.113549.1.5.6":
            # PBE_MD5_RC2_CBC
            hashmod = MD5
            ciphermod = ARC2
            cipher_params['effective_keylen'] = 64
        elif pbe_oid == "1.2.840.113549.1.5.10":
            # PBE_SHA1_DES_CBC
            hashmod = SHA1
            ciphermod = DES
        elif pbe_oid == "1.2.840.113549.1.5.11":
            # PBE_SHA1_RC2_CBC
            hashmod = SHA1
            ciphermod = ARC2
            cipher_params['effective_keylen'] = 64
        else:
            raise PbesError("Unknown OID for PBES1")

        pbe_params = decode_der(DerSequence, encrypted_algorithm[1])
        salt = decode_der(DerOctetString, pbe_params[0]).payload
        iterations = pbe_params[1]

        key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod)
        key, iv = key_iv[:8], key_iv[8:]

        cipher = ciphermod.new(key, ciphermod.MODE_CBC, iv, **cipher_params)
        pt = cipher.decrypt(encrypted_data)
        return unpad(pt, cipher.block_size)
Exemple #7
0
 def decrypt(self, encrypt_string):
     self.cipher = self.gen_cipher()
     if self.use_urlsafe:
         encrypt_byte_string = base64.urlsafe_b64decode(bytes(map(ord, encrypt_string)))
     else:
         encrypt_byte_string = base64.b64decode(bytes(map(ord, encrypt_string)))
     pad_byte_string = self.cipher.decrypt(encrypt_byte_string)
     original_string = unpad(pad_byte_string, AES.block_size).decode('utf-8')
     return original_string
def file_decrypt(password, file_path, output_file_path):
    key = generate_key(password)
    # 使用ECB模式进行加密解密
    cipher = AES.new(key, AES.MODE_ECB)
    # 设置加密解密时分块读取10240KB
    read_kb = 10240
    block_size = read_kb * 1024
    data_handle_func = cipher.decrypt
    # 读取到文件尾部时,执行解密后尾部去除补位
    data_end_handle_func = lambda d: unpad(cipher.decrypt(d), MULTIPLE_OF_BYTE)
    file_handle(file_path, output_file_path, block_size, data_handle_func, data_end_handle_func)
Exemple #9
0
# A: msg_a_t = Alice, Bob, Ra
msg_a_t = []
msg_a_t.append("Alice")
msg_a_t.append("Bob")
msg_a_t.append(a_random.hex())
json_a_t = json.dumps(msg_a_t)

# A->T: msg_a_t
print("A->T: " + json_a_t)
socket.enviar(json_a_t.encode("utf-8"))

# T->A: E_AT(Ra, Bob, K_AB, E_BT(K_AB, Alice))
# A: Descifrar msg_t_a
datos = socket.recibir()
decipher_aes_a_t = AES.new(key_a_t, AES.MODE_ECB)
json_t_a = unpad(decipher_aes_a_t.decrypt(datos),
                 BLOCK_SIZE_AES).decode("utf-8")
print("T->A (Clear): " + json_t_a)
msg_t_a = json.loads(json_t_a)

# A: Comprobar campos de msg_t_a
t_random, t_bob, t_k_ab, t_bt = msg_t_a
t_random = bytearray.fromhex(t_random)
t_k_ab = bytearray.fromhex(t_k_ab)
if (a_random != t_random):
    print("ERROR: Nonce Equivocado")
    socket.cerrar()
    exit()
if (a_bob != t_bob):
    print("ERROR: Receptor incorrecto")
    socket.cerrar()
    exit()
Exemple #10
0
def decryptCBC(ciphertext, key):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = cipher.decrypt(ciphertext)
    return unpad(plaintext, AES.block_size)
Exemple #11
0
def response(flow: http.HTTPFlow):
    global MSLAESKey
    global ClientPublicKey
    global ProxyRSAKey

    if isPathEvaluator(flow.request.pretty_url):
        logging.info("Netflix pathEvaluator response: " +
                     flow.request.pretty_url)
        if IS_PYTHON2:
            logging.info(
                unquote(flow.request.content.decode('utf-8')).decode('utf-8'))
        else:
            logging.info(unquote(flow.request.content.decode('utf-8')))

    if isMSLAPI(flow.request.pretty_url):
        logging.info("Netflix msl response: " + flow.request.pretty_url)
        parsedResponse = None
        parsedRespChunks = []
        headerEndOffset = -1

        try:
            parsedResponse = json.loads(flow.response.content)
        except json.JSONDecodeError as e:
            headerEndOffset = e.pos
            parsedResponse = json.loads(flow.response.content[0:e.pos])
            appendChunk(parsedRespChunks, flow.response.content[e.pos:])

        #logging.info(flow.response.content.decode())
        if not "headerdata" in parsedResponse.keys():
            return

        headerData = b64decode(parsedResponse["headerdata"])
        #logging.info(headerData.decode())

        parsedHeaderData = json.loads(headerData)
        if "keyresponsedata" in parsedHeaderData.keys():
            hmacKeyEncStr = parsedHeaderData["keyresponsedata"]["keydata"][
                "hmackey"]
            encKeyEncStr = parsedHeaderData["keyresponsedata"]["keydata"][
                "encryptionkey"]

            proxyCipher = PKCS1_OAEP.new(ProxyRSAKey)
            clientCipher = PKCS1_OAEP.new(ClientPublicKey)

            global MSLAESKey

            if Mechanism == "JWK_RSA":
                hmacKeyEnv = proxyCipher.decrypt(b64decode(hmacKeyEncStr))
                encKeyEnv = proxyCipher.decrypt(b64decode(encKeyEncStr))

                hmacKeyEncStr = b64encode(
                    clientCipher.encrypt(hmacKeyEnv)).decode()
                encKeyEncStr = b64encode(
                    clientCipher.encrypt(encKeyEnv)).decode()

                MSLAESKey = b64urldecode(json.loads(encKeyEnv)["k"])
                logging.info("MSL AES key: " + json.loads(encKeyEnv)["k"])
                updateSession()

            elif Mechanism == "JWEJS_RSA":
                hmacKeyJWEJS = json.loads(b64decode(hmacKeyEncStr))
                encKeyJWEJS = json.loads(b64decode(encKeyEncStr))

                logging.info("encryptionkey before: " +
                             b64decode(encKeyEncStr).decode())
                logging.info("hmackey before: " +
                             b64decode(hmacKeyEncStr).decode())

                encKey = proxyCipher.decrypt(
                    b64urldecode(
                        encKeyJWEJS["recipients"][0]["encrypted_key"]))
                gcmCipher = AES.new(
                    encKey, AES.MODE_GCM,
                    b64urldecode(encKeyJWEJS["initialization_vector"]))
                encKeyPlain = gcmCipher.decrypt(
                    b64urldecode(encKeyJWEJS["ciphertext"])).decode()

                #logging.info("JWEJS message: " + encKeyPlain)

                MSLAESKey = b64urldecode(json.loads(encKeyPlain)["k"])
                logging.info("MSL AES key: " + json.loads(encKeyPlain)["k"])
                updateSession()

                encKeyJWEJS["recipients"][0]["encrypted_key"] = b64urlencode(
                    clientCipher.encrypt(encKey)).decode()

                gcmCipher = AES.new(
                    encKey, AES.MODE_GCM,
                    b64urldecode(encKeyJWEJS["initialization_vector"]))
                aad = encKeyJWEJS["recipients"][0][
                    "header"] + "." + encKeyJWEJS["recipients"][0][
                        "encrypted_key"] + "." + encKeyJWEJS[
                            "initialization_vector"]
                gcmCipher.update(aad.encode())
                cip, tag = gcmCipher.encrypt_and_digest(encKeyPlain.encode())
                #logging.info("expected ciphertext: " + b64urlencode(cip).decode())
                #logging.info("expected integrity_value: " + b64urlencode(tag).decode())

                encKeyJWEJS["recipients"][0]["integrity_value"] = b64urlencode(
                    tag).decode()

                encKeyJWEJS_str = json.dumps(encKeyJWEJS)
                encKeyJWEJS_str = re.sub(r'[\s+]', '', encKeyJWEJS_str)
                encKeyEncStr = b64encode(encKeyJWEJS_str.encode()).decode()

                hmacKey = proxyCipher.decrypt(
                    b64urldecode(
                        hmacKeyJWEJS["recipients"][0]["encrypted_key"]))
                gcmCipher = AES.new(
                    hmacKey, AES.MODE_GCM,
                    b64urldecode(hmacKeyJWEJS["initialization_vector"]))
                hmacKeyPlain = gcmCipher.decrypt(
                    b64urldecode(hmacKeyJWEJS["ciphertext"])).decode()

                hmacKeyJWEJS["recipients"][0]["encrypted_key"] = b64urlencode(
                    clientCipher.encrypt(hmacKey)).decode()

                gcmCipher = AES.new(
                    hmacKey, AES.MODE_GCM,
                    b64urldecode(hmacKeyJWEJS["initialization_vector"]))
                aad = hmacKeyJWEJS["recipients"][0][
                    "header"] + "." + hmacKeyJWEJS["recipients"][0][
                        "encrypted_key"] + "." + hmacKeyJWEJS[
                            "initialization_vector"]
                gcmCipher.update(aad.encode())
                cip, tag = gcmCipher.encrypt_and_digest(hmacKeyPlain.encode())
                #logging.info("expected ciphertext: " + b64urlencode(cip).decode())
                #logging.info("expected integrity_value: " + b64urlencode(tag).decode())

                hmacKeyJWEJS["recipients"][0][
                    "integrity_value"] = b64urlencode(tag).decode()

                hmacKeyJWEJS_str = json.dumps(hmacKeyJWEJS)
                hmacKeyJWEJS_str = re.sub(r'[\s+]', '', hmacKeyJWEJS_str)
                hmacKeyEncStr = b64encode(hmacKeyJWEJS_str.encode()).decode()

                logging.info("encryptionkey after: " + encKeyJWEJS_str)
                logging.info("hmackey after: " + hmacKeyJWEJS_str)

            #logging.info("Signature after: " + parsedResponse["signature"])
            parsedHeaderData["keyresponsedata"]["keydata"][
                "hmackey"] = hmacKeyEncStr
            parsedHeaderData["keyresponsedata"]["keydata"][
                "encryptionkey"] = encKeyEncStr

            headerDataModified = json.dumps(parsedHeaderData).encode()
            parsedResponse["headerdata"] = b64encode(
                headerDataModified).decode()

            #logging.info("Signature before: " + parsedResponse["signature"])

            headerDataHash = SHA256.new(headerDataModified)
            parsedResponse["signature"] = b64encode(
                pkcs1_15.new(ProxySignKey).sign(headerDataHash)).decode()

            contentRest = b""
            if headerEndOffset != -1:
                contentRest = flow.response.content[headerEndOffset:]

            flow.response.content = json.dumps(
                parsedResponse).encode() + contentRest

            #logging.info(b64decode(parsedResponse["headerdata"]).decode())
            #logging.info(flow.response.content.decode())
        elif "ciphertext" in parsedHeaderData.keys() and MSLAESKey is not None:
            iv = b64decode(parsedHeaderData["iv"])
            cipher = AES.new(MSLAESKey, AES.MODE_CBC, iv)

            cipherText = b64decode(parsedHeaderData["ciphertext"])
            try:
                plainText = unpad(cipher.decrypt(cipherText), 16)
                logging.info(plainText.decode())
            except ValueError:
                logging.error("Error: incorrect AES key")

        #logging.info("Number of chunks: " + str(len(parsedRespChunks)))
        for chunk in parsedRespChunks:
            if MSLAESKey is None:
                continue

            payload = json.loads(b64decode(chunk["payload"]))
            iv = b64decode(payload["iv"])
            cipher = AES.new(MSLAESKey, AES.MODE_CBC, iv)

            cipherText = b64decode(payload["ciphertext"])
            try:
                plainText = unpad(cipher.decrypt(cipherText), 16)
            except ValueError:
                logging.error("Error: incorrect AES key")
                continue

            plainJSON = None

            try:
                plainJSON = json.loads(plainText)
            except json.JSONDecodeError as e:
                plainJSON = json.loads(plainText[0:e.pos])

            #logging.info(plainText.decode())
            decoded = b64decode(plainJSON["data"])
            if "compressionalgo" in plainJSON.keys():
                if plainJSON["compressionalgo"] == "GZIP":
                    decoded = gzip.decompress(decoded)
                elif plainJSON["compressionalgo"] == "LZW":
                    decoded = lzw_decompress(decoded)

            logging.info(decoded.decode())

    elif "/cadmium-playercore" in flow.request.pretty_url:
        logging.info("Netflix cadmium player response")
        proxySignKeyStr = b64encode(ProxySignKey.publickey().exportKey("DER"))
        flow.response.content = flow.response.content.replace(
            ServerSignPubKey.encode(),
            proxySignKeyStr).replace(ServerSignPubKey2.encode(),
                                     proxySignKeyStr)
Exemple #12
0
 def test1(self):
     padded = pad(b(""), 4, 'iso7816')
     self.failUnless(padded == uh(b("80000000")))
     back = unpad(padded, 4, 'iso7816')
     self.failUnless(back == b(""))
Exemple #13
0
 def test1(self):
     padded = pad(b(""), 4, 'x923')
     self.failUnless(padded == uh(b("00000004")))
     back = unpad(padded, 4, 'x923')
     self.failUnless(back == b(""))
Exemple #14
0
def decode(pem_data, passphrase=None):
    """Decode a PEM block into binary.

    :Parameters:
      pem_data : string
        The PEM block.
      passphrase : byte string
        If given and the PEM block is encrypted,
        the key will be derived from the passphrase.
    :Returns:
      A tuple with the binary data, the marker string, and a boolean to
      indicate if decryption was performed.
    :Raises ValueError:
      If decoding fails, if the PEM file is encrypted and no passphrase has
      been provided or if the passphrase is incorrect.
    """

    # Verify Pre-Encapsulation Boundary
    r = re.compile("\s*-----BEGIN (.*)-----\n")
    m = r.match(pem_data)
    if not m:
        raise ValueError("Not a valid PEM pre boundary")
    marker = m.group(1)

    # Verify Post-Encapsulation Boundary
    r = re.compile("-----END (.*)-----\s*$")
    m = r.search(pem_data)
    if not m or m.group(1) != marker:
        raise ValueError("Not a valid PEM post boundary")

    # Removes spaces and slit on lines
    lines = pem_data.replace(" ", '').split()

    # Decrypts, if necessary
    if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
        if not passphrase:
            raise ValueError("PEM is encrypted, but no passphrase available")
        DEK = lines[2].split(':')
        if len(DEK) != 2 or DEK[0] != 'DEK-Info':
            raise ValueError("PEM encryption format not supported.")
        algo, salt = DEK[1].split(',')
        salt = unhexlify(tobytes(salt))
        if algo == "DES-CBC":
            # This is EVP_BytesToKey in OpenSSL
            key = PBKDF1(passphrase, salt, 8, 1, MD5)
            objdec = DES.new(key, DES.MODE_CBC, salt)
        elif algo == "DES-EDE3-CBC":
            # Note that EVP_BytesToKey is note exactly the same as PBKDF1
            key = PBKDF1(passphrase, salt, 16, 1, MD5)
            key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
            objdec = DES3.new(key, DES3.MODE_CBC, salt)
        elif algo == "AES-128-CBC":
            key = PBKDF1(passphrase, salt[:8], 16, 1, MD5)
            objdec = AES.new(key, AES.MODE_CBC, salt)
        else:
            raise ValueError("Unsupport PEM encryption algorithm.")
        lines = lines[2:]
    else:
        objdec = None

    # Decode body
    data = a2b_base64(b(''.join(lines[1:-1])))
    enc_flag = False
    if objdec:
        data = unpad(objdec.decrypt(data), objdec.block_size)
        enc_flag = True

    return (data, marker, enc_flag)
Exemple #15
0
    def decrypt(data, passphrase):
        """Decrypt a piece of data using a passphrase and *PBES2*.

        The algorithm to use is automatically detected.

        :Parameters:
          data : byte string
            The piece of data to decrypt.
          passphrase : byte string
            The passphrase to use for decrypting the data.
        :Returns:
          The decrypted data, as a binary string.
        """

        enc_private_key_info = DerSequence().decode(data, nr_elements=2)
        enc_algo = DerSequence().decode(enc_private_key_info[0])
        encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload

        pbe_oid = DerObjectId().decode(enc_algo[0]).value
        if pbe_oid != _OID_PBES2:
            raise PbesError("Not a PBES2 object")

        pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2)

        ### Key Derivation Function selection
        kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2)
        kdf_oid = DerObjectId().decode(kdf_info[0]).value

        kdf_key_length = None

        # We only support PBKDF2 or scrypt
        if kdf_oid == _OID_PBKDF2:

            pbkdf2_params = DerSequence().decode(kdf_info[1], nr_elements=(2, 3, 4))
            salt = DerOctetString().decode(pbkdf2_params[0]).payload
            iteration_count = pbkdf2_params[1]

            left = len(pbkdf2_params) - 2
            idx = 2

            if left > 0:
                try:
                    kdf_key_length = pbkdf2_params[idx] - 0
                    left -= 1
                    idx += 1
                except TypeError:
                    pass

            # Default is HMAC-SHA1
            pbkdf2_prf_oid = "1.2.840.113549.2.7"
            if left > 0:
                pbkdf2_prf_algo_id = DerSequence().decode(pbkdf2_params[idx])
                pbkdf2_prf_oid = DerObjectId().decode(pbkdf2_prf_algo_id[0]).value

        elif kdf_oid == _OID_SCRYPT:

            scrypt_params = DerSequence().decode(kdf_info[1], nr_elements=(4, 5))
            salt = DerOctetString().decode(scrypt_params[0]).payload
            iteration_count, scrypt_r, scrypt_p = [scrypt_params[x]
                                                   for x in (1, 2, 3)]
            if len(scrypt_params) > 4:
                kdf_key_length = scrypt_params[4]
            else:
                kdf_key_length = None
        else:
            raise PbesError("Unsupported PBES2 KDF")

        ### Cipher selection
        enc_info = DerSequence().decode(pbes2_params[1])
        enc_oid = DerObjectId().decode(enc_info[0]).value

        if enc_oid == _OID_DES_EDE3_CBC:
            # DES_EDE3_CBC
            ciphermod = DES3
            key_size = 24
        elif enc_oid == _OID_AES128_CBC:
            # AES128_CBC
            ciphermod = AES
            key_size = 16
        elif enc_oid == _OID_AES192_CBC:
            # AES192_CBC
            ciphermod = AES
            key_size = 24
        elif enc_oid == _OID_AES256_CBC:
            # AES256_CBC
            ciphermod = AES
            key_size = 32
        else:
            raise PbesError("Unsupported PBES2 cipher")

        if kdf_key_length and kdf_key_length != key_size:
            raise PbesError("Mismatch between PBES2 KDF parameters"
                            " and selected cipher")

        IV = DerOctetString().decode(enc_info[1]).payload

        # Create cipher
        if kdf_oid == _OID_PBKDF2:
            if pbkdf2_prf_oid == _OID_HMAC_SHA1:
                hmac_hash_module = SHA1
            elif pbkdf2_prf_oid == _OID_HMAC_SHA224:
                hmac_hash_module = SHA224
            elif pbkdf2_prf_oid == _OID_HMAC_SHA256:
                hmac_hash_module = SHA256
            elif pbkdf2_prf_oid == _OID_HMAC_SHA384:
                hmac_hash_module = SHA384
            elif pbkdf2_prf_oid == _OID_HMAC_SHA512:
                hmac_hash_module = SHA512
            else:
                raise PbesError("Unsupported HMAC %s" % pbkdf2_prf_oid)

            key = PBKDF2(passphrase, salt, key_size, iteration_count,
                         hmac_hash_module=hmac_hash_module)
        else:
            key = scrypt(passphrase, salt, key_size, iteration_count,
                         scrypt_r, scrypt_p)
        cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV)

        # Decrypt data
        pt = cipher.decrypt(encrypted_data)
        return unpad(pt, cipher.block_size)
def decrypt(text):
    '''Decrypts data using AES 256'''
    cipher = AES.new(key, AES.MODE_ECB)
    decrypted_bytes = cipher.decrypt(text)
    return unpad(decrypted_bytes, 32).decode('utf-8')
Exemple #17
0
def descifrar(ciphertext):
    plaintext = ""
    if len(ciphertext) > 0:
        cipher = AES.new(key, AES.MODE_ECB)
        plaintext = unpad(cipher.decrypt(bytes.fromhex(ciphertext)), AES.block_size).decode('utf-8')
    return plaintext
Exemple #18
0
 def test4(self):
     padded = pad(uh(b("1234567890")), 4, 'x923')
     self.failUnless(padded == uh(b("1234567890000003")))
     back = unpad(padded, 4, 'x923')
     self.failUnless(back == uh(b("1234567890")))
Exemple #19
0
 def test3(self):
     padded = pad(uh(b("123456")), 4, 'x923')
     self.failUnless(padded == uh(b("12345601")))
     back = unpad(padded, 4, 'x923')
     self.failUnless(back == uh(b("123456")))
Exemple #20
0
 def test2(self):
     padded = pad(uh(b("12345678")), 4, 'x923')
     self.failUnless(padded == uh(b("1234567800000004")))
     back = unpad(padded, 4, 'x923')
     self.failUnless(back == uh(b("12345678")))
 def test3(self):
     padded = pad(uh(b("123456")), 4, 'iso7816')
     self.failUnless(padded == uh(b("12345680")))
     #import pdb; pdb.set_trace()
     back = unpad(padded, 4, 'iso7816')
     self.failUnless(back == uh(b("123456")))
Exemple #22
0
def D(CTX, KEY):
    return unpad(
        AES.new(b64decode(KEY), AES.MODE_ECB).decrypt(b64decode(CTX)),
        AES.block_size)
 def test2(self):
     padded = pad(uh(b("12345678")), 4)
     self.failUnless(padded == uh(b("1234567804040404")))
     back = unpad(padded, 4)
     self.failUnless(back == uh(b("12345678")))
from base64 import b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from Crypto.Hash import SHA256, SHA512


key_digest = '31af112461ca634ea7468e685a6edec4b63a1b1a324a2d77e2172d0d14a84ac455c7448836ec9ab98a614e14487e010ed88ef80f081a7bf911b8e20e04e1c9d7'
iv = b64decode('750dddjhwyJSJ2YhRFZAjw==')
flag = b64decode('L1i39WIWpALQBHZiZWzXdU/mCzwD6pbVZowcJiGUz237mfOBEuYK3/dpJMHq+DP4')

pswd = input('Insert password: '******'You did it: ', pt.decode('utf-8'))
else:
    print("lol nope")


Exemple #25
0
 def decrypt(self, file_path, output_file_path):
     self.cipher = self.gen_cipher()
     data_handle_func = self.cipher.decrypt
     # 读取到文件尾部时,执行解密后尾部去除补位
     data_end_handle_func = lambda d: unpad(self.cipher.decrypt(d), AES.block_size)
     self.handle(file_path, output_file_path, data_handle_func, data_end_handle_func)
    bit += str(sList[i] & 1)
    if (len(bit) == 8):
        val = int(bit, 2)
        resImg.append(val)
        bit = ''
    pbar.update(1)
    i += 1
pbar.close()

print('Decrypting data...')
while True:
    try:
        password = getpass()
        sha = bytes(hashlib.sha256(bytes(password.encode())).digest())
        iv = b'This is an IV456'
        cipher = AES.new(sha, AES.MODE_CBC, iv)
        dct = unpad(cipher.decrypt(bytes(resImg)), AES.block_size)
        break
    except ValueError:
        print('Entered password is wrong! unable to decrypt.')

resImgList = list(b64decode(dct))
outputImg = np.array(resImgList).reshape((n, m, 3))
print('Writing output to jpg file...')
try:
    cv2.imwrite(output, outputImg)
    print('Successfully written to file ' + output)
except Exception as inst:
    print('Exception caught!')
    print(inst.with_traceback)
    print(inst.args)
Exemple #27
0
 def test4(self):
     padded = pad(uh(b("1234567890")), 4, 'x923')
     self.assertTrue(padded == uh(b("1234567890000003")))
     back = unpad(padded, 4, 'x923')
     self.assertTrue(back == uh(b("1234567890")))
Exemple #28
0
    def aes_decrypt(
        self,
        key: str,
        iv: str = "00000000000000000000000000000000",
        mode: str = "CBC",
        hex_key: bool = False,
        hex_iv: bool = True,
    ):
        """Decrypt raw state encrypted with DES. 

        Advanced Encryption Standard (AES) is a U.S. Federal Information Processing 
        Standard (FIPS). It was selected after a 5-year process where 15 competing 
        designs were evaluated.<br><br><b>Key:</b> The following algorithms will 
        be used based on the size of the 
        
        key:
            16 bytes = AES-128
            24 bytes = AES-192
            32 bytes = AES-256
        
        You can generate a password-based key using one of the KDF operations. 
        IV: The Initialization Vector should be 16 bytes long. If not entered, it will 
        default to 16 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used.
        
        Args:
            key (str): Required. The secret key
            iv (str, optional): IV for certain modes only. 
                Defaults to '00000000000000000000000000000000'.
            mode (str, optional): Encryption mode. Defaults to 'CBC'.
            hex_key (bool, optional): If the secret key is a hex string. Defaults to False.
            hex_iv (bool, optional): If the IV is a hex string. Defaults to True.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> c = Chepy("5fb8c186394fc399849b89d3b6605fa3")
            >>> c.hex_to_str()
            >>> c.aes_decrypt("7365637265742070617373776f726421", hex_key=True)
            >>> c.o
            b"some data"
        """

        assert mode in ["CBC", "OFB", "CTR", "ECB", "GCM"], "Not a valid mode."

        key, iv = self._convert_key(key, iv, hex_key, hex_iv)

        if mode == "CBC":
            cipher = AES.new(key, mode=AES.MODE_CBC, iv=iv)
            self.state = unpad(cipher.decrypt(self._convert_to_bytes()), 16)
            return self
        elif mode == "ECB":
            cipher = AES.new(key, mode=AES.MODE_ECB)
            self.state = unpad(cipher.decrypt(self._convert_to_bytes()), 16)
            return self
        elif mode == "CTR":
            cipher = AES.new(key, mode=AES.MODE_CTR, nonce=b"")
            self.state = cipher.decrypt(self._convert_to_bytes())
            return self
        elif mode == "GCM":
            cipher = AES.new(
                key,
                mode=AES.MODE_GCM,
                nonce=binascii.unhexlify("00000000000000000000000000000000"),
            )
            self.state = cipher.decrypt(self._convert_to_bytes())
            return self
        elif mode == "OFB":
            cipher = AES.new(key, mode=AES.MODE_OFB, iv=iv)
            self.state = cipher.decrypt(self._convert_to_bytes())
            return self
Exemple #29
0
 def decrypt(self, file_path):
     block_size = self.read_kb * 1024
     data_handle_func = self.cipher.decrypt
     # 读取到文件尾部时,执行解密后尾部去除补位
     data_end_handle_func = lambda d: unpad(self.cipher.decrypt(d), self.multiple_of_byte)
     return ByteCrypto.handle(file_path, block_size, data_handle_func, data_end_handle_func)
Exemple #30
0
privKeyObj = RSA.importKey(binPrivKey)
pubKeyObj = RSA.importKey(binPubKey)
#KRIPTIRAMO PORUKU SIM KLJUCEM
cipher = Sim.new(Simkljuc, SimC)
input = pad(data.read(), 64)
C1 = cipher.encrypt(input)
#JAVNIM KLJUCEM PRIMATELJA KRIPTIRAMO SIMETRICNI KLJUC
cipher = PKCS1_OAEP.new(pubKeyObj)
C2 = cipher.encrypt(Simkljuc)
rj = b64encode(str(C2))
print(rj)
cipher = PKCS1_OAEP.new(privKeyObj)
KljucZaDek = cipher.decrypt(C2)
cipher = Sim.new(KljucZaDek, SimC)
ciphertext = cipher.decrypt(C1)
print(unpad(ciphertext, 64))
with open('digitalnaomotnica.txt', 'w') as f:
    f.write('''---BEGIN OS2 CRYPTO DATA---
Description:
    Envelope
File name:
    datoteka.txt
Method:
    {simetricni}
    {asimetricni}
Key length:
    {sym_key_len}
    {asym_key_len}
Envelope data:
    {data}
Envelope crypt key:
Exemple #31
0
def request(flow: http.HTTPFlow):
    global MSLAESKey
    if MSLAESKey is None:
        initSession()

    if isPathEvaluator(flow.request.pretty_url):
        logging.info("Netflix pathEvaluator request: " +
                     flow.request.pretty_url)
        if IS_PYTHON2:
            logging.info(
                unquote(flow.request.content.decode('utf-8')).decode('utf-8'))
        else:
            logging.info(unquote(flow.request.content.decode('utf-8')))

    if isMSLAPI(flow.request.pretty_url):
        logging.info("Netflix msl request: " + flow.request.pretty_url)
        parsedRequest = None
        parsedReqChunks = []
        headerEndOffset = -1

        try:
            parsedRequest = json.loads(flow.request.content)
        except json.JSONDecodeError as e:
            headerEndOffset = e.pos
            parsedRequest = json.loads(flow.request.content[0:e.pos])
            appendChunk(parsedReqChunks, flow.request.content[e.pos:])

        #logging.info(flow.request.content.decode())
        if not "headerdata" in parsedRequest.keys():
            return

        headerData = b64decode(parsedRequest["headerdata"])
        #logging.info(headerData.decode())

        parsedHeaderData = json.loads(headerData)
        if "keyrequestdata" in parsedHeaderData.keys():
            #logging.info("ProxySignKey: " + b64encode(ProxySignKey.publickey().exportKey("DER")).decode())

            #logging.info(flow.request.content.decode())
            pubKeyStr = parsedHeaderData["keyrequestdata"][0]["keydata"][
                "publickey"]
            logging.info("Client pubkey: " + pubKeyStr)

            global Mechanism
            global ClientPublicKey
            global ProxyRSAKey

            Mechanism = parsedHeaderData["keyrequestdata"][0]["keydata"][
                "mechanism"]

            ClientPublicKey = RSA.import_key(b64decode(pubKeyStr))

            ProxyRSAKey = RSA.generate(2048)
            proxyPubKeyStr = b64encode(
                ProxyRSAKey.publickey().exportKey("DER")).decode()
            logging.info("To be replaced with: " + proxyPubKeyStr)

            parsedHeaderData["keyrequestdata"][0]["keydata"][
                "publickey"] = proxyPubKeyStr
            parsedRequest["headerdata"] = b64encode(
                json.dumps(parsedHeaderData).encode()).decode()

            contentRest = b""
            if headerEndOffset != -1:
                contentRest = flow.request.content[headerEndOffset:]
            flow.request.content = json.dumps(
                parsedRequest).encode() + contentRest

            #logging.info(flow.request.content.decode())

        elif "ciphertext" in parsedHeaderData.keys() and MSLAESKey is not None:
            iv = b64decode(parsedHeaderData["iv"])
            cipher = AES.new(MSLAESKey, AES.MODE_CBC, iv)

            cipherText = b64decode(parsedHeaderData["ciphertext"])
            try:
                plainText = unpad(cipher.decrypt(cipherText), 16)
                logging.info(plainText.decode())
            except ValueError:
                logging.error("Error: incorrect AES key")

        #logging.info("Number of chunks: " + str(len(parsedReqChunks)))
        for chunk in parsedReqChunks:
            if MSLAESKey is None:
                continue

            payload = json.loads(b64decode(chunk["payload"]))
            iv = b64decode(payload["iv"])

            cipher = AES.new(MSLAESKey, AES.MODE_CBC, iv)

            cipherText = b64decode(payload["ciphertext"])
            try:
                plainText = unpad(cipher.decrypt(cipherText), 16)
            except ValueError:
                logging.error("Error: incorrect AES key")
                continue

            plainJSON = None

            try:
                plainJSON = json.loads(plainText)
            except json.JSONDecodeError as e:
                plainJSON = json.loads(plainText[0:e.pos])

            #logging.info(plainText.decode())
            decoded = b64decode(plainJSON["data"])
            if "compressionalgo" in plainJSON.keys():
                if plainJSON["compressionalgo"] == "GZIP":
                    decoded = gzip.decompress(decoded)
                elif plainJSON["compressionalgo"] == "LZW":
                    decoded = lzw_decompress(decoded)

            logging.info(decoded.decode())
w_file.close()

try:
    aprox_size_mb = round(
        os.path.getsize('./task2_128_lt1mb.bin') / 1000000.0, 5)

    start_time = time()  # Adding a start time to get the difference.

    while True:
        now = time()
        elapsed_time = now - start_time

        if not elapsed_time >= total_seconds:
            #  perform another encryption and decryption if elapsed time is less than 1 second.
            number_of_iterations += 1
            r_file = open('./task2_128_lt1mb.bin', 'rb')
            ciphered_data = r_file.read()
            r_file.close()

            # Decrypt
            cipher = AES.new(aes_key, AES.MODE_CBC, iv)
            plaintext = unpad(cipher.decrypt(ciphered_data), AES.block_size)
        else:
            break
    print(
        "\n (AES MODE: CBC, KEYSIZE: 128-bit) The max file size that could be decrypted in 1 second on this computer is: "
        + str(number_of_iterations * aprox_size_mb) + "MB")

except ValueError, KeyError:
    print("Incorrect decryption")
Exemple #33
0
#key = Random.new().read(AES.block_size)
#key = bytearray.fromhex('6ab9f619a67b90f58d590e466f8b3f33')
key = '1234567890123456'.encode()
#iv = Random.new().read(AES.block_size)
iv = bytearray.fromhex('af7bc4709ae803b616b3b6f161e2b409')
plaintext = 'Huynh Truong Minh Quang'.encode()
enc = encryptCBC(plaintext, key)
dec = decryptCBC(enc, key)

print("Key: ", key.hex())
print("IV: ", iv.hex())
print("Cipher: ", enc.hex())
print("Cipher (base64): ", base64.b64encode(enc))
print("Plain: ", dec.decode())
print(dec.hex())

file = 'input.jpg'
encrypt_file(file, key)
decrypt_file('input.jpg.enc', key)

##decrypt from hex
ciphertext = bytearray.fromhex(
    '0bd77995a9e5f022ac46fad44e815d91ce20adaef47eb6563844ea77dc55bf63')

cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext)
plaintext = unpad(plaintext, AES.block_size)

print(plaintext.hex())
print(plaintext.decode())
Exemple #34
0
def decrypt_aes128cbc_buffer_to_str(data, key, iv):
    cipher = AES.new(key.encode("ascii"), AES.MODE_CBC, iv.encode("ascii"))
    return unpad(cipher.decrypt(data), AES.block_size)
Exemple #35
0
def unpad_aes(data):
    try:
        return unpad(data, AES.block_size)
    except (ValueError):
        print('Padding is incorrect')
        sys.exit(1)
Exemple #36
0
        encryptedMessageEncoded1 = RSA_cipher1.encrypt(
            nonEncryptedMessageEncoded1)
        print('\nSent ciphertext: "{}" (Step 1)'.format(
            encryptedMessageEncoded1))
        centralizedCertificateAuthority.sendall(encryptedMessageEncoded1)

        #  Application server registration; reception and parsing of message contents (2)
        #  (Centralized Certificate Authority -> Application Server)
        #  Expected message contents:
        #  [Application Server Public-Key||Application Server Private-Key +\
        #  ||Certificate||Application Server ID||Timestamp2]
        cipher2 = DES.new(applicationServer_tk.encode('utf-8'), DES.MODE_ECB)
        receivedData2 = centralizedCertificateAuthority.recv(4096)
        receivedDataDecrypted2 = cipher2.decrypt(
            receivedData2)  # stores decoded byte data as string
        unpad(receivedDataDecrypted2, BLOCK_SIZE)
        receivedDataDecryptedDecoded2 = receivedDataDecrypted2.decode(
            "utf-8").strip()
        print('\nTEST >>> "{}" (Step 2)'.format(receivedDataDecrypted2))
        print('\nReceived ciphertext: "{}" (Step 2)'.format(receivedData2))
        receivedTimestamp2 = receivedDataDecryptedDecoded2[-10:]
        receivedApplicationServerID = receivedDataDecryptedDecoded2[-19:-10]
        upperBoundApplicationServerPublicKey = receivedDataDecryptedDecoded2.rindex(
            "END PUBLIC KEY-----") + 19
        lowerBoundApplicationServerPublicKey = receivedDataDecryptedDecoded2.find(
            "-----BEGIN PUBLIC KEY")
        receivedApplicationServerPublicKey =\
            receivedDataDecryptedDecoded2[lowerBoundApplicationServerPublicKey:upperBoundApplicationServerPublicKey]
        upperBoundApplicationServerPrivateKey = receivedDataDecryptedDecoded2.rindex(
            "END RSA PRIVATE KEY-----") + 24
        lowerBoundApplicationServerPrivateKey = receivedDataDecryptedDecoded2.find(
 def test1(self):
     padded = pad(b(""), 4, 'iso7816')
     self.failUnless(padded == uh(b("80000000")))
     back = unpad(padded, 4, 'iso7816')
     self.failUnless(back == b(""))
Exemple #38
0
    def decrypt(data, passphrase):
        """Decrypt a piece of data using a passphrase and *PBES2*.

        The algorithm to use is automatically detected.

        :Parameters:
          data : byte string
            The piece of data to decrypt.
          passphrase : byte string
            The passphrase to use for decrypting the data.
        :Returns:
          The decrypted data, as a binary string.
        """

        encrypted_private_key_info = decode_der(DerSequence, data)
        encryption_algorithm = decode_der(
                                DerSequence,
                                encrypted_private_key_info[0]
                                )
        encrypted_data = decode_der(
                            DerOctetString,
                            encrypted_private_key_info[1]
                            ).payload

        pbe_oid = decode_der(DerObjectId, encryption_algorithm[0]).value
        if pbe_oid != "1.2.840.113549.1.5.13":
            raise PbesError("Not a PBES2 object")

        pbes2_params = decode_der(DerSequence, encryption_algorithm[1])

        ### Key Derivation Function selection
        key_derivation_func = decode_der(DerSequence, pbes2_params[0])
        key_derivation_oid = decode_der(
                                DerObjectId,
                                key_derivation_func[0]
                                ).value

        # We only support PBKDF2 or scrypt
        if key_derivation_oid == "1.2.840.113549.1.5.12":

            pbkdf2_params = decode_der(DerSequence, key_derivation_func[1])
            salt = decode_der(DerOctetString, pbkdf2_params[0]).payload
            iteration_count = pbkdf2_params[1]
            if len(pbkdf2_params) > 2:
                kdf_key_length = pbkdf2_params[2]
            else:
                kdf_key_length = None
            if len(pbkdf2_params) > 3:
                raise PbesError("Unsupported PRF for PBKDF2")

        elif key_derivation_oid == "1.3.6.1.4.1.11591.4.11":

            scrypt_params = decode_der(DerSequence, key_derivation_func[1])
            salt = decode_der(DerOctetString, scrypt_params[0]).payload
            iteration_count, scrypt_r, scrypt_p = [scrypt_params[x]
                                                   for x in (1, 2, 3)]
            if len(scrypt_params) > 4:
                kdf_key_length = scrypt_params[4]
            else:
                kdf_key_length = None
        else:
            raise PbesError("Unsupported PBES2 KDF")

        ### Cipher selection
        encryption_scheme = decode_der(DerSequence, pbes2_params[1])
        encryption_oid = decode_der(
                            DerObjectId,
                            encryption_scheme[0]
                            ).value

        if encryption_oid == "1.2.840.113549.3.7":
            # DES_EDE3_CBC
            ciphermod = DES3
            key_size = 24
        elif encryption_oid == "2.16.840.1.101.3.4.1.2":
            # AES128_CBC
            ciphermod = AES
            key_size = 16
        elif encryption_oid == "2.16.840.1.101.3.4.1.22":
            # AES192_CBC
            ciphermod = AES
            key_size = 24
        elif encryption_oid == "2.16.840.1.101.3.4.1.42":
            # AES256_CBC
            ciphermod = AES
            key_size = 32
        else:
            raise PbesError("Unsupported PBES2 cipher")

        if kdf_key_length and kdf_key_length != key_size:
            raise PbesError("Mismatch between PBES2 KDF parameters"
                            " and selected cipher")

        IV = decode_der(DerOctetString, encryption_scheme[1]).payload

        # Create cipher
        if key_derivation_oid == "1.2.840.113549.1.5.12": # PBKDF2
            key = PBKDF2(passphrase, salt, key_size, iteration_count)
        else:
            key = scrypt(passphrase, salt, key_size, iteration_count,
                         scrypt_r, scrypt_p)
        cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV)

        # Decrypt data
        pt = cipher.decrypt(encrypted_data)
        return unpad(pt, cipher.block_size)
 def test4(self):
     padded = pad(uh(b("1234567890")), 4, 'iso7816')
     self.failUnless(padded == uh(b("1234567890800000")))
     back = unpad(padded, 4, 'iso7816')
     self.failUnless(back == uh(b("1234567890")))
Exemple #40
0
 def test3(self):
     padded = pad(uh(b("123456")), 4, 'iso7816')
     self.assertTrue(padded == uh(b("12345680")))
     #import pdb; pdb.set_trace()
     back = unpad(padded, 4, 'iso7816')
     self.assertTrue(back == uh(b("123456")))
 def test3(self):
     padded = pad(uh(b("123456")), 4)
     self.failUnless(padded == uh(b("12345601")))
     back = unpad(padded, 4)
     self.failUnless(back == uh(b("123456")))
Exemple #42
0
 def test3(self):
     padded = pad(uh(b("123456")), 4, 'iso7816')
     self.failUnless(padded == uh(b("12345680")))
     #import pdb; pdb.set_trace()
     back = unpad(padded, 4, 'iso7816')
     self.failUnless(back == uh(b("123456")))
Exemple #43
0
 def decrypt(self, data_to_decrypt):
     self.cipher = self.gen_cipher()
     return unpad(self.cipher.decrypt(data_to_decrypt), AES.block_size)
Exemple #44
0
 def test2(self):
     padded = pad(uh(b("12345678")), 4, 'x923')
     self.assertTrue(padded == uh(b("1234567800000004")))
     back = unpad(padded, 4, 'x923')
     self.assertTrue(back == uh(b("12345678")))
    print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()
print('Socket bind complete')

s.listen(10)
print('Socket now listening')

#wait to accept a connection - blocking call
while 1:
    conn, addr = s.accept()
    print('A new padding test requested by ' + addr[0] + ':' + str(addr[1]))

    iv = conn.recv(AES.block_size)
    ciphertext = conn.recv(1024)

    cipher = AES.new(key, AES.MODE_CBC, iv)

    try:
        unpad(cipher.decrypt(ciphertext), AES.block_size)
        #PKCS  01 / 0202 / 030303

    except ValueError:
        conn.send(b'NO')
        continue

    conn.send(b'OK')

    conn.close()

s.close()
Exemple #46
0
 def test4(self):
     padded = pad(uh(b("1234567890")), 4, 'iso7816')
     self.failUnless(padded == uh(b("1234567890800000")))
     back = unpad(padded, 4, 'iso7816')
     self.failUnless(back == uh(b("1234567890")))
Exemple #47
0
 def test1(self):
     padded = pad(b(""), 4, 'iso7816')
     self.assertTrue(padded == uh(b("80000000")))
     back = unpad(padded, 4, 'iso7816')
     self.assertTrue(back == b(""))
Exemple #48
0
cipher = DES.new(key, DES.MODE_CTR)

# Ciframos, haciendo que data sea multiplo del tamaño de bloque
ciphertext = cipher.encrypt(pad(data, BLOCK_SIZE_DES))

# Mostramos el cifrado por pantalla en modo binario y en modo base 64
print(ciphertext)
encoded_ciphertext = base64.b64encode(ciphertext)
print(encoded_ciphertext)

# Creamos un mecanismo de (des)cifrado DES en modo CBC con una inicializacion IV
# Ambos, cifrado y descifrado, se crean de la misma forma
decipher_des = DES.new(key, DES.MODE_CTR, IV)

# Desciframos, eliminamos el padding, y recuperamos la cadena
new_data = unpad(decipher_des.decrypt(ciphertext),
                 BLOCK_SIZE_DES).decode("utf-8", "ignore")

# Imprimimos los datos descifrados
print(new_data)


class DES_CIPHER:

    BLOCK_SIZE_DES = 8  # DES: Bloque de 64 bits

    def __init__(self, key):
        #Inicializa las variables locales
        self.key = key

    def cifrar(self, cadena, IV):
        #Cifra el parámetro cadena (de tipo String) con una IV específica, y devuelve el texto cifrado binario
Exemple #49
0
 def test4(self):
     padded = pad(uh(b("1234567890")), 4, 'iso7816')
     self.assertTrue(padded == uh(b("1234567890800000")))
     back = unpad(padded, 4, 'iso7816')
     self.assertTrue(back == uh(b("1234567890")))
Exemple #50
0
 def descifrar(self, cifrado, IV):
     #Descrifra el parámetro cifrado (de tipo binario) con una IV específica, y devuelve la cadena en claro de tipo String
     decipher_des = DES.new(self.key, DES.MODE_CTR, IV)
     new_data = unpad(decipher_des.decrypt(cifrado),
                      self.BLOCK_SIZE_DES).decode("utf-8", "ignore")
     return new_data
Exemple #51
0
 def test1(self):
     padded = pad(b(""), 4, 'x923')
     self.assertTrue(padded == uh(b("00000004")))
     back = unpad(padded, 4, 'x923')
     self.assertTrue(back == b(""))
Exemple #52
0
def decrypt(data, key):
    payload = base64.b64decode(data)
    data = aes_decrypt(payload, key)
    # response starts with 2 random bytes, exclude them
    response = unpad(data, 16, style='pkcs7')[2:]
    return response.decode('ascii')
Exemple #53
0
 def test3(self):
     padded = pad(uh(b("123456")), 4, 'x923')
     self.assertTrue(padded == uh(b("12345601")))
     back = unpad(padded, 4, 'x923')
     self.assertTrue(back == uh(b("123456")))
Exemple #54
0
def decrypt_confirmation_ecb(encrypted_text):
    cipher = AES.new(K1, AES.MODE_ECB)  # Setup cipher
    original_data = unpad(cipher.decrypt(encrypted_text), AES.block_size) 
    return original_data
 def decrypt(self, encrypt_string):
     encrypt_byte_string = base64.urlsafe_b64decode(bytes(map(ord, encrypt_string)))
     pad_byte_string = self.cipher.decrypt(encrypt_byte_string)
     string = unpad(pad_byte_string, MULTIPLE_OF_BYTE).decode('utf-8')
     return string
            print("Sua chave é inválida")
        else:
            if modo == "C":
                chave = bytes.fromhex(chave)
                # Cria a cifra AES, utilizando a chave informada e com o modo ECB, que é o mais simples
                cifra = AES.new(chave, AES.MODE_ECB)

                texto = bytes.fromhex(texto)
                # Realiza a encriptação dos dados e adiciona padding caso necessário
                resultado = cifra.encrypt(pad(texto, AES.block_size))

                # Mostrando o resultado da cifra em hexadecimal
                print(hex(int.from_bytes(resultado, byteorder='big'))[2:])

            elif modo == "D":
                chave = bytes.fromhex(chave)
                # Cria a cifra AES, utilizando a chave informada e com o modo ECB, que é o mais simples
                cifra = AES.new(chave, AES.MODE_ECB)

                texto = bytes.fromhex(texto)
                # Realiza a encriptação dos dados e remove padding caso necessário
                resultado = unpad(cifra.decrypt(texto), AES.block_size)

                # Mostrando o resultado da decifragem em hexadecimal
                print(hex(int.from_bytes(resultado, byteorder='big'))[2:])
            else:
                print("O modo informado não existe")
    else:
        print("A sua entrada está incorreta, digite \"ajuda\" caso queira saber mais")

input()
Exemple #57
0
def decode(pem_data, passphrase=None):
    """Decode a PEM block into binary.

    Args:
      pem_data (string):
        The PEM block.
      passphrase (byte string):
        If given and the PEM block is encrypted,
        the key will be derived from the passphrase.

    Returns:
      A tuple with the binary data, the marker string, and a boolean to
      indicate if decryption was performed.

    Raises:
      ValueError: if decoding fails, if the PEM file is encrypted and no passphrase has
                  been provided or if the passphrase is incorrect.
    """

    # Verify Pre-Encapsulation Boundary
    r = re.compile(r"\s*-----BEGIN (.*)-----\s+")
    m = r.match(pem_data)
    if not m:
        raise ValueError("Not a valid PEM pre boundary")
    marker = m.group(1)

    # Verify Post-Encapsulation Boundary
    r = re.compile(r"-----END (.*)-----\s*$")
    m = r.search(pem_data)
    if not m or m.group(1) != marker:
        raise ValueError("Not a valid PEM post boundary")

    # Removes spaces and slit on lines
    lines = pem_data.replace(" ", '').split()

    # Decrypts, if necessary
    if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
        if not passphrase:
            raise ValueError("PEM is encrypted, but no passphrase available")
        DEK = lines[2].split(':')
        if len(DEK) != 2 or DEK[0] != 'DEK-Info':
            raise ValueError("PEM encryption format not supported.")
        algo, salt = DEK[1].split(',')
        salt = unhexlify(tobytes(salt))

        padding = True

        if algo == "DES-CBC":
            key = _EVP_BytesToKey(passphrase, salt, 8)
            objdec = DES.new(key, DES.MODE_CBC, salt)
        elif algo == "DES-EDE3-CBC":
            key = _EVP_BytesToKey(passphrase, salt, 24)
            objdec = DES3.new(key, DES3.MODE_CBC, salt)
        elif algo == "AES-128-CBC":
            key = _EVP_BytesToKey(passphrase, salt[:8], 16)
            objdec = AES.new(key, AES.MODE_CBC, salt)
        elif algo == "AES-192-CBC":
            key = _EVP_BytesToKey(passphrase, salt[:8], 24)
            objdec = AES.new(key, AES.MODE_CBC, salt)
        elif algo == "AES-256-CBC":
            key = _EVP_BytesToKey(passphrase, salt[:8], 32)
            objdec = AES.new(key, AES.MODE_CBC, salt)
        elif algo.lower() == "id-aes256-gcm":
            key = _EVP_BytesToKey(passphrase, salt[:8], 32)
            objdec = AES.new(key, AES.MODE_GCM, nonce=salt)
            padding = False
        else:
            raise ValueError("Unsupport PEM encryption algorithm (%s)." % algo)
        lines = lines[2:]
    else:
        objdec = None

    # Decode body
    data = a2b_base64(''.join(lines[1:-1]))
    enc_flag = False
    if objdec:
        if padding:
            data = unpad(objdec.decrypt(data), objdec.block_size)
        else:
            # There is no tag, so we don't use decrypt_and_verify
            data = objdec.decrypt(data)
        enc_flag = True

    return (data, marker, enc_flag)
Exemple #58
0
"""CAPTURO EL MENSAJE EN EL DISCO DURO"""
archivo = "mensaje.docx"
escribearchivo = open(archivo,"rb")
mensajecapturado = escribearchivo.read()
escribearchivo.close()


#Ahora que tengo el mensaje como conozco la clave de b con el servidor descifro el mensaje
msg_b_t = bytearray.fromhex(mensajecapturado.decode("UTF-8"))

# B descifra los datos a través de la clave KBT, guarda la clave KAB y la identidad
# de Alicia y crea un valor random denominado Rb 

uncipher_b_t = AES.new(key_b_t, AES.MODE_ECB)
json_b_t = unpad(uncipher_b_t.decrypt(msg_b_t), BLOCK_SIZE_AES).decode("UTF-8", "ignore")
msg_a_b = json.loads(json_b_t)
a_k_ab, b_alice = msg_a_b
t_k_ab = bytearray.fromhex(a_k_ab)
key_a_t=t_k_ab






#####################################################################
# COMPLETAR: CONTACTAR CON BOB, SEGUIR EL PROTOCOLO NEEDHAM-SCHROEDER
#####################################################################

# Crea el socket servidor y escucha
Exemple #59
0
def decode(pem_data, passphrase=None):
    """Decode a PEM block into binary.

    :Parameters:
      pem_data : string
        The PEM block.
      passphrase : byte string
        If given and the PEM block is encrypted,
        the key will be derived from the passphrase.
    :Returns:
      A tuple with the binary data, the marker string, and a boolean to
      indicate if decryption was performed.
    :Raises ValueError:
      If decoding fails, if the PEM file is encrypted and no passphrase has
      been provided or if the passphrase is incorrect.
    """

    # Verify Pre-Encapsulation Boundary
    r = re.compile("\s*-----BEGIN (.*)-----\n")
    m = r.match(pem_data)
    if not m:
        raise ValueError("Not a valid PEM pre boundary")
    marker = m.group(1)

    # Verify Post-Encapsulation Boundary
    r = re.compile("-----END (.*)-----\s*$")
    m = r.search(pem_data)
    if not m or m.group(1) != marker:
        raise ValueError("Not a valid PEM post boundary")

    # Removes spaces and slit on lines
    lines = pem_data.replace(" ", '').split()

    # Decrypts, if necessary
    if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
        if not passphrase:
            raise ValueError("PEM is encrypted, but no passphrase available")
        DEK = lines[2].split(':')
        if len(DEK) != 2 or DEK[0] != 'DEK-Info':
            raise ValueError("PEM encryption format not supported.")
        algo, salt = DEK[1].split(',')
        salt = unhexlify(tobytes(salt))
        if algo == "DES-CBC":
            # This is EVP_BytesToKey in OpenSSL
            key = PBKDF1(passphrase, salt, 8, 1, MD5)
            objdec = DES.new(key, DES.MODE_CBC, salt)
        elif algo == "DES-EDE3-CBC":
            # Note that EVP_BytesToKey is note exactly the same as PBKDF1
            key = PBKDF1(passphrase, salt, 16, 1, MD5)
            key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
            objdec = DES3.new(key, DES3.MODE_CBC, salt)
        elif algo == "AES-128-CBC":
            key = PBKDF1(passphrase, salt[:8], 16, 1, MD5)
            objdec = AES.new(key, AES.MODE_CBC, salt)
        else:
            raise ValueError("Unsupport PEM encryption algorithm.")
        lines = lines[2:]
    else:
        objdec = None

    # Decode body
    data = a2b_base64(b(''.join(lines[1:-1])))
    enc_flag = False
    if objdec:
        data = unpad(objdec.decrypt(data), objdec.block_size)
        enc_flag = True

    return (data, marker, enc_flag)
Exemple #60
0
    def decrypt(data, passphrase):
        """Decrypt a piece of data using a passphrase and *PBES2*.

        The algorithm to use is automatically detected.

        :Parameters:
          data : byte string
            The piece of data to decrypt.
          passphrase : byte string
            The passphrase to use for decrypting the data.
        :Returns:
          The decrypted data, as a binary string.
        """

        enc_private_key_info = DerSequence().decode(data, nr_elements=2)
        enc_algo = DerSequence().decode(enc_private_key_info[0])
        encrypted_data = DerOctetString().decode(enc_private_key_info[1]).payload

        pbe_oid = DerObjectId().decode(enc_algo[0]).value
        if pbe_oid != _OID_PBES2:
            raise PbesError("Not a PBES2 object")

        pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2)

        ### Key Derivation Function selection
        kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2)
        kdf_oid = DerObjectId().decode(kdf_info[0]).value

        kdf_key_length = None

        # We only support PBKDF2 or scrypt
        if kdf_oid == _OID_PBKDF2:

            pbkdf2_params = DerSequence().decode(kdf_info[1], nr_elements=(2, 3, 4))
            salt = DerOctetString().decode(pbkdf2_params[0]).payload
            iteration_count = pbkdf2_params[1]

            left = len(pbkdf2_params) - 2
            idx = 2

            if left > 0:
                try:
                    kdf_key_length = pbkdf2_params[idx] - 0
                    left -= 1
                    idx += 1
                except TypeError:
                    pass

            # Default is HMAC-SHA1
            pbkdf2_prf_oid = "1.2.840.113549.2.7"
            if left > 0:
                pbkdf2_prf_algo_id = DerSequence().decode(pbkdf2_params[idx])
                pbkdf2_prf_oid = DerObjectId().decode(pbkdf2_prf_algo_id[0]).value

        elif kdf_oid == _OID_SCRYPT:

            scrypt_params = DerSequence().decode(kdf_info[1], nr_elements=(4, 5))
            salt = DerOctetString().decode(scrypt_params[0]).payload
            iteration_count, scrypt_r, scrypt_p = [scrypt_params[x]
                                                   for x in (1, 2, 3)]
            if len(scrypt_params) > 4:
                kdf_key_length = scrypt_params[4]
            else:
                kdf_key_length = None
        else:
            raise PbesError("Unsupported PBES2 KDF")

        ### Cipher selection
        enc_info = DerSequence().decode(pbes2_params[1])
        enc_oid = DerObjectId().decode(enc_info[0]).value

        if enc_oid == _OID_DES_EDE3_CBC:
            # DES_EDE3_CBC
            ciphermod = DES3
            key_size = 24
        elif enc_oid == _OID_AES128_CBC:
            # AES128_CBC
            ciphermod = AES
            key_size = 16
        elif enc_oid == _OID_AES192_CBC:
            # AES192_CBC
            ciphermod = AES
            key_size = 24
        elif enc_oid == _OID_AES256_CBC:
            # AES256_CBC
            ciphermod = AES
            key_size = 32
        else:
            raise PbesError("Unsupported PBES2 cipher")

        if kdf_key_length and kdf_key_length != key_size:
            raise PbesError("Mismatch between PBES2 KDF parameters"
                            " and selected cipher")

        IV = DerOctetString().decode(enc_info[1]).payload

        # Create cipher
        if kdf_oid == _OID_PBKDF2:
            if pbkdf2_prf_oid == _OID_HMAC_SHA1:
                hmac_hash_module = SHA1
            elif pbkdf2_prf_oid == _OID_HMAC_SHA224:
                hmac_hash_module = SHA224
            elif pbkdf2_prf_oid == _OID_HMAC_SHA256:
                hmac_hash_module = SHA256
            elif pbkdf2_prf_oid == _OID_HMAC_SHA384:
                hmac_hash_module = SHA384
            elif pbkdf2_prf_oid == _OID_HMAC_SHA512:
                hmac_hash_module = SHA512
            else:
                raise PbesError("Unsupported HMAC %s" % pbkdf2_prf_oid)

            key = PBKDF2(passphrase, salt, key_size, iteration_count,
                         hmac_hash_module=hmac_hash_module)
        else:
            key = scrypt(passphrase, salt, key_size, iteration_count,
                         scrypt_r, scrypt_p)
        cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV)

        # Decrypt data
        pt = cipher.decrypt(encrypted_data)
        return unpad(pt, cipher.block_size)