本文整理汇总了Python中Cryptodome.Hash.HMAC.new方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.new方法的具体用法?Python HMAC.new怎么用?Python HMAC.new使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cryptodome.Hash.HMAC
的用法示例。
在下文中一共展示了HMAC.new方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: GSS_GetMIC
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def GSS_GetMIC(self, sessionKey, data, sequenceNumber, direction = 'init'):
GSS_GETMIC_HEADER = '\x60\x23\x06\x09\x2a\x86\x48\x86\xf7\x12\x01\x02\x02'
token = self.MIC()
# Let's pad the data
pad = (4 - (len(data) % 4)) & 0x3
padStr = chr(pad) * pad
data += padStr
token['SGN_ALG'] = GSS_HMAC
if direction == 'init':
token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\x00'*4
else:
token['SND_SEQ'] = struct.pack('>L', sequenceNumber) + '\xff'*4
Ksign = HMAC.new(sessionKey.contents, 'signaturekey\0', MD5).digest()
Sgn_Cksum = MD5.new( struct.pack('<L',15) + str(token)[:8] + data).digest()
Sgn_Cksum = HMAC.new(Ksign, Sgn_Cksum, MD5).digest()
token['SGN_CKSUM'] = Sgn_Cksum[:8]
Kseq = HMAC.new(sessionKey.contents, struct.pack('<L',0), MD5).digest()
Kseq = HMAC.new(Kseq, token['SGN_CKSUM'], MD5).digest()
token['SND_SEQ'] = ARC4.new(Kseq).encrypt(token['SND_SEQ'])
finalData = GSS_GETMIC_HEADER + token.getData()
return finalData
示例2: decrypt
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def decrypt(self, key):
if self['HashAlgo'] == ALGORITHMS.CALG_HMAC.value:
hashModule = SHA1
else:
hashModule = ALGORITHMS_DATA[self['HashAlgo']][1]
prf = lambda p, s: HMAC.new(p, s, hashModule).digest()
derivedBlob = self.deriveKey(key, self['Salt'],
ALGORITHMS_DATA[self['CryptAlgo']][0] + ALGORITHMS_DATA[self['CryptAlgo']][3],
count=self['MasterKeyIterationCount'], hashFunction=prf)
cryptKey = derivedBlob[:ALGORITHMS_DATA[self['CryptAlgo']][0]]
iv = derivedBlob[ALGORITHMS_DATA[self['CryptAlgo']][0]:][:ALGORITHMS_DATA[self['CryptAlgo']][3]]
cipher = ALGORITHMS_DATA[self['CryptAlgo']][1].new(cryptKey, mode = ALGORITHMS_DATA[self['CryptAlgo']][2], iv = iv)
cleartext = cipher.decrypt(self['data'])
decryptedKey = cleartext[-64:]
hmacSalt = cleartext[:16]
hmac = cleartext[16:][:ALGORITHMS_DATA[self['HashAlgo']][0]]
hmacKey = HMAC.new(key, hmacSalt, hashModule).digest()
hmacCalculated = HMAC.new(hmacKey, decryptedKey, hashModule ).digest()
if hmacCalculated[:ALGORITHMS_DATA[self['HashAlgo']][0]] == hmac:
self.decryptedKey = decryptedKey
return decryptedKey
else:
return None
示例3: runTest
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def runTest(self):
key = b"0" * 16
data = b"\x00\x01\x02"
def get_mv_ro(data):
return memoryview(data)
def get_mv_rw(data):
return memoryview(bytearray(data))
for get_mv in (get_mv_ro, get_mv_rw):
# Data and key can be a memoryview (during initialization)
key_mv = get_mv(key)
data_mv = get_mv(data)
h1 = HMAC.new(key, data)
h2 = HMAC.new(key_mv, data_mv)
if not data_mv.readonly:
key_mv[:1] = b'\xFF'
data_mv[:1] = b'\xFF'
self.assertEqual(h1.digest(), h2.digest())
# Data can be a memoryview (during operation)
data_mv = get_mv(data)
h1 = HMAC.new(key)
h2 = HMAC.new(key)
h1.update(data)
h2.update(data_mv)
if not data_mv.readonly:
data_mv[:1] = b'\xFF'
self.assertEqual(h1.digest(), h2.digest())
示例4: ComputeResponsev2
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def ComputeResponsev2(NegFlg, ResponseKeyNT, ResponseKeyLM, ServerChallenge,
ClientChallenge, Time=None, ServerName=None, av_pairs=None):
if Time is None:
Time = nttime.NtTime(nttime.datetime.now())
if ServerName is None:
ServerName = "SERVER"
ServerName = ServerName.encode("utf-16-le")
TimeBuf = array.array("B")
cur = core.Cursor(TimeBuf,0)
cur.encode_uint64le(Time)
Responseversion = "\x01"
HiResponseversion = "\x01"
ntlmv2_client_challenge = NTLMv2ClientChallenge()
ntlmv2_client_challenge.time_stamp = Time
ntlmv2_client_challenge.challenge_from_client = ClientChallenge
if av_pairs is not None:
ntlmv2_client_challenge.av_pairs = av_pairs
temp = encode_frame(ntlmv2_client_challenge).tostring()
NTProofStr = HMAC.new(ResponseKeyNT,
ServerChallenge + temp,
MD5).digest()
NtChallengeResponse = NTProofStr + temp
LmChallengeResponse = HMAC.new(ResponseKeyLM,
ServerChallenge + ClientChallenge,
MD5).digest() +\
ClientChallenge
SessionBaseKey = HMAC.new(ResponseKeyNT, NTProofStr, MD5).digest()
return NtChallengeResponse, LmChallengeResponse, SessionBaseKey
示例5: encrypt
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def encrypt(cls, key, keyusage, plaintext, confounder):
if confounder is None:
confounder = get_random_bytes(8)
ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
cksum = HMAC.new(ki, confounder + plaintext, MD5).digest()
ke = HMAC.new(ki, cksum, MD5).digest()
return cksum + ARC4.new(ke).encrypt(bytes(confounder + plaintext))
示例6: deriveKeysFromUser
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def deriveKeysFromUser(self, sid, password):
# Will generate two keys, one with SHA1 and another with MD4
key1 = HMAC.new(SHA1.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
key2 = HMAC.new(MD4.new(password.encode('utf-16le')).digest(), (sid + '\0').encode('utf-16le'), SHA1).digest()
# For Protected users
tmpKey = pbkdf2_hmac('sha256', MD4.new(password.encode('utf-16le')).digest(), sid.encode('utf-16le'), 10000)
tmpKey2 = pbkdf2_hmac('sha256', tmpKey, sid.encode('utf-16le'), 1)[:16]
key3 = HMAC.new(tmpKey2, (sid + '\0').encode('utf-16le'), SHA1).digest()[:20]
return key1, key2, key3
示例7: runTest
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def runTest(self):
key = b("\x90\x91\x92\x93") * 4
payload = b("\x00") * 100
for hashname, hashmod in self.hashmods.items():
if hashmod is None:
continue
self.description = "Test HMAC in combination with " + hashname
one = HMAC.new(key, payload, hashmod).digest()
two = HMAC.new(key, payload, hashmod.new()).digest()
self.assertEqual(one, two)
示例8: verfiyMessageSignature
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def verfiyMessageSignature(self, message, hex_mac, method=None,
slot_id=DEFAULT_KEY):
"""
verify the hex mac is same for the message -
the comparison is done in a constant time comparison
:param message: the original message
:param hex_mac: the to compared mac in hex
:param method: the hash method - we use by default sha256
:param slot_id: which key should be used
:return: boolean
"""
sign_key = None
result = True
if method is None:
method = SHA256
try:
sign_key = self.getSecret(slot_id)
hmac = HMAC.new(sign_key, message, method)
sign_mac = HMAC.new(sign_key, message, method).hexdigest()
res = 0
# as we compare on hex, we have to multiply by 2
digest_size = hmac.digest_size * 2
for x, y in zip(hex_mac, sign_mac):
res |= ord(x) ^ ord(y)
if len(sign_mac) != digest_size:
result = False
if res:
result = False
except ValueError as err:
log.error("Mac Comparison failed! %r", err)
except Exception as exx:
pass
finally:
if sign_key:
zerome(sign_key)
del sign_key
return result
示例9: NTOWFv2
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def NTOWFv2(password, user, userdom):
nt_passwd = password.encode("utf-16-le")
nt_hash_passwd = MD4.new(nt_passwd).digest()
nt_userdom = (user.upper() + userdom).encode("utf-16-le")
return HMAC.new(nt_hash_passwd,
nt_userdom,
MD5).digest()
示例10: signMessage
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def signMessage(self, message, method=None, slot_id=DEFAULT_KEY):
"""
create the hex mac for the message -
:param message: the original message
:param method: the hash method - we use by default sha256
:param slot_id: which key should be used
:return: hex mac
"""
sign_key = None
if method is None:
method = SHA256
try:
sign_key = self.getSecret(slot_id)
hex_mac = HMAC.new(sign_key, message, method).hexdigest()
finally:
if sign_key:
zerome(sign_key)
del sign_key
return hex_mac
示例11: encrypt
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def encrypt(plaintext):
iv = urandom(16)
salt = urandom(8)
iterations = 1000
ks = 128
ts = 64
hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest()
password = b64encode(urandom(32))
key = PBKDF2(password, salt=salt, count=iterations, prf=hash_func)
smalliv = trunc_iv(iv, plaintext, 0)
cipher = AES.new(key, mode=AES.MODE_CCM, nonce=smalliv, mac_len=ts // 8)
ciphertext = b''.join(cipher.encrypt_and_digest(plaintext))
# OrderedDict because 0bin is a piece of shit requiring "iv" as the first key
return password.decode('ascii'), OrderedDict([
('iv', b64encode(iv).decode('ascii')),
('v', 1),
('iter', iterations),
('ks', ks),
('ts', ts),
('mode', 'ccm'),
('adata', ''),
('cipher', 'aes'),
('salt', b64encode(salt).decode('ascii')),
('ct', b64encode(ciphertext).decode('ascii')),
])
示例12: aes_cbc_hmac_decrypt
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def aes_cbc_hmac_decrypt(key, iv, aad, ct, tag):
"""
Perform authenticated decryption with the combined AES-CBC
and HMAC algorithm.
:param key : Key; length MUST be 32, 48, or 64 octets
:param iv : Initialization vector; length MUST be 16 octets
:param aad: Additional authenticated data
:param ct : Cipher text
:param tag: Authentication tag
:return: (plaintext, result) tuple, with plaintext as bytes
and result as boolean
"""
ka, ke, seclen, dgst = get_keys_seclen_dgst(key, iv)
# Verify A || IV || E || AL
al = pack("!Q", 8*len(aad))
if isinstance(aad, str):
aad = aad.encode("utf-8")
mac_input = aad + iv + ct + al
h = HMAC.new(ka, digestmod=dgst)
h.update(mac_input)
candidate = h.digest()[:seclen]
# Decrypt if verified
if candidate == tag:
cipher = AES.new(ke, AES.MODE_CBC, iv)
pt = pkcs5trim(cipher.decrypt(ct))
return pt
else:
raise VerificationFailure('AES-CBC HMAC')
示例13: deriveKey
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def deriveKey(self, sessionKey):
def fixparity(deskey):
from six import indexbytes, b
temp = b''
for i in range(len(deskey)):
t = (bin(indexbytes(deskey,i))[2:]).rjust(8,'0')
if t[:7].count('1') %2 == 0:
temp+= b(chr(int(t[:7]+'1',2)))
else:
temp+= b(chr(int(t[:7]+'0',2)))
return temp
if len(sessionKey) > ALGORITHMS_DATA[self['HashAlgo']][4]:
derivedKey = HMAC.new(sessionKey, digestmod = ALGORITHMS_DATA[self['HashAlgo']][1]).digest()
else:
derivedKey = sessionKey
if len(derivedKey) < ALGORITHMS_DATA[self['CryptAlgo']][0]:
# Extend the key
derivedKey += b'\x00'*ALGORITHMS_DATA[self['HashAlgo']][4]
ipad = bytearray([ i ^ 0x36 for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])
opad = bytearray([ i ^ 0x5c for i in bytearray(derivedKey)][:ALGORITHMS_DATA[self['HashAlgo']][4]])
derivedKey = ALGORITHMS_DATA[self['HashAlgo']][1].new(ipad).digest() + \
ALGORITHMS_DATA[self['HashAlgo']][1].new(opad).digest()
derivedKey = fixparity(derivedKey)
return derivedKey
示例14: decrypt
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def decrypt(secretkey, params):
iv = b64decode(params['iv'])
salt = b64decode(params['salt'])
#~ keylen = params.get('ks', 128) // 8 # FIXME use somewhere?
taglen = params.get('ts', 64) // 8
iterations = params.get('iter', 1000)
data = b64decode(params['ct'])
ciphertext = data[:-taglen]
tag = data[-taglen:]
if params.get('adata'):
raise NotImplementedError('authenticated data support is not implemented')
iv = trunc_iv(iv, ciphertext, taglen)
hash_func = lambda k, s: HMAC.new(k, s, SHA256).digest()
key = PBKDF2(secretkey, salt=salt, count=iterations, prf=hash_func)
mode_str = params.get('mode', 'ccm')
mode = dict(ccm=AES.MODE_CCM)[mode_str]
if mode_str == 'ccm':
cipher = AES.new(key, mode=AES.MODE_CCM, nonce=iv, mac_len=taglen)
else:
cipher = AES.new(key, mode=mode, iv=iv)
decrypted = cipher.decrypt_and_verify(ciphertext, tag)
return decrypted
示例15: aes_cbc_hmac_encrypt
# 需要导入模块: from Cryptodome.Hash import HMAC [as 别名]
# 或者: from Cryptodome.Hash.HMAC import new [as 别名]
def aes_cbc_hmac_encrypt(key, iv, aad, pt):
"""
Perform authenticated encryption with the combined AES-CBC
and HMAC algorithm.
:param key: key; length MUST be 32, 48, or 64 octets
:param iv: Initialization vector; length MUST be 16 octets
:param aad: Additional authenticated data
:param pt: Plaintext
:return: (ciphertext, tag) tuple, with each as bytes
"""
ka, ke, seclen, dgst = get_keys_seclen_dgst(key, iv)
# Encrypt
cipher = AES.new(ke, AES.MODE_CBC, iv)
ct = cipher.encrypt(pkcs5pad(pt))
# MAC A || IV || E || AL
al = pack("!Q", 8*len(aad))
mac_input = aad + iv + ct + al
h = HMAC.new(ka, digestmod=dgst)
h.update(mac_input)
tag = h.digest()[:seclen]
return ct, tag