Python sha.new() Examples
The following are 30
code examples of sha.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
sha
, or try the search function
.
Example #1
Source File: __init__.py From faces with GNU General Public License v2.0 | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #2
Source File: __init__.py From earthengine with MIT License | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #3
Source File: test_sha.py From ironpython2 with Apache License 2.0 | 6 votes |
def check(self, data, digest): # Check digest matches the expected value obj = sha.new(data) computed = obj.hexdigest() self.assertTrue(computed == digest) # Verify that the value doesn't change between two consecutive # digest operations. computed_again = obj.hexdigest() self.assertTrue(computed == computed_again) # Check hexdigest() output matches digest()'s output digest = obj.digest() hexd = "" for c in digest: hexd += '%02x' % ord(c) self.assertTrue(computed == hexd)
Example #4
Source File: tests.py From dirigible-spreadsheet with MIT License | 6 votes |
def test_registration_view(self): """ Test that the registration view rejects invalid submissions, and creates a new user and redirects after a valid submission. """ # Invalid data fails. response = self.client.post(reverse('registration_register'), data={ 'username': 'alice', # Will fail on username uniqueness. 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.assertEqual(response.status_code, 200) self.failUnless(response.context['form']) self.failUnless(response.context['form'].errors) response = self.client.post(reverse('registration_register'), data={ 'username': 'foo', 'email': 'foo@example.com', 'password1': 'foo', 'password2': 'foo' }) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], 'http://testserver%s' % reverse('registration_complete')) self.assertEqual(RegistrationProfile.objects.count(), 3)
Example #5
Source File: __init__.py From faces with GNU General Public License v2.0 | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #6
Source File: __init__.py From sndlatr with Apache License 2.0 | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #7
Source File: cert.py From CyberScan with GNU General Public License v3.0 | 6 votes |
def is_revoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and is now valid again in a new CRL and bot are in the list, it will be considered revoked: this is because _all_ CRLs are checked (not only the freshest) and revocation status is not handled. Also note that the check on the issuer is performed on the Authority Key Identifier if available in _both_ the CRL and the Cert. Otherwise, the issuers are simply compared. """ for c in crl_list: if (self.authorityKeyID is not None and c.authorityKeyID is not None and self.authorityKeyID == c.authorityKeyID): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) elif (self.issuer == c.issuer): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) return False
Example #8
Source File: test_sha.py From BinderFilter with MIT License | 6 votes |
def check(self, data, digest): # Check digest matches the expected value obj = sha.new(data) computed = obj.hexdigest() self.assertTrue(computed == digest) # Verify that the value doesn't change between two consecutive # digest operations. computed_again = obj.hexdigest() self.assertTrue(computed == computed_again) # Check hexdigest() output matches digest()'s output digest = obj.digest() hexd = "" for c in digest: hexd += '%02x' % ord(c) self.assertTrue(computed == hexd)
Example #9
Source File: __init__.py From googleapps-message-recall with Apache License 2.0 | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #10
Source File: __init__.py From billing-export-python with Apache License 2.0 | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #11
Source File: test_sha.py From oss-ftp with MIT License | 6 votes |
def check(self, data, digest): # Check digest matches the expected value obj = sha.new(data) computed = obj.hexdigest() self.assertTrue(computed == digest) # Verify that the value doesn't change between two consecutive # digest operations. computed_again = obj.hexdigest() self.assertTrue(computed == computed_again) # Check hexdigest() output matches digest()'s output digest = obj.digest() hexd = "" for c in digest: hexd += '%02x' % ord(c) self.assertTrue(computed == hexd)
Example #12
Source File: __init__.py From aqua-monitor with GNU Lesser General Public License v3.0 | 6 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val) request_digest = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % ( self.credentials[0], self.challenge['realm'], self.challenge['snonce'], cnonce, request_uri, created, request_digest, keylist)
Example #13
Source File: cert.py From mptcp-abuse with GNU General Public License v2.0 | 6 votes |
def is_revoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and is now valid again in a new CRL and bot are in the list, it will be considered revoked: this is because _all_ CRLs are checked (not only the freshest) and revocation status is not handled. Also note that the check on the issuer is performed on the Authority Key Identifier if available in _both_ the CRL and the Cert. Otherwise, the issuers are simply compared. """ for c in crl_list: if (self.authorityKeyID is not None and c.authorityKeyID is not None and self.authorityKeyID == c.authorityKeyID): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) elif (self.issuer == c.issuer): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) return False
Example #14
Source File: cert.py From CVE-2016-6366 with MIT License | 6 votes |
def is_revoked(self, crl_list): """ Given a list of trusted CRL (their signature has already been verified with trusted anchors), this function returns True if the certificate is marked as revoked by one of those CRL. Note that if the Certificate was on hold in a previous CRL and is now valid again in a new CRL and bot are in the list, it will be considered revoked: this is because _all_ CRLs are checked (not only the freshest) and revocation status is not handled. Also note that the check on the issuer is performed on the Authority Key Identifier if available in _both_ the CRL and the Cert. Otherwise, the issuers are simply compared. """ for c in crl_list: if (self.authorityKeyID is not None and c.authorityKeyID is not None and self.authorityKeyID == c.authorityKeyID): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) elif (self.issuer == c.issuer): return self.serial in map(lambda x: x[0], c.revoked_cert_serials) return False
Example #15
Source File: models.py From dirigible-spreadsheet with MIT License | 5 votes |
def create_profile(self, user): """ Create a ``RegistrationProfile`` for a given ``User``, and return the ``RegistrationProfile``. The activation key for the ``RegistrationProfile`` will be a SHA1 hash, generated from a combination of the ``User``'s username and a random salt. """ salt = sha.new(str(random.random())).hexdigest()[:5] activation_key = sha.new(salt+user.username).hexdigest() return self.create(user=user, activation_key=activation_key)
Example #16
Source File: UcsBase.py From UcsPythonSDK with Apache License 2.0 | 5 votes |
def Expandkey(key, clen): """ Internal method supporting encryption and decryption functionality. """ import sha from string import join from array import array blocks = (clen + 19) / 20 xkey = [] seed = key for i in xrange(blocks): seed = sha.new(key + seed).digest() xkey.append(seed) j = join(xkey, '') return array('L', j)
Example #17
Source File: __init__.py From googleapps-message-recall with Apache License 2.0 | 5 votes |
def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False
Example #18
Source File: UcsBase.py From UcsPythonSDK with Apache License 2.0 | 5 votes |
def EncryptPassword(password, key): """ Encrypts the password using the given key. """ from time import time from array import array import hmac import sha import os import base64 H = UcsUtils.GetShaHash uhash = H(','.join(str(x) for x in [`time()`, `os.getpid()`, `len(password)`, password, key]))[:16] k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash) n = len(password) passwordStream = array('L', password + '0000'[n & 3:]) xkey = UcsUtils.Expandkey(k_enc, n + 4) for i in xrange(len(passwordStream)): passwordStream[i] = passwordStream[i] ^ xkey[i] ct = uhash + passwordStream.tostring()[:n] auth = hmac.new(ct, k_auth, sha).digest() encryptStr = ct + auth[:8] encodedStr = base64.encodestring(encryptStr) encryptedPassword = encodedStr.rstrip('\n') return encryptedPassword
Example #19
Source File: __init__.py From aqua-monitor with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, cache, safe=safename): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior self.cache = cache self.safe = safe if not os.path.exists(cache): os.makedirs(self.cache)
Example #20
Source File: UcsBase.py From UcsPythonSDK with Apache License 2.0 | 5 votes |
def DecryptPassword(cipher, key): """ Decrypts the password using the given key with which the password was encrypted first. """ import base64 import hmac import sha from array import array H = UcsUtils.GetShaHash cipher = cipher + "\n" cipher = base64.decodestring(cipher) n = len(cipher) - 16 - 8 uhash = cipher[:16] passwordStream = cipher[16:-8] + "0000"[n & 3:] auth = cipher[-8:] k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash) vauth = hmac.new(cipher[-8:], k_auth, sha).digest()[:8] passwordStream = array('L', passwordStream) xkey = UcsUtils.Expandkey(k_enc, n + 4) for i in xrange(len(passwordStream)): passwordStream[i] = passwordStream[i] ^ xkey[i] decryptedPassword = passwordStream.tostring()[:n] return decryptedPassword
Example #21
Source File: __init__.py From aqua-monitor with GNU Lesser General Public License v3.0 | 5 votes |
def __init__(self, credentials, host, request_uri, headers, response, content, http): Authentication.__init__(self, credentials, host, request_uri, headers, response, content, http) challenge = _parse_www_authenticate(response, 'www-authenticate') self.challenge = challenge['hmacdigest'] # TODO: self.challenge['domain'] self.challenge['reason'] = self.challenge.get('reason', 'unauthorized') if self.challenge['reason'] not in ['unauthorized', 'integrity']: self.challenge['reason'] = 'unauthorized' self.challenge['salt'] = self.challenge.get('salt', '') if not self.challenge.get('snonce'): raise UnimplementedHmacDigestAuthOptionError( _("The challenge doesn't contain a server nonce, or this one is empty.")) self.challenge['algorithm'] = self.challenge.get('algorithm', 'HMAC-SHA-1') if self.challenge['algorithm'] not in ['HMAC-SHA-1', 'HMAC-MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for algorithm: %s." % self.challenge['algorithm'])) self.challenge['pw-algorithm'] = self.challenge.get('pw-algorithm', 'SHA-1') if self.challenge['pw-algorithm'] not in ['SHA-1', 'MD5']: raise UnimplementedHmacDigestAuthOptionError( _("Unsupported value for pw-algorithm: %s." % self.challenge['pw-algorithm'])) if self.challenge['algorithm'] == 'HMAC-MD5': self.hashmod = _md5 else: self.hashmod = _sha if self.challenge['pw-algorithm'] == 'MD5': self.pwhashmod = _md5 else: self.pwhashmod = _sha self.key = "".join([self.credentials[0], ":", self.pwhashmod.new("".join([self.credentials[1], self.challenge['salt']])).hexdigest().lower(), ":", self.challenge['realm']]) self.key = self.pwhashmod.new(self.key).hexdigest().lower()
Example #22
Source File: __init__.py From aqua-monitor with GNU Lesser General Public License v3.0 | 5 votes |
def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False
Example #23
Source File: utils6.py From mptcp-abuse with GNU General Public License v2.0 | 5 votes |
def in6_getRandomizedIfaceId(ifaceid, previous=None): """ Implements the interface ID generation algorithm described in RFC 3041. The function takes the Modified EUI-64 interface identifier generated as described in RFC 4291 and an optional previous history value (the first element of the output of this function). If no previous interface identifier is provided, a random one is generated. The function returns a tuple containing the randomized interface identifier and the history value (for possible future use). Input and output values are provided in a "printable" format as depicted below. ex: >>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3') ('4c61:76ff:f46a:a5f3', 'd006:d540:db11:b092') >>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3', previous='d006:d540:db11:b092') ('fe97:46fe:9871:bd38', 'eeed:d79c:2e3f:62e') """ s = "" if previous is None: d = "".join(map(chr, range(256))) for i in range(8): s += random.choice(d) previous = s s = inet_pton(socket.AF_INET6, "::"+ifaceid)[8:] + previous import md5 s = md5.new(s).digest() s1,s2 = s[:8],s[8:] s1 = chr(ord(s1[0]) | 0x04) + s1[1:] s1 = inet_ntop(socket.AF_INET6, "\xff"*8 + s1)[20:] s2 = inet_ntop(socket.AF_INET6, "\xff"*8 + s2)[20:] return (s1, s2)
Example #24
Source File: utils6.py From mptcp-abuse with GNU General Public License v2.0 | 5 votes |
def in6_getLocalUniquePrefix(): """ Returns a pseudo-randomly generated Local Unique prefix. Function follows recommandation of Section 3.2.2 of RFC 4193 for prefix generation. """ # Extracted from RFC 1305 (NTP) : # NTP timestamps are represented as a 64-bit unsigned fixed-point number, # in seconds relative to 0h on 1 January 1900. The integer part is in the # first 32 bits and the fraction part in the last 32 bits. # epoch = (1900, 1, 1, 0, 0, 0, 5, 1, 0) # x = time.time() # from time import gmtime, strftime, gmtime, mktime # delta = mktime(gmtime(0)) - mktime(self.epoch) # x = x-delta tod = time.time() # time of day. Will bother with epoch later i = int(tod) j = int((tod - i)*(2**32)) tod = struct.pack("!II", i,j) # TODO: Add some check regarding system address gathering rawmac = get_if_raw_hwaddr(conf.iface6)[1] mac = ":".join(map(lambda x: "%.02x" % ord(x), list(rawmac))) # construct modified EUI-64 ID eui64 = inet_pton(socket.AF_INET6, '::' + in6_mactoifaceid(mac))[8:] import sha globalid = sha.new(tod+eui64).digest()[:5] return inet_ntop(socket.AF_INET6, '\xfd' + globalid + '\x00'*10)
Example #25
Source File: util.py From mbuild with Apache License 2.0 | 5 votes |
def hash_string(s): """Compute a sha1 hash of a string and return the hex digest""" if check_python_version(2,5): m = hashlib.sha1() else: m = sha.new() m.update(s) d = m.hexdigest() return d
Example #26
Source File: cert.py From mptcp-abuse with GNU General Public License v2.0 | 5 votes |
def keyHash(self): m = self.modulus_hexdump res = [] i = 0 l = len(m) while i<l: # get a string version of modulus res.append(struct.pack("B", int(m[i:i+2], 16))) i += 2 return sha.new("".join(res)).digest()
Example #27
Source File: utils6.py From CVE-2016-6366 with MIT License | 5 votes |
def in6_getRandomizedIfaceId(ifaceid, previous=None): """ Implements the interface ID generation algorithm described in RFC 3041. The function takes the Modified EUI-64 interface identifier generated as described in RFC 4291 and an optional previous history value (the first element of the output of this function). If no previous interface identifier is provided, a random one is generated. The function returns a tuple containing the randomized interface identifier and the history value (for possible future use). Input and output values are provided in a "printable" format as depicted below. ex: >>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3') ('4c61:76ff:f46a:a5f3', 'd006:d540:db11:b092') >>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3', previous='d006:d540:db11:b092') ('fe97:46fe:9871:bd38', 'eeed:d79c:2e3f:62e') """ s = "" if previous is None: d = "".join(map(chr, range(256))) for i in range(8): s += random.choice(d) previous = s s = inet_pton(socket.AF_INET6, "::"+ifaceid)[8:] + previous import md5 s = md5.new(s).digest() s1,s2 = s[:8],s[8:] s1 = chr(ord(s1[0]) | 0x04) + s1[1:] s1 = inet_ntop(socket.AF_INET6, "\xff"*8 + s1)[20:] s2 = inet_ntop(socket.AF_INET6, "\xff"*8 + s2)[20:] return (s1, s2)
Example #28
Source File: utils6.py From CVE-2016-6366 with MIT License | 5 votes |
def in6_getLocalUniquePrefix(): """ Returns a pseudo-randomly generated Local Unique prefix. Function follows recommandation of Section 3.2.2 of RFC 4193 for prefix generation. """ # Extracted from RFC 1305 (NTP) : # NTP timestamps are represented as a 64-bit unsigned fixed-point number, # in seconds relative to 0h on 1 January 1900. The integer part is in the # first 32 bits and the fraction part in the last 32 bits. # epoch = (1900, 1, 1, 0, 0, 0, 5, 1, 0) # x = time.time() # from time import gmtime, strftime, gmtime, mktime # delta = mktime(gmtime(0)) - mktime(self.epoch) # x = x-delta tod = time.time() # time of day. Will bother with epoch later i = int(tod) j = int((tod - i)*(2**32)) tod = struct.pack("!II", i,j) # TODO: Add some check regarding system address gathering rawmac = get_if_raw_hwaddr(conf.iface6)[1] mac = ":".join(map(lambda x: "%.02x" % ord(x), list(rawmac))) # construct modified EUI-64 ID eui64 = inet_pton(socket.AF_INET6, '::' + in6_mactoifaceid(mac))[8:] import sha globalid = sha.new(tod+eui64).digest()[:5] return inet_ntop(socket.AF_INET6, '\xfd' + globalid + '\x00'*10)
Example #29
Source File: __init__.py From alfred-gmail with MIT License | 5 votes |
def response(self, response, content): """Gives us a chance to update with new nonces or such returned from the last authorized response. Over-rise this in sub-classes if necessary. Return TRUE is the request is to be retried, for example Digest may return stale=true. """ return False
Example #30
Source File: UcsBase.py From UcsPythonSDK with Apache License 2.0 | 5 votes |
def GetShaHash(str): """ Method returns the sha hash digest for a given string. """ import sha return sha.new(str).digest()