Python Crypto.Hash.SHA256.new() Examples

The following are 30 code examples of Crypto.Hash.SHA256.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.Hash.SHA256 , 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: crypt.py    From googleapps-message-recall with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
      """Verifies a message against a signature.

      Args:
        message: string, The message to verify.
        signature: string, The signature on the message.

      Returns:
        True if message was signed by the private key associated with the public
        key that this object was constructed with.
      """
      try:
        return PKCS1_v1_5.new(self._pubkey).verify(
            SHA256.new(message), signature)
      except:
        return False 
Example #4
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 #5
Source File: crypt.py    From earthengine with MIT License 6 votes vote down vote up
def verify(self, message, signature):
      """Verifies a message against a signature.

      Args:
        message: string, The message to verify.
        signature: string, The signature on the message.

      Returns:
        True if message was signed by the private key associated with the public
        key that this object was constructed with.
      """
      try:
        return PKCS1_v1_5.new(self._pubkey).verify(
            SHA256.new(message), signature)
      except:
        return False 
Example #6
Source File: test_SHA256.py    From earthengine with MIT License 6 votes vote down vote up
def runTest(self):
        """SHA256: 512/520 MiB test"""
        from Crypto.Hash import SHA256
        zeros = bchr(0x00) * (1024*1024)

        h = SHA256.new(zeros)
        for i in xrange(511):
            h.update(zeros)

        # This test vector is from PyCrypto's old testdata.py file.
        self.assertEqual('9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767', h.hexdigest()) # 512 MiB

        for i in xrange(8):
            h.update(zeros)

        # This test vector is from PyCrypto's old testdata.py file.
        self.assertEqual('abf51ad954b246009dfe5a50ecd582fd5b8f1b8b27f30393853c3ef721e7fa6e', h.hexdigest()) # 520 MiB 
Example #7
Source File: lsasecrets.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def decrypt_aes(secret, key):
    """
    Based on code from http://lab.mediaservice.net/code/cachedump.rb
    """
    sha = SHA256.new()
    sha.update(key)
    for _i in range(1, 1000 + 1):
        sha.update(secret[28:60])
    aeskey = sha.digest()

    data = ""
    for i in range(60, len(secret), 16):
        aes = AES.new(aeskey, AES.MODE_CBC, '\x00' * 16)
        buf = secret[i : i + 16]
        if len(buf) < 16:
            buf += (16 - len(buf)) * "\00"
        data += aes.decrypt(buf)

    return data 
Example #8
Source File: lsasecrets.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def decrypt_secret(secret, key):
    """Python implementation of SystemFunction005.

    Decrypts a block of data with DES using given key.
    Note that key can be longer than 7 bytes."""
    decrypted_data = ''
    j = 0   # key index
    for i in range(0, len(secret), 8):
        enc_block = secret[i:i + 8]
        block_key = key[j:j + 7]
        des_key = hashdump.str_to_key(block_key)

        des = DES.new(des_key, DES.MODE_ECB)
        enc_block = enc_block + "\x00" * int(abs(8 - len(enc_block)) % 8)
        decrypted_data += des.decrypt(enc_block)

        j += 7
        if len(key[j:j + 7]) < 7:
            j = len(key[j:j + 7])

    (dec_data_len,) = struct.unpack("<L", decrypted_data[:4])
    return decrypted_data[8:8 + dec_data_len] 
Example #9
Source File: crypto.py    From ACE with Apache License 2.0 6 votes vote down vote up
def test_encryption_password(password):
    """Tests the given password against what is saved in the global section of the config file as the encryption password.
       Returns True if the password is correct, False if it is incorrect or if the password is not set."""
    assert isinstance(password, str)

    validation_hash = _get_validation_hash()
    if validation_hash is None:
        return False
    
    from Crypto.Hash import SHA256
    h = SHA256.new()
    h.update(password.encode())
    initial_digest = h.digest() # this would be the AES key

    h = SHA256.new()
    h.update(initial_digest)
    if h.hexdigest().lower() != validation_hash:
        return False

    return True 
Example #10
Source File: crypto.py    From ACE with Apache License 2.0 6 votes vote down vote up
def encrypt_chunk(chunk, password=None):
    """Encrypts the given chunk of data and returns the encrypted chunk.
       If password is None then saq.ENCRYPTION_PASSWORD is used instead.
       password must be a byte string 32 bytes in length."""

    if password is None:
        password = saq.ENCRYPTION_PASSWORD

    assert isinstance(password, bytes)
    assert len(password) == 32

    iv = Crypto.Random.OSRNG.posix.new().read(AES.block_size)
    encryptor = AES.new(password, AES.MODE_CBC, iv)

    original_size = len(chunk)

    if len(chunk) % 16 != 0:
        chunk += b' ' * (16 - len(chunk) % 16)

    result = struct.pack('<Q', original_size) + iv + encryptor.encrypt(chunk)
    return result 
Example #11
Source File: crypto.py    From ACE with Apache License 2.0 6 votes vote down vote up
def decrypt_chunk(chunk, password=None):
    """Decrypts the given encrypted chunk with the given password and returns the decrypted chunk.
       If password is None then saq.ENCRYPTION_PASSWORD is used instead.
       password must be a byte string 32 bytes in length."""

    if password is None:
        password = saq.ENCRYPTION_PASSWORD

    assert isinstance(password, bytes)
    assert len(password) == 32


    _buffer = io.BytesIO(chunk)
    original_size = struct.unpack('<Q', _buffer.read(struct.calcsize('Q')))[0]
    iv = _buffer.read(16)
    chunk = _buffer.read()

    #original_size = struct.unpack('<Q', chunk[0:struct.calcsize('Q')])[0]
    #iv = chunk[struct.calcsize('Q'):struct.calcsize('Q') + 16]
    #chunk = chunk[struct.calcsize('Q') + 16:]
    decryptor = AES.new(password, AES.MODE_CBC, iv)
    result = decryptor.decrypt(chunk)
    return result[:original_size] 
Example #12
Source File: crypto.py    From Python-Scripts with GNU General Public License v3.0 6 votes vote down vote up
def decrypt(key, filename):
	chunksize = 64 * 1024
	outputFile = filename.split('.hacklab')[0]


	with open(filename, 'rb') as infile:
		filesize = int(infile.read(16))
		IV = infile.read(16)
		decryptor = AES.new(key, AES.MODE_CBC, IV)

		with open(outputFile, 'wb') as outfile:

			while True:
				chunk = infile.read(chunksize)

				if len(chunk) == 0:
					break

				chunk = str(decryptor.decrypt(chunk))
				chunk = chunk.replace("0000hack1lab0000", "")
				outfile.write(chunk)
			outfile.truncate(filesize) 
Example #13
Source File: crypt.py    From splunk-ref-pas-code with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
      """Verifies a message against a signature.

      Args:
        message: string, The message to verify.
        signature: string, The signature on the message.

      Returns:
        True if message was signed by the private key associated with the public
        key that this object was constructed with.
      """
      try:
        return PKCS1_v1_5.new(self._pubkey).verify(
            SHA256.new(message), signature)
      except:
        return False 
Example #14
Source File: test_senders_simple.py    From webhooks with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple_signature():

    @unhashed_hook(event="example200", sender_callable=sender)
    def basic(wife, husband, creator, encoding, url, signing_secret):
        return {"husband": husband, "wife": wife}
    secret = "secret_key"
    status = basic("Audrey Roy Greenfeld", "Daniel Roy Greenfeld", creator="pydanny", encoding="application/json", url="http://httpbin.org", signing_secret = secret)

    assert status['wife'] == "Audrey Roy Greenfeld"
    assert status['husband'] == "Daniel Roy Greenfeld"
    signature = status['post_attributes']['headers']['x-hub-signature']
    body = {"wife": "Audrey Roy Greenfeld", "husband": "Daniel Roy Greenfeld"}

    if not isinstance(secret, bytes):
        secret = secret.encode('utf-8')
    hash = SHA256.new(secret)
    hash.update(json.dumps(body, cls=StandardJSONEncoder).encode("utf-8"))
    expected_signature = "sha256="+hash.hexdigest()
    assert signature == expected_signature 
Example #15
Source File: crypto.py    From WSC2 with GNU General Public License v3.0 6 votes vote down vote up
def encryptData(cls, clearText, key):
		"""Encrypts data with the provided key.
		The returned byte array is as follow:
		:==============:==================================================:
		: IV (16bytes) :    Encrypted (data + PKCS7 padding information)  :
		:==============:==================================================:
		"""

		# Generate a crypto secure random Initialization Vector
		iv = urandom(AES.block_size)

		# Perform PKCS7 padding so that clearText is a multiple of the block size
		clearText = cls.pad(clearText)

		cipher = AES.new(key, AES.MODE_CBC, iv)
		return iv + cipher.encrypt(clearText)

    #----------------------------------------------------------- 
Example #16
Source File: cas_client.py    From python-cas-client with MIT License 6 votes vote down vote up
def _build_auth_token_data(
        self,
        auth_token_ticket,
        authenticator,
        private_key,
        **kwargs
    ):
        auth_token = dict(
            authenticator=authenticator,
            ticket=auth_token_ticket,
            **kwargs
            )
        auth_token = json.dumps(auth_token, sort_keys=True)
        if six.PY3:
            auth_token = auth_token.encode('utf-8')
        digest = SHA256.new()
        digest.update(auth_token)
        auth_token = base64.b64encode(auth_token)
        rsa_key = RSA.importKey(private_key)
        signer = PKCS1_v1_5.new(rsa_key)
        auth_token_signature = signer.sign(digest)
        auth_token_signature = base64.b64encode(auth_token_signature)
        return auth_token, auth_token_signature 
Example #17
Source File: decrypt.py    From HackTheBox with MIT License 6 votes vote down vote up
def decrypt(key, filename):
	chunksize = 64*1024

	with open(filename, 'rb') as infile:
		IV = infile.read(16)
		#print IV

		decryptor = AES.new(key, AES.MODE_CBC, IV)

		with open('decryted.txt','wb') as outfile:
			while True:
				chunk = infile.read(chunksize)

				if len(chunk) == 0:
					break

				outfile.write(decryptor.decrypt(chunk)) 
Example #18
Source File: kissenc.py    From kissanime_dl with MIT License 6 votes vote down vote up
def ver5(raw_str, sess, type):
    # for version 5
    # requires a session because the js makes an ajax request
    # in 256
    sha = comb[type]['sha']
    topost = comb[type]['topost']
    payload = comb[type]['payload']
    f = comb[type]['f']

    if(sha == ''):
        post_data = sess.post(topost, headers=post_headers, data=payload)
        obj_sha = SHA256.new(post_data.text.encode('utf8') )
        comb[type]['sha'] = binascii.unhexlify(obj_sha.hexdigest() )
        sha = comb[type]['sha']

    g = AES.new(sha, AES.MODE_CBC, f)
    jj = base64.b64decode(raw_str)
    #
    filled = g.decrypt(jj)
    return pkc.decode(filled).decode('utf8') 
Example #19
Source File: cryptography.py    From modern-paste with MIT License 6 votes vote down vote up
def get_encid(decid):
    """
    Generate an encrypted ID from a decrypted ID

    :param decid: Decrypted ID, type int
    :return: Encrypted ID, type str
    """
    try:
        int(decid)
    except:
        raise InvalidIDException('Decrypted ID must be int-castable')

    # Slashes are not URL-friendly; replace them with dashes
    # Also strip the base64 padding: it can be recovered.
    cipher = AES.new(config.ID_ENCRYPTION_KEY, AES.MODE_CBC, config.ID_ENCRYPTION_IV)
    return base64.b64encode(cipher.encrypt(_pad(str(decid))), ALTCHARS).rstrip('=') 
Example #20
Source File: test_SHA256.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def runTest(self):
        """SHA256: 512/520 MiB test"""
        from Crypto.Hash import SHA256
        zeros = bchr(0x00) * (1024*1024)

        h = SHA256.new(zeros)
        for i in xrange(511):
            h.update(zeros)

        # This test vector is from PyCrypto's old testdata.py file.
        self.assertEqual('9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767', h.hexdigest()) # 512 MiB

        for i in xrange(8):
            h.update(zeros)

        # This test vector is from PyCrypto's old testdata.py file.
        self.assertEqual('abf51ad954b246009dfe5a50ecd582fd5b8f1b8b27f30393853c3ef721e7fa6e', h.hexdigest()) # 520 MiB 
Example #21
Source File: crypt.py    From billing-export-python with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
      """Verifies a message against a signature.

      Args:
        message: string, The message to verify.
        signature: string, The signature on the message.

      Returns:
        True if message was signed by the private key associated with the public
        key that this object was constructed with.
      """
      try:
        return PKCS1_v1_5.new(self._pubkey).verify(
            SHA256.new(message), signature)
      except:
        return False 
Example #22
Source File: crypt.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def verify(self, message, signature):
      """Verifies a message against a signature.

      Args:
        message: string, The message to verify.
        signature: string, The signature on the message.

      Returns:
        True if message was signed by the private key associated with the public
        key that this object was constructed with.
      """
      try:
        return PKCS1_v1_5.new(self._pubkey).verify(
            SHA256.new(message), signature)
      except:
        return False 
Example #23
Source File: SHAd256.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def new(data=None):
    """Return a new SHAd256 hashing object"""
    if not data:
        data=b("")
    sha = _SHAd256(_SHAd256._internal, SHA256.new(data))
    sha.new = globals()['new']
    return sha

# vim:set ts=4 sw=4 sts=4 expandtab: 
Example #24
Source File: crypto.py    From gitlab-tools with GNU General Public License v3.0 5 votes vote down vote up
def calculate_fingerprint(pkey: paramiko.pkey.PKey, algorithm: str='md5') -> bytes:
    """
    Calculates fingerprint for PKey
    :param pkey: pkey
    :param algorithm: algoright to use 
    :return: fingerprint
    """

    h = hashlib.new(algorithm)
    h.update(pkey.asbytes())
    return h.digest() 
Example #25
Source File: AliPay.py    From django-RESTfulAPI with MIT License 5 votes vote down vote up
def _verify(self, raw_content, signature):
        # 开始计算签名
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False 
Example #26
Source File: AliPay.py    From django-RESTfulAPI with MIT License 5 votes vote down vote up
def sign(self, unsigned_string):
        # 开始计算签名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        # base64 编码,转换为unicode表示并移除回车
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign 
Example #27
Source File: client.py    From coinbase-python with Apache License 2.0 5 votes vote down vote up
def verify_callback(self, body, signature):
        h = SHA256.new()
        h.update(body)
        key = Client.callback_public_key()
        verifier = PKCS1_v1_5.new(key)
        signature = bytes(signature, 'utf-8') if six.PY3 else bytes(signature)
        signature_buffer = base64.b64decode(signature)
        return verifier.verify(h, signature_buffer) 
Example #28
Source File: client.py    From coinbase-python with Apache License 2.0 5 votes vote down vote up
def create_checkout_order(self, checkout_id, **params):
        """https://developers.coinbase.com/api/v2#create-a-new-order-for-a-checkout"""
        response = self._post('v2', 'checkouts', checkout_id, 'orders', data=params)
        return self._make_api_object(response, Order) 
Example #29
Source File: client.py    From coinbase-python with Apache License 2.0 5 votes vote down vote up
def create_report(self, **params):
        """https://developers.coinbase.com/api/v2#generate-a-new-report"""
        if 'type' not in params and 'email' not in params:
            raise ValueError("Missing required parameter: 'type' or 'email'")
        response = self._post('v2', 'reports', data=params)
        return self._make_api_object(response, Report)

    # Buys API
    # ----------------------------------------------------------- 
Example #30
Source File: ustvnow.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_token(self):
        """
        Get the token for USTVNow
        :return: a valid token
        """

        if not self._token:
            log.debug("Getting new session token")
            res = self.session.http.get(self._token_url, params={
                "tenant_code": self.TENANT_CODE,
                "box_id": self.box_id,
                "product": self.TENANT_CODE,
                "device_id": 5,
                "display_lang_code": "ENG",
                "device_sub_type": "",
                "timezone": "UTC"
            })

            data = res.json()
            if data['status']:
                self._token = data['response']['sessionId']
                log.debug("New token: {}".format(self._token))
            else:
                log.error("Token acquisition failed: {details} ({detail})".format(**data['error']))
                raise PluginError("could not obtain token")

        return self._token