本文整理汇总了Python中Crypto.Hash.HMAC.new方法的典型用法代码示例。如果您正苦于以下问题:Python HMAC.new方法的具体用法?Python HMAC.new怎么用?Python HMAC.new使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Crypto.Hash.HMAC
的用法示例。
在下文中一共展示了HMAC.new方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getHBootKey
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def getHBootKey(self):
LOG.debug('Calculating HashedBootKey from SAM')
QWERTY = "!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%\0"
DIGITS = "0123456789012345678901234567890123456789\0"
F = self.getValue(ntpath.join('SAM\Domains\Account','F'))[1]
domainData = DOMAIN_ACCOUNT_F(F)
rc4Key = self.MD5(domainData['Key0']['Salt'] + QWERTY + self.__bootKey + DIGITS)
rc4 = ARC4.new(rc4Key)
self.__hashedBootKey = rc4.encrypt(domainData['Key0']['Key']+domainData['Key0']['CheckSum'])
# Verify key with checksum
checkSum = self.MD5( self.__hashedBootKey[:16] + DIGITS + self.__hashedBootKey[:16] + QWERTY)
if checkSum != self.__hashedBootKey[16:]:
raise Exception('hashedBootKey CheckSum failed, Syskey startup password probably in use! :(')
示例2: __decryptSecret
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def __decryptSecret(self, key, value):
# [MS-LSAD] Section 5.1.2
plainText = ''
encryptedSecretSize = unpack('<I', value[:4])[0]
value = value[len(value)-encryptedSecretSize:]
key0 = key
for i in range(0, len(value), 8):
cipherText = value[:8]
tmpStrKey = key0[:7]
tmpKey = self.__cryptoCommon.transformKey(tmpStrKey)
Crypt1 = DES.new(tmpKey, DES.MODE_ECB)
plainText += Crypt1.decrypt(cipherText)
key0 = key0[7:]
value = value[8:]
# AdvanceKey
if len(key0) < 7:
key0 = key[len(key0):]
secret = LSA_SECRET_XP(plainText)
return secret['Secret']
示例3: __decryptLSA
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def __decryptLSA(self, value):
if self.__vistaStyle is True:
# ToDo: There could be more than one LSA Keys
record = LSA_SECRET(value)
tmpKey = self.__sha256(self.__bootKey, record['EncryptedData'][:32])
plainText = self.__cryptoCommon.decryptAES(tmpKey, record['EncryptedData'][32:])
record = LSA_SECRET_BLOB(plainText)
self.__LSAKey = record['Secret'][52:][:32]
else:
md5 = hashlib.new('md5')
md5.update(self.__bootKey)
for i in range(1000):
md5.update(value[60:76])
tmpKey = md5.digest()
rc4 = ARC4.new(tmpKey)
plainText = rc4.decrypt(value[12:60])
self.__LSAKey = plainText[0x10:0x20]
示例4: decrypt
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def decrypt(cls, key, keyusage, ciphertext):
if len(ciphertext) < 24:
raise ValueError('ciphertext too short')
cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
ke = HMAC.new(ki, cksum, MD5).digest()
basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
ok = _mac_equal(cksum, exp_cksum)
if not ok and keyusage == 9:
# Try again with usage 8, due to RFC 4757 errata.
ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
ok = _mac_equal(cksum, exp_cksum)
if not ok:
raise InvalidChecksum('ciphertext integrity failure')
# Discard the confounder.
return basic_plaintext[8:]
示例5: GSS_GetMIC
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.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
示例6: decrypt_hash
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def decrypt_hash(edata, nlkm, ch, xp = True):
if xp:
hmac_md5 = HMAC.new(nlkm, ch)
rc4key = hmac_md5.digest()
rc4 = ARC4.new(rc4key)
data = rc4.encrypt(edata)
else:
# based on Based on code from http://lab.mediaservice.net/code/cachedump.rb
aes = AES.new(nlkm[16:32], AES.MODE_CBC, ch)
data = ""
for i in range(0, len(edata), 16):
buf = edata[i : i + 16]
if len(buf) < 16:
buf += (16 - len(buf)) * "\00"
data += aes.decrypt(buf)
return data
示例7: encrypt
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def encrypt(self, plaintext, esn):
"""
Encrypt the given Plaintext with the encryption key
:param plaintext:
:return: Serialized JSON String of the encryption Envelope
"""
init_vector = get_random_bytes(16)
cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)
ciphertext = base64.standard_b64encode(
cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16))).decode('utf-8')
encryption_envelope = {
'ciphertext': ciphertext,
'keyid': '_'.join((esn, str(self.sequence_number))),
'sha256': 'AA==',
'iv': base64.standard_b64encode(init_vector).decode('utf-8')
}
return json.dumps(encryption_envelope)
示例8: __decryptHash
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def __decryptHash(self, rid, cryptedHash, constant, newStyle = False):
# Section 2.2.11.1.1 Encrypting an NT or LM Hash Value with a Specified Key
# plus hashedBootKey stuff
Key1,Key2 = self.__cryptoCommon.deriveKey(rid)
Crypt1 = DES.new(Key1, DES.MODE_ECB)
Crypt2 = DES.new(Key2, DES.MODE_ECB)
if newStyle is False:
rc4Key = self.MD5( self.__hashedBootKey[:0x10] + pack("<L",rid) + constant )
rc4 = ARC4.new(rc4Key)
key = rc4.encrypt(cryptedHash['Hash'])
else:
key = self.__cryptoCommon.decryptAES(self.__hashedBootKey[:0x10], cryptedHash['Hash'], cryptedHash['Salt'])[:16]
decryptedHash = Crypt1.decrypt(key[:8]) + Crypt2.decrypt(key[8:])
return decryptedHash
示例9: decrypt_hash
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def decrypt_hash(edata, nlkm, ch):
hmac_md5 = HMAC.new(nlkm,ch)
rc4key = hmac_md5.digest()
rc4 = ARC4.new(rc4key)
data = rc4.encrypt(edata)
return data
示例10: create_signature
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def create_signature(self, secret_key, to_sign):
sign = HMAC.new(secret_key, to_sign, SHA)
return str(b64encode(sign.hexdigest().encode()))
# creates device spec JSON
示例11: _randnum
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def _randnum(self, size):
from Crypto import Random
return Random.new().read(size)
示例12: PBKDF1
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
"""Derive one key from a password (or passphrase).
This function performs key derivation according an old version of
the PKCS#5 standard (v1.5).
This algorithm is called ``PBKDF1``. Even though it is still described
in the latest version of the PKCS#5 standard (version 2, or RFC2898),
newer applications should use the more secure and versatile `PBKDF2` instead.
:Parameters:
password : string
The secret password or pass phrase to generate the key from.
salt : byte string
An 8 byte string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation.
dkLen : integer
The length of the desired key. Default is 16 bytes, suitable for instance for `Crypto.Cipher.AES`.
count : integer
The number of iterations to carry out. It's recommended to use at least 1000.
hashAlgo : module
The hash algorithm to use, as a module or an object from the `Crypto.Hash` package.
The digest length must be no shorter than ``dkLen``.
The default algorithm is `SHA1`.
:Return: A byte string of length `dkLen` that can be used as key.
"""
if not hashAlgo:
hashAlgo = SHA1
password = tobytes(password)
pHash = hashAlgo.new(password+salt)
digest = pHash.digest_size
if dkLen>digest:
raise ValueError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
if len(salt)!=8:
raise ValueError("Salt is not 8 bytes long.")
for i in xrange(count-1):
pHash = pHash.new(pHash.digest())
return pHash.digest()[:dkLen]
示例13: PBKDF2
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def PBKDF2(password, salt, dkLen=16, count=1000, prf=None):
"""Derive one or more keys from a password (or passphrase).
This performs key derivation according to the PKCS#5 standard (v2.0),
by means of the ``PBKDF2`` algorithm.
:Parameters:
password : string
The secret password or pass phrase to generate the key from.
salt : string
A string to use for better protection from dictionary attacks.
This value does not need to be kept secret, but it should be randomly
chosen for each derivation. It is recommended to be at least 8 bytes long.
dkLen : integer
The cumulative length of the desired keys. Default is 16 bytes, suitable for instance for `Crypto.Cipher.AES`.
count : integer
The number of iterations to carry out. It's recommended to use at least 1000.
prf : callable
A pseudorandom function. It must be a function that returns a pseudorandom string
from two parameters: a secret and a salt. If not specified, HMAC-SHA1 is used.
:Return: A byte string of length `dkLen` that can be used as key material.
If you wanted multiple keys, just break up this string into segments of the desired length.
"""
password = tobytes(password)
if prf is None:
prf = lambda p,s: HMAC.new(p,s,SHA1).digest()
key = b('')
i = 1
while len(key)<dkLen:
U = previousU = prf(password,salt+struct.pack(">I", i))
for j in xrange(count-1):
previousU = t = prf(password,previousU)
U = strxor(U,t)
key += U
i = i + 1
return key[:dkLen]
示例14: test1
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def test1(self):
# Test only for HMAC-SHA1 as PRF
def prf(p,s):
return HMAC.new(p,s,SHA1).digest()
for i in xrange(len(self._testData)):
v = self._testData[i]
res = PBKDF2(v[0], t2b(v[1]), v[2], v[3])
res2 = PBKDF2(v[0], t2b(v[1]), v[2], v[3], prf)
self.assertEqual(res, t2b(v[4]))
self.assertEqual(res, res2)
示例15: __restore
# 需要导入模块: from Crypto.Hash import HMAC [as 别名]
# 或者: from Crypto.Hash.HMAC import new [as 别名]
def __restore(self):
# First of all stop the service if it was originally stopped
if self.__shouldStop is True:
LOG.info('Stopping service %s' % self.__serviceName)
scmr.hRControlService(self.__scmr, self.__serviceHandle, scmr.SERVICE_CONTROL_STOP)
if self.__disabled is True:
LOG.info('Restoring the disabled state for service %s' % self.__serviceName)
scmr.hRChangeServiceConfigW(self.__scmr, self.__serviceHandle, dwStartType = 0x4)
if self.__serviceDeleted is False:
# Check again the service we created does not exist, starting a new connection
# Why?.. Hitting CTRL+C might break the whole existing DCE connection
try:
rpc = transport.DCERPCTransportFactory(r'ncacn_np:%s[\pipe\svcctl]' % self.__smbConnection.getRemoteHost())
if hasattr(rpc, 'set_credentials'):
# This method exists only for selected protocol sequences.
rpc.set_credentials(*self.__smbConnection.getCredentials())
rpc.set_kerberos(self.__doKerberos, self.__kdcHost)
self.__scmr = rpc.get_dce_rpc()
self.__scmr.connect()
self.__scmr.bind(scmr.MSRPC_UUID_SCMR)
# Open SC Manager
ans = scmr.hROpenSCManagerW(self.__scmr)
self.__scManagerHandle = ans['lpScHandle']
# Now let's open the service
resp = scmr.hROpenServiceW(self.__scmr, self.__scManagerHandle, self.__tmpServiceName)
service = resp['lpServiceHandle']
scmr.hRDeleteService(self.__scmr, service)
scmr.hRControlService(self.__scmr, service, scmr.SERVICE_CONTROL_STOP)
scmr.hRCloseServiceHandle(self.__scmr, service)
scmr.hRCloseServiceHandle(self.__scmr, self.__serviceHandle)
scmr.hRCloseServiceHandle(self.__scmr, self.__scManagerHandle)
rpc.disconnect()
except Exception, e:
# If service is stopped it'll trigger an exception
# If service does not exist it'll trigger an exception
# So. we just wanna be sure we delete it, no need to
# show this exception message
pass