Example #1
0
def encryption_oracle(input):
    rand_num1 = randint(5, 10)
    rand_num2 = randint(5, 10)
    encrypt_ecb = randint(0, 1)
    before = pkcs7_pad("", rand_num1)
    after = pkcs7_pad("", rand_num2)

    ciphertext = ""
    iv = ""
    key = Random.get_random_bytes(16)
    modified_input = before + input + after
    padded_input = pkcs7_pad(modified_input, 16)
    if encrypt_ecb == 1:
        # encrypt ECB
        encryptor = AES.new(key, AES.MODE_ECB)
        ciphertext = encryptor.encrypt(padded_input)
        print "ECB here"
    else:
        # encrypt CBC
        iv = Random.get_random_bytes(16)
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        ciphertext = encryptor.encrypt(padded_input)
        print "CBC here"

    return key, iv, ciphertext
Example #2
0
    def test_aes_256(self):
        key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"
        iv = "000102030405060708090a0b0c0d0e0f"
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "f58c4c04d6e5f1ba779eabfb5f7bfbd6"
            + "9cfc4e967edb808d679f777bc6702c7d"
            + "39f23369a9d9bacfa530e26304231461"
            + "b2eb05e2c39be9fcda6c19078c6a9d1b"
        )

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #3
0
    def test_valid_init_verify(self):
        # Verify path INIT->VERIFY
        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        mac = cipher.digest()

        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        cipher.verify(mac)
Example #4
0
    def export_data(self, entrystore, password):
        "Exports data from an entrystore"

        # check and pad password
        if password is None:
            raise base.PasswordError

        password = util.pad_right(password[:32], 32, "\0")

        # generate XML
        data = RevelationXML.export_data(self, entrystore)

        # compress data, and right-pad with the repeated ascii
        # value of the pad length
        data = zlib.compress(data)

        padlen = 16 - (len(data) % 16)
        if padlen == 0:
            padlen = 16

        data += chr(padlen) * padlen

        # generate an initial vector for the CBC encryption
        iv = util.random_string(16)

        # encrypt data
        AES.block_size = 16
        AES.key_size = 32

        data = AES.new(password, AES.MODE_CBC, iv).encrypt(data)

        # encrypt the iv, and prepend it to the data with a header
        data = self.__generate_header() + AES.new(password).encrypt(iv) + data

        return data
Example #5
0
    def test_aes_128(self):
        key = "2b7e151628aed2a6abf7158809cf4f3c"
        iv = "000102030405060708090a0b0c0d0e0f"
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "7649abac8119b246cee98e9b12e9197d"
            + "5086cb9b507219ee95db113a917678b2"
            + "73bed6b8e3c1743b7116e69e22229516"
            + "3ff1caa1681fac09120eca307586e1a7"
        )

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #6
0
    def test_aes_256_cfb128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )

        ciphertext = (
            "dc7e84bfda79164b7ecd8486985d3860"
            + "39ffed143b28b1c832113c6331e5407b"
            + "df10132415e54b92a13ed0a8267ae2f9"
            + "75a385741ab9cef82031623d55b1e471"
        )
        key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #7
0
    def test_aes_192(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "cdc80d6fddf18cab34c25909c99a4174"
            + "fcc28b8d4c63837c09e81700c1100401"
            + "8d9a9aeac0f6596f559c6d4daf59a5f2"
            + "6d9f200857ca6c3e9cac524bd9acc92a"
        )
        key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
Example #8
0
    def encrypt(self, data):
        if self.initialized == 0 and self.is_server == False:
            taddr = self.proto.factory.tun.addr
            taddr_hash = SHA384.new(taddr).digest()

            iv = Random.new().read(AES.block_size)
            salt = Random.new().read(SALT_LEN)
            passwd = self.proto.passwd

            self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN * 4, count=PBKDF2_ITERATIONS)
            self.aes_e = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv)
            self.aes_d = AES.new(self.key[AES_KEYLEN : AES_KEYLEN * 2], AES.MODE_CFB, iv)
            self.hmac_txkey = self.key[AES_KEYLEN * 2 : AES_KEYLEN * 3]
            self.hmac_rxkey = self.key[AES_KEYLEN * 3 :]

            data = taddr_hash + salt + iv + self.aes_e.encrypt(data)
            tag = HMAC.new(self.hmac_txkey, msg=data, digestmod=SHA384).digest()[:SHA384_LEN]
            data = data + tag

            self.initialized = 1

        else:
            data = self.aes_e.encrypt(data)
            tag = HMAC.new(self.hmac_txkey, msg=data, digestmod=SHA384).digest()[:SHA384_LEN]
            data = data + tag

        return data
Example #9
0
    def decrypt_body(self, password, data):
        import time

        key = sha256(password).digest()
        hdr = self.header

        then = time.time()
        # sha256 the password, encrypt it upon itself 50000 times, sha256 it again, and sha256 it again concatenated with a random number :|
        cipher = AES.new(hdr["seed_key"], AES.MODE_ECB)
        for x in range(hdr["seed_rot_n"]):
            key = cipher.encrypt(key)
        key = sha256(key).digest()
        key = sha256(hdr["seed_rand"] + key).digest()
        cipher = AES.new(key, AES.MODE_CBC, hdr["enc_iv"])
        body = cipher.decrypt(data)

        # remove some padding
        padding = unpack("b", body[-1])[0]
        body = body[:-padding]

        now = time.time()

        print "spent %.3fms on decryption" % ((now - then) * 1000)
        if sha256(body).digest() != hdr["checksum"]:
            raise KdbReaderDecodeFailError()

        return body
Example #10
0
def decrypt_hmac(key: bytes, ciphertext: bytes) -> str:
    """ decrypt(key, ciphertext) -> Decrypts the ciphertext using the key.

    """

    encrypted_hmac_key, hmac_digest, salt, iv, real_ciphertext = get_data_hmac(ciphertext)

    # Re-generate the key from the salt.
    valid_key = key_gen(key, salt)

    hmac_iv = encrypted_hmac_key[:IV_LEN]
    hmac_decrypt_obj = AES.new(valid_key, AES.MODE_CBC, hmac_iv)
    hmac_key = hmac_decrypt_obj.decrypt(encrypted_hmac_key[IV_LEN:])

    hmac = HMAC.new(hmac_key, digestmod=SHA512)
    hmac.update(salt + iv + real_ciphertext)
    assert hmac.digest() == hmac_digest

    decrypt_obj = AES.new(valid_key, AES.MODE_CBC, iv)
    padded_plaintext = decrypt_obj.decrypt(real_ciphertext)

    try:
        # Remove the padding from the plaintext.
        plaintext = padded_plaintext[: -padded_plaintext[-1]].decode()
    except UnicodeDecodeError:
        print("There was an error.  Maybe the wrong password was given.")
        return ""

    return plaintext
Example #11
0
def TryPassword(password):
    key = pbkdf2.PBKDF2(password, salt, PBKDF2VgenCount, hashlib.sha512, hmac)
    key_64bytes = key.read(64)

    hash = hashlib.sha512()
    hash.update(key_64bytes)
    hash.update(bin_salt)
    T = hash.digest()

    obj = AES.new(T[0:32], AES.MODE_CBC, "\x00" * 16)
    client_generated_random_salt = obj.decrypt(bin_client_session_key)

    obj = AES.new(T[0:32], AES.MODE_CBC, "\x00" * 16)
    cryptotext = obj.decrypt(bin_server_session_key)

    decryption_key = pbkdf2.PBKDF2(
        binascii.hexlify(client_generated_random_salt + cryptotext).upper(),
        bin_PBKDF2Salt,
        PBKDF2SderCount,
        hashlib.sha512,
        hmac,
    ).read(32)

    # obj = AES.new(decryption_key, AES.MODE_CBC, '\x00'*16)
    # password_net = obj.decrypt(bin_password)
    # print("Decrypted password: %s" %(password_net[16:]))

    obj = AES.new(decryption_key, AES.MODE_CBC, "\x00" * 16)
    cleartext = obj.decrypt(bin_speedy_key)

    if cleartext[16:] == key_64bytes:
        return True
    else:
        return False
Example #12
0
def encrypt_hmac(key: bytes, plaintext: str) -> bytes:
    """ encrypt(key, plaintext) ->  Encrypts plaintext using key.

    """

    # Generate a key from a salt and hashed key.
    salt = Random.new().read(SALT_LEN)
    valid_key = key_gen(key, salt)

    iv = Random.new().read(IV_LEN)

    padded_plaintext = PKCS7_pad(plaintext.encode(), AES.block_size)

    encrypt_obj = AES.new(valid_key, AES.MODE_CBC, iv)

    # Put the salt and iv at the start of the ciphertext so when it
    # needs to be decrypted the same salt and iv can be used.
    ciphertext = salt + iv + encrypt_obj.encrypt(padded_plaintext)

    hmac_key = Random.new().read(32)
    hmac = HMAC.new(hmac_key, digestmod=SHA512)
    hmac.update(ciphertext)
    hmac_digest = hmac.digest()

    # Encrypt the hmac key
    hmac_iv = Random.new().read(IV_LEN)
    hmac_encrypt_obj = AES.new(valid_key, AES.MODE_CBC, hmac_iv)
    encrypted_hmac_key = hmac_iv + hmac_encrypt_obj.encrypt(hmac_key)

    # ciphertext = encrypted hmac key + hmac digest + salt + iv +
    # encrypted data.
    ciphertext = encrypted_hmac_key + hmac_digest + ciphertext

    return ciphertext
Example #13
0
def output_index(hash_data, file_name):
    existing_index = raw_input("Do you have an existing index? y/n:\n")
    if existing_index == "y":
        key = raw_input("Enter key for index:\n")
        encryptor = AES.new(key, mode)
        index_output = open("index.txt", "r+")
        index_data = index_output.read()
        index_open = encryptor.decrypt(index_data)
        print index_open
        index_open = file_name + "\t" + hash_data + "\n"
        if len(key) == 16:
            index_open += "\n" * (16 - len(index_open) % 16)  # Make length of file data 16
        else:
            index_open += "\n" * (32 - len(index_open) % 32)  # Make length of file data 32
        index_open = encryptor.encrypt(index_open)
        index_output.write(index_open)

        index_output.close()
    elif existing_index == "n":
        new_key = raw_input("Enter a key to encrypt with (must be length of 16 or 32)\n:")
        index_output = open("index.txt", "w")
        encryptor = AES.new(new_key, mode)
        index_data = file_name + "\t" + hash_data + "\n"
        if len(new_key) == 16:
            index_data += "\n" * (16 - len(index_data) % 16)  # Make length of file data 16
        else:
            index_data += "\n" * (32 - len(index_data) % 32)  # Make length of file data 32
        index_data = encryptor.encrypt(index_data)
        index_output.write(index_data)
    else:
        print "Enter a valid option"
    exit()
Example #14
0
    def __init__(self, cipher_mode=None, initialization_vector=None, key=None, **kwargs):
        """Initializes the decrypter object.

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

    Raises:
      ValueError: when key is not set, block cipher mode is not supported,
                  or initialization_vector is required and not set.
    """
        if not key:
            raise ValueError(u"Missing key.")

        cipher_mode = self.ENCRYPTION_MODES.get(cipher_mode, None)
        if cipher_mode is None:
            raise ValueError(u"Unsupported cipher mode: {0!s}".format(cipher_mode))

        if cipher_mode != AES.MODE_ECB and not initialization_vector:
            # Pycrypto does not create a meaningful error when initialization vector
            # is missing. Therefore, we report it ourselves.
            raise ValueError(u"Missing initialization vector.")

        super(AESDecrypter, self).__init__()
        if cipher_mode == AES.MODE_ECB:
            self._aes_cipher = AES.new(key, mode=cipher_mode)
        else:
            self._aes_cipher = AES.new(key, IV=initialization_vector, mode=cipher_mode)
Example #15
0
    def test_aes_128_cfb128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "3b3fd92eb72dad20333449f8e83cfb4a"
            + "c8a64537a0b3a93fcde3cdad9f1ce58b"
            + "26751f67a3cbb140b1808cf187a4f4df"
            + "c04b05357c5d1c0eeac4c66f9ff7f2e6"
        )
        key = "2b7e151628aed2a6abf7158809cf4f3c"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
Example #16
0
def encrypt(str, key):
    str = str.rjust(32)
    if not os.path.exists(key):
        cipher = AES.new(key.rjust(32), AES.MODE_ECB)  # never use ECB
    else:
        cipher = AES.new(open(key).readline().rstrip().rjust(32), AES.MODE_ECB)  # never use ECB
    return base64.b64encode(cipher.encrypt(str))[:-1]
Example #17
0
    def test_aes_192_cfb128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "cdc80d6fddf18cab34c25909c99a4174"
            + "67ce7f7f81173621961a2b70171d3d7a"
            + "2e1e8a1dd59b88b1c8e60fed1efac4c9"
            + "c05f9f9ca9834fa042ae8fba584b09ff"
        )
        key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CFB, iv, segment_size=128)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def test_aes_encryption():
    secret = {"secret": "This is a secret!"}
    secret_data = json.dumps(secret)

    aes_key = "This is a key123"  # 128bit key

    # Generate initialization vector for AES
    iv = Random.new().read(AES.block_size)
    assert len(iv) == AES.block_size

    # Initialize AES cipher
    cipher = AES.new(aes_key, AES.MODE_CFB, iv)

    # Prepare a packed string containing IV + crypto text
    packed = iv + cipher.encrypt(secret_data.encode("utf-8"))

    del iv, cipher

    # ---------- time to get the message back! ----------

    iv = packed[: AES.block_size]
    msg = packed[AES.block_size :]

    cypher = AES.new(aes_key, AES.MODE_CFB, iv)

    decrypted = cypher.decrypt(msg)
    assert decrypted == secret_data

    loaded = json.loads(decrypted)
    assert loaded == secret
Example #19
0
    def test_aes_128(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "3b3fd92eb72dad20333449f8e83cfb4a"
            + "7789508d16918f03f53c52dac54ed825"
            + "9740051e9c5fecf64344f7a82260edcc"
            + "304c6528f659c77866a510d9c1d6ae5e"
        )
        key = "2b7e151628aed2a6abf7158809cf4f3c"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
Example #20
0
def AESDecrypt(filename, key, output):
    def getlocation():

        html = urllib.urlopen("http://geoiptool.com").read()

        lat = float(re.search(r"lat: [0-9]*\.[0-9]*", html).group()[5:])
        lng = float(re.search(r"lng: [0-9]*\.[0-9]*", html).group()[5:])
        return lat, lng

    f = open(filename, "r")
    cip = f.read().split("\n")
    eLat = cip[0]
    eLon = cip[1]

    f.close()

    obj1 = AES.new("This is coordina", AES.MODE_CFB, "Luckyson Khaidem")
    latitude = float(obj1.decrypt(eLat))
    longitude = float(obj1.decrypt(eLon))
    try:
        lat, lng = getlocation()
    except:
        return -1
    if abs(latitude - lat) >= 0.9999 or abs(longitude - lng) >= 0.9999:
        print "Cannot Decrypt. Location Invalid."
        return -2
    ciphertext = cip[2]
    for i in range(3, len(cip)):
        ciphertext = ciphertext + "\n" + cip[i]

    o = open(output, "w")
    obj = AES.new(key, AES.MODE_CFB, "Luckyson Khaidem")
    message = obj.decrypt(ciphertext)
    o.write(message)
    o.close()
Example #21
0
    def test_aes_256(self):
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "dc7e84bfda79164b7ecd8486985d3860"
            + "4febdc6740d20b3ac88f6ad82a4fb08d"
            + "71ab47a086e86eedf39d1c5bba97c408"
            + "0126141d67f37be8538f5a8be740e484"
        )
        key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"
        iv = "000102030405060708090a0b0c0d0e0f"

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)

        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
        cipher = AES.new(key, AES.MODE_OFB, iv)
        self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
Example #22
0
    def encrypt(self, toReturnVal, *args):
        from Crypto.Cipher import AES
        import base64
        import os

        BLOCK_SIZE = 32
        PADDING = "{"
        pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
        EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
        len_args = len(args)
        if len_args == 1:
            cipher = AES.new(args[0])
            encoded = EncodeAES(cipher, self._ds[self._currentTag].value)
            if toReturnVal == 0:
                self._ds[self._currentTag].value = encoded
            else:
                return encoded
        else:
            cipher = AES.new(args[1])
            ElementName = args[0]
            if ElementName in self._ds:
                de = self.ds.data_element(ElementName)
                val = de.value
                encoded = EncodeAES(cipher, val)
                if toReturnVal == 0:
                    self._ds[self._currentTag].value = encoded
                else:
                    return encoded
            else:
                raise AttributeError(ElementName)
                return None
Example #23
0
    def encrypt(self, plaintext):
        AES.encrypt(self, plaintext)

        plaintextBytes = stringToBytes(plaintext)
        chainBytes = stringToBytes(self.IV)

        # CBC Mode: For each block...
        for x in range(len(plaintextBytes) / 16):

            # XOR with the chaining block
            blockBytes = plaintextBytes[x * 16 : (x * 16) + 16]
            for y in range(16):
                blockBytes[y] ^= chainBytes[y]
            blockString = bytesToString(blockBytes)

            # Encrypt it
            encryptedBytes = stringToBytes(self.rijndael.encrypt(blockString))

            # Overwrite the input with the output
            for y in range(16):
                plaintextBytes[(x * 16) + y] = encryptedBytes[y]

            # Set the next chaining block
            chainBytes = encryptedBytes

        self.IV = bytesToString(chainBytes)
        return bytesToString(plaintextBytes)
Example #24
0
    def authenticationStage(self):
        """Handle the challenge response for the client, and start the proxy connection."""
        if len(self.buffer) < 32:
            return

        attempt, iv, self.buffer = self.buffer[:16], self.buffer[16:32], self.buffer[32:]
        # Check which cookie to use
        cookie, info = common.cookies.pop(self.challenge, attempt)
        if info is None:
            log.msg("Client failed to authenticate")
            # Send a dummy IV
            self.transport.write(16 * "\x00")
            # Failure code, error description
            self.transport.write(struct.pack("!l", 1) + self.varstring("Authentication failed"))
            self.transport.loseConnection()
            return

        # Take the input stream IV, and generate an IV for the output stream
        aesobj = AES.new(cookie, AES.MODE_ECB)
        iniv = aesobj.decrypt(iv)
        outiv = os.urandom(16)
        encryptediv = aesobj.encrypt(outiv)
        self.transport.write(encryptediv)

        # Prepare the AES instances for encryption
        self.inaes = AES.new(cookie, AES.MODE_CFB, iniv, segment_size=8)
        self.outaes = AES.new(cookie, AES.MODE_CFB, outiv, segment_size=8)

        # Post-pone authentication response until finishSetup
        del self.challenge
        self.state = RFBState.SETUP
        connectVNC(self, info).addCallbacks(self.finishSetup, self.bail)
Example #25
0
    def test_aes_192(self):
        key = "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b"
        iv = "000102030405060708090a0b0c0d0e0f"
        plaintext = (
            "6bc1bee22e409f96e93d7e117393172a"
            + "ae2d8a571e03ac9c9eb76fac45af8e51"
            + "30c81c46a35ce411e5fbc1191a0a52ef"
            + "f69f2445df4f9b17ad2b417be66c3710"
        )
        ciphertext = (
            "4f021db243bc633d7178183a9fa071e8"
            + "b4d9ada9ad7dedf4e5e738763f69145a"
            + "571b242012fb7ae07fa9baac3df102e0"
            + "08b0e27988598881d920a9e64f5615cd"
        )

        key = unhexlify(key)
        iv = unhexlify(iv)
        plaintext = unhexlify(plaintext)
        ciphertext = unhexlify(ciphertext)

        cipher = AES.new(key, AES.MODE_CBC, iv)
        self.assertEqual(cipher.encrypt(plaintext), ciphertext)
        cipher = AES.new(key, AES.MODE_CBC, iv)
        self.assertEqual(cipher.decrypt(ciphertext), plaintext)
    def encrypt_user_credentials(self, user_name, user_pass):
        """ Function encrypt user credentials by
			using AES (CBC mode) with given key. In our
			case key for user name encryption is user
			password and for user password is user name.

			user_name:
				User name as string

			user_pass:
				User password as string
		"""
        user_name, user_pass = self._credential_preparer(user_name, user_pass)

        key_for_pass = hashlib.sha256(user_name).digest()
        key_for_name = hashlib.sha256(user_pass).digest()

        iv = "".join(chr(random.randint(0, 0xFF)) for i in range(16))
        encryptor_for_name = AES.new(key_for_name, self.mode, iv)
        encryptor_for_pass = AES.new(key_for_pass, self.mode, iv)

        # adding symbols ':' to divide phrase
        # during decription

        return (
            encryptor_for_name.encrypt(user_name) + "1234" + iv + "1234" + encryptor_for_pass.encrypt(user_pass)
        ).encode("hex")
Example #27
0
    def test_hex_mac(self):
        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        mac_hex = cipher.hexdigest()
        self.assertEqual(cipher.digest(), unhexlify(mac_hex))

        cipher = AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96)
        cipher.hexverify(mac_hex)
Example #28
0
    def close(self):
        """ Closes the file and returns a URI with the final address of the file.
		If save_metadata is set, the file metadata is saved in the DHT.
		You can always access to the metadata with File.metadata """
        if self.closed:
            return
        logger.info("Closing %s" % self.uri.get_readable())
        if self.mode == "w":
            self.flush(True)
            self.metadata.set("Main:parts", len(self.parts))
            self.metadata.set("Main:length", self.filelength)
            self.metadata.set("Main:hash", self.hasher.hexdigest())
            self.metadata.set("Main:p", "")
            if self.save_metadata:
                # variables used to chain metadata blocks
                puri = self.uri
                pmeta = self.metadata
                not_saved = True
                # crypter used to encrypt the metadata. There is always
                # a crypter to protect against casual atackers, but
                # if there is no Kf the crypter is nearly useless
                if SECURED:
                    if self.keys[4]:
                        mdencrypter = AES.new(self.keys[4], AES.MODE_CBC, self.uri.get_hd())
                    else:
                        mdencrypter = AES.new(self.uri.get_hd(), AES.MODE_CBC, self.uri.get_hd())
                else:
                    mdencrypter = DummyEncrypter()
                for i in range(0, len(self.parts)):
                    pmeta.set("Part:%d" % i, self.parts[i])
                    # chain the metadata blocks, each block only with
                    # DESC_PER_METAPART references to parts of the file
                    if i < len(self.parts) - 1 and i % self.DESC_PER_METAPART == self.DESC_PER_METAPART - 1:
                        nuri = URI(self.uri.uid, utils.random_nick(), "", self.keys)
                        nuri.hd = utils.random_string(16, False)
                        pmeta.set("Main:n", nuri.get_static())
                        m = pmeta.save()
                        pmeta.set("Main:p", utils.random_string(self.BLOCK_SIZE - len(m)))
                        m = mdencrypter.encrypt(pmeta.save())
                        dfs.dht.put(puri.get_hd(), m, puri.nick)
                        pmeta = utils.Config()
                        pmeta.set("Main:p", "")
                        puri = nuri
                        not_saved = False
                    else:
                        not_saved = True
                if not_saved:
                    m = pmeta.save()
                    pmeta.set("Main:p", utils.random_string(self.BLOCK_SIZE - len(m)))
                    m = mdencrypter.encrypt(pmeta.save())
                    dfs.dht.put(puri.get_hd(), m, puri.nick)

                    # Create the final metadata
            for i in range(0, len(self.parts)):
                self.metadata.set("Part:%d" % i, self.parts[i])
        else:
            # In read, free the buffer
            self.buffer = None
        self.closed = True
        return self.uri
Example #29
0
    def test_unknown_parameters(self):
        self.assertRaises(TypeError, AES.new, self.key_256, AES.MODE_SIV, self.nonce_96, 7)
        self.assertRaises(TypeError, AES.new, self.key_256, AES.MODE_SIV, nonce=self.nonce_96, unknown=7)

        # But some are only known by the base cipher
        # (e.g. use_aesni consumed by the AES module)
        AES.new(self.key_256, AES.MODE_SIV, nonce=self.nonce_96, use_aesni=False)
Example #30
0
def GetAndPrintEid(ik, scaler, beacon_time_seconds):
    """Return the EID generated by the given parameters."""
    tkdata = (
        "\x00" * 11
        + "\xFF"
        + "\x00" * 2
        + chr((beacon_time_seconds / (2 ** 24)) % 256)
        + chr((beacon_time_seconds / (2 ** 16)) % 256)
    )
    PrintBinary("Temporary Key data", tkdata)
    tk = AES.new(ik, AES.MODE_ECB).encrypt(tkdata)
    PrintBinary("Temporary Key", tk)
    beacon_time_seconds = (beacon_time_seconds // 2 ** scaler) * (2 ** scaler)
    eiddata = (
        "\x00" * 11
        + chr(scaler)
        + chr((beacon_time_seconds / (2 ** 24)) % 256)
        + chr((beacon_time_seconds / (2 ** 16)) % 256)
        + chr((beacon_time_seconds / (2 ** 8)) % 256)
        + chr((beacon_time_seconds / (2 ** 0)) % 256)
    )
    PrintBinary("Ephemeral Id data", eiddata)
    eid = AES.new(tk, AES.MODE_ECB).encrypt(eiddata)[:8]
    PrintBinary("Ephemeral Id", eid)
    return eid