本文整理汇总了Python中Crypto.Hash.HMAC.HMAC类的典型用法代码示例。如果您正苦于以下问题:Python HMAC类的具体用法?Python HMAC怎么用?Python HMAC使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HMAC类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: putSecret
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)
示例2: __init__
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"))
示例3: putSecret
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)
示例4: _hmacedString
def _hmacedString(key, string):
"""
Return the SHA-1 HMAC hash of the given key and string.
"""
hash = HMAC(key, digestmod=sha)
hash.update(string)
return hash.digest()
示例5: getSecret
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
示例6: getSecret
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
示例7: __init__
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))
示例8: getSecret
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
示例9: getSecret
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
示例10: ExtractEntropySeed
def ExtractEntropySeed(rounds, username, password, salt=None):
# Concentrates and then extracts the random entropy provided
# by the password into a seed value for the first hash stage.
# If if an explicit salt value is missing, use a hash of
# the username as if it were the salt.
if salt is None:
salt = SHA512.new(username).digest()
# Confirm the supplied salt meets the minimum length of 64
# octets required, is aligned to a 32 octet boundary and does not
# exceed 1,024 octets. Some implementations may not handle salt
# values longer than 1,024 octets properly.
elif len(salt) < 64:
raise ValueError("The salt, if supplied, must be at least " \
"64 octets in length.")
elif operator.mod(len(salt), 32) != 0:
warnings.warn("The salt, if longer than 64 octets, should " \
"be aligned to a 32 octet boundary.")
elif len(salt) > 1024:
warnings.warn("The salt should not exceed 1,024 octets.")
# For salt values which don't match the 128 octets required for
# an HMAC key value, the salt is hashed twice using a 3 octet
# counter value of 0 and 1, and the outputs are concatenated.
if len(salt) != 128:
key = \
SHA512.new(salt + struct.pack('>I', 0)[1:4]).digest() + \
SHA512.new(salt + struct.pack('>I', 1)[1:4]).digest()
# If the supplied salt is 128 octets use it directly as the key value.
else:
key = salt
# Initialize the HMAC instance using the key created above.
hmac = HMAC(key, None, SHA512)
# Repeat the plaintext password successively based on
# the number of instances specified by the rounds variable.
for unused in range(0, rounds):
hmac.update(password)
# Create the 64 octet seed value.
seed = hmac.digest()
return seed
示例11: putSecret
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())
示例12: _check_hash_match
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
示例13: encode
def encode(self, msg, db):
h = HMAC(self.get_current_key(db), msg, self.algorithm)
return h.hexdigest()