当前位置: 首页>>代码示例>>Python>>正文


Python HMAC.hexdigest方法代码示例

本文整理汇总了Python中Crypto.Hash.HMAC.HMAC.hexdigest方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.hexdigest方法的具体用法?Python HMAC.hexdigest怎么用?Python HMAC.hexdigest使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Crypto.Hash.HMAC.HMAC的用法示例。


在下文中一共展示了HMAC.hexdigest方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: putSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def putSecret(name, secret, version, kms_key="alias/credstash",
              region="us-east-1", table="credential-store", context=None):
    '''
    put a secret called `name` into the secret-store,
    protected by the key kms_key
    '''
    kms = boto.kms.connect_to_region(region)
    # generate a a 64 byte key.
    # Half will be for data encryption, the other half for HMAC
    try:
        kms_response = kms.generate_data_key(kms_key, context, 64)
    except:
        raise KmsError("Could not generate key using KMS key %s" % kms_key)
    data_key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    wrapped_key = kms_response['CiphertextBlob']

    enc_ctr = Counter.new(128)
    encryptor = AES.new(data_key, AES.MODE_CTR, counter=enc_ctr)

    c_text = encryptor.encrypt(secret)
    # compute an HMAC using the hmac key and the ciphertext
    hmac = HMAC(hmac_key, msg=c_text, digestmod=SHA256)
    b64hmac = hmac.hexdigest()

    secretStore = Table(table,
                        connection=boto.dynamodb2.connect_to_region(region))

    data = {}
    data['name'] = name
    data['version'] = version if version != "" else "1"
    data['key'] = b64encode(wrapped_key)
    data['contents'] = b64encode(c_text)
    data['hmac'] = b64hmac
    return secretStore.put_item(data=data)
开发者ID:Expii,项目名称:credstash,代码行数:37,代码来源:credstash.py

示例2: __init__

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
    def __init__(self, stash_key, manager_provider, aws_profile=None, aws_region=None, aws_bucket=None):
        check_latest_version()

        self._aws_manager = manager_provider.aws_manager(aws_profile, aws_region or 'us-east-1')

        if aws_bucket is None:
            deployment_bucket_name = 'novastash_%s' % self._aws_manager.account_alias
        else:
            deployment_bucket_name = aws_bucket

        key = "%s.txt.enc" % stash_key
        existing_stash = self._aws_manager.s3_get(deployment_bucket_name, key)

        if existing_stash is None:
            raise NovaError("No stash '%s' found!" % stash_key)
        else:
            contents = existing_stash['Body'].read()
            metadata = existing_stash['Metadata']
            encryption_key = metadata['encryption-key']
            kms_response = self._aws_manager.kms_decrypt(b64decode(encryption_key), {})

            key = kms_response['Plaintext'][:32]
            hmac_key = kms_response['Plaintext'][32:]
            hmac = HMAC(hmac_key, msg=b64decode(contents), digestmod=SHA256)

            if hmac.hexdigest() != metadata['hmac']:
                raise NovaError("Computed HMAC on '%s' does not match stored HMAC" % stash_key)

            dec_ctr = Counter.new(128)
            decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
            print(decryptor.decrypt(b64decode(contents)).decode("utf-8"))
开发者ID:gilt,项目名称:nova,代码行数:33,代码来源:decrypt.py

示例3: putSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def putSecret(name, secret, version, kms_key="alias/credstash",
              region="us-east-1", context=None):
    '''
    put a secret called `name` into the secret-store,
    protected by the key kms_key
    '''
    if not context:
        context = {}
    kms = boto3.client('kms', region_name=region)
    # generate a a 64 byte key.
    # Half will be for data encryption, the other half for HMAC
    # try:
    kms_response = kms.generate_data_key(KeyId=kms_key, EncryptionContext=context, NumberOfBytes=64)
    # except:
    #     raise KmsError("Could not generate key using KMS key %s" % kms_key)
    data_key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    wrapped_key = kms_response['CiphertextBlob']

    enc_ctr = Counter.new(128)
    encryptor = AES.new(data_key, AES.MODE_CTR, counter=enc_ctr)

    c_text = encryptor.encrypt(secret)
    # compute an HMAC using the hmac key and the ciphertext
    hmac = HMAC(hmac_key, msg=c_text, digestmod=SHA256)
    b64hmac = hmac.hexdigest()

    data = {}
    data['name'] = name
    data['version'] = version if version != "" else "1"
    data['key'] = b64encode(wrapped_key).decode('utf-8')
    data['contents'] = b64encode(c_text).decode('utf-8')
    data['hmac'] = b64hmac
    with open('{0}.{1}.json'.format(name,data['version']), 'w') as fp:
      json.dump(data, fp)
开发者ID:hirenj,项目名称:credstash-local,代码行数:37,代码来源:credstash-local.py

示例4: getSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def getSecret(name, version="", region="us-east-1", table="credential-store"):
    '''
    fetch and decrypt the secret called `name`
    '''
    secretStore = Table(table, connection=boto.dynamodb2.connect_to_region(region))
    if version == "":
        # do a consistent fetch of the credential with the highest version
        result_set = [x for x in secretStore.query_2(limit=1, reverse=True, consistent=True, name__eq=name)]
        if not result_set:
            raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
        material = result_set[0]
    else:
        material = secretStore.get_item(name=name, version=version)

    kms = boto.kms.connect_to_region(region)
    # Check the HMAC before we decrypt to verify ciphertext integrity
    try:
        kms_response = kms.decrypt(b64decode(material['key']))
    except:
        raise KmsError("Could not decrypt hmac key with KMS")
    key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    hmac = HMAC(hmac_key, msg=b64decode(material['contents']), digestmod=SHA256)
    if hmac.hexdigest() != material['hmac']:
        raise IntegrityError("Computed HMAC on %s does not match stored HMAC" % name)
    dec_ctr = Counter.new(128)
    decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
    plaintext = decryptor.decrypt(b64decode(material['contents']))
    return plaintext
开发者ID:askulkarni2,项目名称:credstash,代码行数:31,代码来源:credstash.py

示例5: getSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def getSecret(name, version="", region=None,
              table="credential-store", context=None,
              **kwargs):
    '''
    fetch and decrypt the secret called `name`
    '''
    if not context:
        context = {}

    session = get_session(**kwargs)
    dynamodb = session.resource('dynamodb', region_name=region)
    secrets = dynamodb.Table(table)

    if version == "":
        # do a consistent fetch of the credential with the highest version
        response = secrets.query(Limit=1,
                                 ScanIndexForward=False,
                                 ConsistentRead=True,
                                 KeyConditionExpression=boto3.dynamodb.conditions.Key("name").eq(name))
        if response["Count"] == 0:
            raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
        material = response["Items"][0]
    else:
        response = secrets.get_item(Key={"name": name, "version": version})
        if "Item" not in response:
            raise ItemNotFound("Item {'name': '%s', 'version': '%s'} couldn't be found." % (name, version))
        material = response["Item"]

    kms = session.client('kms', region_name=region)
    # Check the HMAC before we decrypt to verify ciphertext integrity
    try:
        kms_response = kms.decrypt(CiphertextBlob=b64decode(material['key']), EncryptionContext=context)
    except botocore.exceptions.ClientError as e:
        if e.response["Error"]["Code"] == "InvalidCiphertextException":
            if context is None:
                msg = ("Could not decrypt hmac key with KMS. The credential may "
                       "require that an encryption context be provided to decrypt "
                       "it.")
            else:
                msg = ("Could not decrypt hmac key with KMS. The encryption "
                       "context provided may not match the one used when the "
                       "credential was stored.")
        else:
            msg = "Decryption error %s" % e
        raise KmsError(msg)
    except Exception as e:
        raise KmsError("Decryption error %s" % e)
    key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    hmac = HMAC(hmac_key, msg=b64decode(material['contents']),
                digestmod=SHA256)
    if hmac.hexdigest() != material['hmac']:
        raise IntegrityError("Computed HMAC on %s does not match stored HMAC"
                             % name)
    dec_ctr = Counter.new(128)
    decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
    plaintext = decryptor.decrypt(b64decode(material['contents'])).decode("utf-8")
    return plaintext
开发者ID:yarbelk,项目名称:credstash,代码行数:60,代码来源:credstash.py

示例6: __init__

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
    def __init__(self, stash_key, value, manager_provider, aws_profile=None, aws_region=None, aws_bucket=None, kms_key='alias/novastash'):
        check_latest_version()

        self._aws_manager = manager_provider.aws_manager(aws_profile, aws_region or 'us-east-1')

        if aws_bucket is None:
            deployment_bucket_name = 'novastash_%s' % self._aws_manager.account_alias
        else:
            deployment_bucket_name = aws_bucket

        if not self._aws_manager.kms_key_exists(kms_key):
            raise NovaError("Please setup the novastash KMS key.")

        self._aws_manager.create_bucket(deployment_bucket_name, "Creating novastash bucket '%s'" % deployment_bucket_name)

        # generate a a 64 byte key.
        # Half will be for data encryption, the other half for HMAC
        kms_response = self._aws_manager.kms_generate_data_key(kms_key, {})

        data_key = tobytes(kms_response['Plaintext'][:32])
        hmac_key = tobytes(kms_response['Plaintext'][32:])
        wrapped_key = tobytes(kms_response['CiphertextBlob'])

        enc_ctr = Counter.new(128)
        encryptor = AES.new(data_key, AES.MODE_CTR, counter=enc_ctr)

        c_text = encryptor.encrypt(tobytes(value))
        # compute an HMAC using the hmac key and the ciphertext
        hmac = HMAC(hmac_key, msg=c_text, digestmod=SHA256)
        b64hmac = hmac.hexdigest()

        key = "%s.txt.enc" % stash_key
        existing_stash = self._aws_manager.s3_head(deployment_bucket_name, key)

        if existing_stash is None:
            print(colored("Stashing '%s'" % stash_key))
            self._aws_manager.s3_put(
                deployment_bucket_name,
                b64encode(c_text).decode('utf-8'),
                key,
                {'encryption-key': b64encode(wrapped_key).decode('utf-8'), 'hmac': b64hmac}
            )
        else:
            perform_overwrite = query_yes_no("Stash '%s' already exists, want to overwrite?" % stash_key, default="no")
            if perform_overwrite:
                self._aws_manager.s3_put(
                    deployment_bucket_name,
                    b64encode(c_text).decode('utf-8'),
                    key,
                    {'encryption-key': b64encode(wrapped_key).decode('utf-8'), 'hmac': b64hmac}
                )
            else:
                print(colored("Not stashing anything for key '%s'" % stash_key))
开发者ID:gilt,项目名称:nova,代码行数:55,代码来源:encrypt.py

示例7: getSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def getSecret(name, version="", region="us-east-1",
              table="credential-store", context=None):
    '''
    fetch and decrypt the secret called `name`
    '''
    if not context:
        context = {}
    secretStore = Table(table,
                        connection=boto.dynamodb2.connect_to_region(region))
    if version == "":
        # do a consistent fetch of the credential with the highest version
        result_set = [x for x in secretStore.query_2(limit=1, reverse=True,
                                                     consistent=True,
                                                     name__eq=name)]
        if not result_set:
            raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
        material = result_set[0]
    else:
        material = secretStore.get_item(name=name, version=version)

    kms = boto3.client('kms', region_name=region)
    # Check the HMAC before we decrypt to verify ciphertext integrity
    try:
        kms_response = kms.decrypt(CiphertextBlob=b64decode(material['key']), EncryptionContext=context)
    except boto.kms.exceptions.InvalidCiphertextException:
        if context is None:
            msg = ("Could not decrypt hmac key with KMS. The credential may "
                   "require that an encryption context be provided to decrypt "
                   "it.")
        else:
            msg = ("Could not decrypt hmac key with KMS. The encryption "
                   "context provided may not match the one used when the "
                   "credential was stored.")
        raise KmsError(msg)
    except Exception as e:
        raise KmsError("Decryption error %s" % e)
    key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    hmac = HMAC(hmac_key, msg=b64decode(material['contents']),
                digestmod=SHA256)
    if hmac.hexdigest() != material['hmac']:
        raise IntegrityError("Computed HMAC on %s does not match stored HMAC"
                             % name)
    dec_ctr = Counter.new(128)
    decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
    plaintext = decryptor.decrypt(b64decode(material['contents'])).decode("utf-8")
    return plaintext
开发者ID:a5an0,项目名称:credstash,代码行数:49,代码来源:credstash.py

示例8: getSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def getSecret(name, version="", region="us-east-1",
              table="credential-store", context=None):
    '''
    fetch and decrypt the secret called `name`
    '''
    if not context:
        context = {}

    if version == "":
        # do a consistent fetch of the credential with the highest version
        # list all files matching pattern
        pass
#        if not result_set:
#            raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
#        material = result_set[0]

    with open("{0}.{1}.json".format(name, version), 'r') as fp:
        material = json.load(fp)

    kms = boto3.client('kms', region_name=region)
    # Check the HMAC before we decrypt to verify ciphertext integrity
    try:
        kms_response = kms.decrypt(CiphertextBlob=b64decode(material['key']), EncryptionContext=context)
    except InvalidCiphertextException:
        if context is None:
            msg = ("Could not decrypt hmac key with KMS. The credential may "
                   "require that an encryption context be provided to decrypt "
                   "it.")
        else:
            msg = ("Could not decrypt hmac key with KMS. The encryption "
                   "context provided may not match the one used when the "
                   "credential was stored.")
        raise KmsError(msg)
    except Exception as e:
        raise KmsError("Decryption error %s" % e)
    key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    hmac = HMAC(hmac_key, msg=b64decode(material['contents']),
                digestmod=SHA256)
    if hmac.hexdigest() != material['hmac']:
        raise IntegrityError("Computed HMAC on %s does not match stored HMAC"
                             % name)
    dec_ctr = Counter.new(128)
    decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
    plaintext = decryptor.decrypt(b64decode(material['contents'])).decode("utf-8")
    return plaintext
开发者ID:hirenj,项目名称:credstash-local,代码行数:48,代码来源:credstash-local.py

示例9: putSecret

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
def putSecret(name, secret, version, kms_key="alias/credstash",
              region=None, table="credential-store", context=None,
              digest="SHA256", **kwargs):
    '''
    put a secret called `name` into the secret-store,
    protected by the key kms_key
    '''
    if not context:
        context = {}
    session = get_session(**kwargs)
    kms = session.client('kms', region_name=region)
    # generate a a 64 byte key.
    # Half will be for data encryption, the other half for HMAC
    try:
        kms_response = kms.generate_data_key(
            KeyId=kms_key, EncryptionContext=context, NumberOfBytes=64)
    except:
        raise KmsError("Could not generate key using KMS key %s" % kms_key)
    data_key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    wrapped_key = kms_response['CiphertextBlob']

    enc_ctr = Counter.new(128)
    encryptor = AES.new(data_key, AES.MODE_CTR, counter=enc_ctr)

    c_text = encryptor.encrypt(secret)
    # compute an HMAC using the hmac key and the ciphertext
    hmac = HMAC(hmac_key, msg=c_text, digestmod=get_digest(digest))

    b64hmac = hmac.hexdigest()

    dynamodb = session.resource('dynamodb', region_name=region)
    secrets = dynamodb.Table(table)

    data = {}
    data['name'] = name
    data['version'] = version if version != "" else paddedInt(1)
    data['key'] = b64encode(wrapped_key).decode('utf-8')
    data['contents'] = b64encode(c_text).decode('utf-8')
    data['hmac'] = b64hmac
    data['digest'] = digest

    return secrets.put_item(Item=data, ConditionExpression=Attr('name').not_exists())
开发者ID:maniacs-ops,项目名称:credstash,代码行数:45,代码来源:credstash.py

示例10: _check_hash_match

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
 def _check_hash_match(self, msg, hashed, db):
     for k in self.get_keys(db):
         h = HMAC(k[1], msg, self.algorithm)
         if h.hexdigest() == hashed:
             return True
     return False
开发者ID:kylechard,项目名称:webauthn,代码行数:8,代码来源:oauth2.py

示例11: encode

# 需要导入模块: from Crypto.Hash.HMAC import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC.HMAC import hexdigest [as 别名]
 def encode(self, msg, db):
     h = HMAC(self.get_current_key(db), msg, self.algorithm)
     return h.hexdigest()
开发者ID:kylechard,项目名称:webauthn,代码行数:5,代码来源:oauth2.py


注:本文中的Crypto.Hash.HMAC.HMAC.hexdigest方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。