Python Crypto.Hash.SHA.new() Examples
The following are 30
code examples of Crypto.Hash.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
Crypto.Hash.SHA
, or try the search function
.
Example #1
Source File: kex_group1.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _parse_kexdh_reply(self, m): # client mode host_key = m.get_string() self.f = m.get_mpint() if (self.f < 1) or (self.f > P - 1): raise SSHException('Server kex "f" is out of range') sig = m.get_string() K = pow(self.f, self.x, P) # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add(self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init) hm.add_string(host_key) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) self.transport._set_K_H(K, SHA.new(str(hm)).digest()) self.transport._verify_key(host_key, sig) self.transport._activate_outbound()
Example #2
Source File: _DSA.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=bord(hash1[i])^bord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise RuntimeError('Bad q value generated')
Example #3
Source File: randpool.py From python-for-android with Apache License 2.0 | 6 votes |
def get_bytes (self, N): """get_bytes(N:int) : string Return N bytes of random data. """ s='' i, pool = self._getPos, self._randpool h=self._hash.new() dsize = self._hash.digest_size num = N while num > 0: h.update( self._randpool[i:i+dsize] ) s = s + h.digest() num = num - dsize i = (i + dsize) % self.bytes if i<dsize: self.stir() i=self._getPos self._getPos = i self._updateEntropyEstimate(- 8*N) return s[:N]
Example #4
Source File: main.py From cryptovenom with GNU General Public License v3.0 | 6 votes |
def signMsg(text, imported_key): seq2 = asn1.DerSequence() data = '\n'.join(imported_key.strip().split('\n')[1:-1]).decode('base64') seq2.decode(data) p, q, g, y, x = seq2[1:] key2 = DSA.construct((y, g, p, q, x)) k1 = random.StrongRandom().randint(1,key2.q-1) h = SHA.new(text).digest() sig = key2.sign(h, k1) return sig
Example #5
Source File: DSA.py From python-for-android with Apache License 2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=ord(hash1[i])^ord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159) < q < pow(2,160): return S, q raise error('Bad q value generated')
Example #6
Source File: DSA.py From python-for-android with Apache License 2.0 | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=ord(hash1[i])^ord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise error, 'Bad q value generated'
Example #7
Source File: randpool.py From python-for-android with Apache License 2.0 | 6 votes |
def stir (self, s = ''): """stir(s:string) Mix up the randomness pool. This will call add_event() twice, but out of paranoia the entropy attribute will not be increased. The optional 's' parameter is a string that will be hashed with the randomness pool. """ entropy=self.entropy # Save inital entropy value self.add_event() # Loop over the randomness pool: hash its contents # along with a counter, and add the resulting digest # back into the pool. for i in range(self.bytes / self._hash.digest_size): h = self._hash.new(self._randpool) h.update(str(self.__counter) + str(i) + str(self._addPos) + s) self._addBytes( h.digest() ) self.__counter = (self.__counter + 1) & 0xFFFFffff self._addPos, self._getPos = 0, self._hash.digest_size self.add_event() # Restore the old value of the entropy. self.entropy=entropy
Example #8
Source File: randpool.py From python-for-android with Apache License 2.0 | 6 votes |
def stir (self, s = ''): """stir(s:string) Mix up the randomness pool. This will call add_event() twice, but out of paranoia the entropy attribute will not be increased. The optional 's' parameter is a string that will be hashed with the randomness pool. """ entropy=self.entropy # Save inital entropy value self.add_event() # Loop over the randomness pool: hash its contents # along with a counter, and add the resulting digest # back into the pool. for i in range(self.bytes / self._hash.digest_size): h = self._hash.new(self._randpool) h.update(str(self.__counter) + str(i) + str(self._addPos) + s) self._addBytes( h.digest() ) self.__counter = (self.__counter + 1) & 0xFFFFffffL self._addPos, self._getPos = 0, self._hash.digest_size self.add_event() # Restore the old value of the entropy. self.entropy=entropy
Example #9
Source File: randpool.py From python-for-android with Apache License 2.0 | 6 votes |
def get_bytes (self, N): """get_bytes(N:int) : string Return N bytes of random data. """ s='' i, pool = self._getPos, self._randpool h=self._hash.new() dsize = self._hash.digest_size num = N while num > 0: h.update( self._randpool[i:i+dsize] ) s = s + h.digest() num = num - dsize i = (i + dsize) % self.bytes if i<dsize: self.stir() i=self._getPos self._getPos = i self._updateEntropyEstimate(- 8*N) return s[:N]
Example #10
Source File: main.py From cryptovenom with GNU General Public License v3.0 | 6 votes |
def verifyMsg(text, imported_key, sig): seq2 = asn1.DerSequence() data = '\n'.join(imported_key.strip().split('\n')[1:-1]).decode('base64') seq2.decode(data) p, q, g, y, x = seq2[1:] key2 = DSA.construct((y, g, p, q, x)) k1 = random.StrongRandom().randint(1,key2.q-1) h = SHA.new(text).digest() a = key2.verify(h, sig) return a
Example #11
Source File: kex_gex.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _parse_kexdh_gex_reply(self, m): host_key = m.get_string() self.f = m.get_mpint() sig = m.get_string() if (self.f < 1) or (self.f > self.p - 1): raise SSHException('Server kex "f" is out of range') K = pow(self.f, self.x, self.p) # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K) hm = Message() hm.add(self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init, host_key) if not self.old_style: hm.add_int(self.min_bits) hm.add_int(self.preferred_bits) if not self.old_style: hm.add_int(self.max_bits) hm.add_mpint(self.p) hm.add_mpint(self.g) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) self.transport._set_K_H(K, SHA.new(str(hm)).digest()) self.transport._verify_key(host_key, sig) self.transport._activate_outbound()
Example #12
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey} """ rsa = RSA.generate(bits, rng.read, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
Example #13
Source File: kex_group1.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _parse_kexdh_reply(self, m): # client mode host_key = m.get_string() self.f = m.get_mpint() if (self.f < 1) or (self.f > P - 1): raise SSHException('Server kex "f" is out of range') sig = m.get_string() K = pow(self.f, self.x, P) # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K) hm = Message() hm.add(self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init) hm.add_string(host_key) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) self.transport._set_K_H(K, SHA.new(str(hm)).digest()) self.transport._verify_key(host_key, sig) self.transport._activate_outbound()
Example #14
Source File: dsskey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey} """ dsa = DSA.generate(bits, rng.read, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
Example #15
Source File: dsskey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def verify_ssh_sig(self, data, msg): if len(str(msg)) == 40: # spies.com bug: signature has no header sig = str(msg) else: kind = msg.get_string() if kind != 'ssh-dss': return 0 sig = msg.get_string() # pull out (r, s) which are NOT encoded as mpints sigR = util.inflate_long(sig[:20], 1) sigS = util.inflate_long(sig[20:], 1) sigM = util.inflate_long(SHA.new(data).digest(), 1) dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q))) return dss.verify(sigM, (sigR, sigS))
Example #16
Source File: transport.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _parse_newkeys(self, m): self._log(DEBUG, 'Switch to new keys ...') self._activate_inbound() # can also free a bunch of stuff here self.local_kex_init = self.remote_kex_init = None self.K = None self.kex_engine = None if self.server_mode and (self.auth_handler is None): # create auth handler for server mode self.auth_handler = AuthHandler(self) if not self.initial_kex_done: # this was the first key exchange self.initial_kex_done = True # send an event? if self.completion_event != None: self.completion_event.set() # it's now okay to send data again (if this was a re-key) if not self.packetizer.need_rekey(): self.in_kex = False self.clear_to_send_lock.acquire() try: self.clear_to_send.set() finally: self.clear_to_send_lock.release() return
Example #17
Source File: transport.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _get_cipher(self, name, key, iv): if name not in self._cipher_info: raise SSHException('Unknown client cipher ' + name) if name in ('arcfour128', 'arcfour256'): # arcfour cipher cipher = self._cipher_info[name]['class'].new(key) # as per RFC 4345, the first 1536 bytes of keystream # generated by the cipher MUST be discarded cipher.encrypt(" " * 1536) return cipher elif name.endswith("-ctr"): # CTR modes, we need a counter counter = Counter.new(nbits=self._cipher_info[name]['block-size'] * 8, initial_value=util.inflate_long(iv, True)) return self._cipher_info[name]['class'].new(key, self._cipher_info[name]['mode'], iv, counter) else: return self._cipher_info[name]['class'].new(key, self._cipher_info[name]['mode'], iv)
Example #18
Source File: transport.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _compute_key(self, id, nbytes): "id is 'A' - 'F' for the various keys used by ssh" m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_byte(id) m.add_bytes(self.session_id) out = sofar = SHA.new(str(m)).digest() while len(out) < nbytes: m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_bytes(sofar) digest = SHA.new(str(m)).digest() out += digest sofar += digest return out[:nbytes]
Example #19
Source File: transport.py From imoocc with GNU General Public License v2.0 | 6 votes |
def renegotiate_keys(self): """ Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you want. Negotiating new keys causes a pause in traffic both ways as the two sides swap keys and do computations. This method returns when the session has switched to new keys. @raise SSHException: if the key renegotiation failed (which causes the session to end) """ self.completion_event = threading.Event() self._send_kex_init() while True: self.completion_event.wait(0.1) if not self.active: e = self.get_exception() if e is not None: raise e raise SSHException('Negotiation failed.') if self.completion_event.isSet(): break return
Example #20
Source File: transport.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _compute_key(self, id, nbytes): "id is 'A' - 'F' for the various keys used by ssh" m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_byte(id) m.add_bytes(self.session_id) out = sofar = SHA.new(str(m)).digest() while len(out) < nbytes: m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_bytes(sofar) digest = SHA.new(str(m)).digest() out += digest sofar += digest return out[:nbytes]
Example #21
Source File: transport.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _get_cipher(self, name, key, iv): if name not in self._cipher_info: raise SSHException('Unknown client cipher ' + name) if name in ('arcfour128', 'arcfour256'): # arcfour cipher cipher = self._cipher_info[name]['class'].new(key) # as per RFC 4345, the first 1536 bytes of keystream # generated by the cipher MUST be discarded cipher.encrypt(" " * 1536) return cipher elif name.endswith("-ctr"): # CTR modes, we need a counter counter = Counter.new(nbits=self._cipher_info[name]['block-size'] * 8, initial_value=util.inflate_long(iv, True)) return self._cipher_info[name]['class'].new(key, self._cipher_info[name]['mode'], iv, counter) else: return self._cipher_info[name]['class'].new(key, self._cipher_info[name]['mode'], iv)
Example #22
Source File: dsskey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def sign_ssh_data(self, rng, data): digest = SHA.new(data).digest() dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q), long(self.x))) # generate a suitable k qsize = len(util.deflate_long(self.q, 0)) while True: k = util.inflate_long(rng.read(qsize), 1) if (k > 2) and (k < self.q): break r, s = dss.sign(util.inflate_long(digest, 1), k) m = Message() m.add_string('ssh-dss') # apparently, in rare cases, r or s may be shorter than 20 bytes! rstr = util.deflate_long(r, 0) sstr = util.deflate_long(s, 0) if len(rstr) < 20: rstr = '\x00' * (20 - len(rstr)) + rstr if len(sstr) < 20: sstr = '\x00' * (20 - len(sstr)) + sstr m.add_string(rstr + sstr) return m
Example #23
Source File: dsskey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def verify_ssh_sig(self, data, msg): if len(str(msg)) == 40: # spies.com bug: signature has no header sig = str(msg) else: kind = msg.get_string() if kind != 'ssh-dss': return 0 sig = msg.get_string() # pull out (r, s) which are NOT encoded as mpints sigR = util.inflate_long(sig[:20], 1) sigS = util.inflate_long(sig[20:], 1) sigM = util.inflate_long(SHA.new(data).digest(), 1) dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q))) return dss.verify(sigM, (sigR, sigS))
Example #24
Source File: dsskey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{DSSKey} """ dsa = DSA.generate(bits, rng.read, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key
Example #25
Source File: kex_gex.py From imoocc with GNU General Public License v2.0 | 6 votes |
def _parse_kexdh_gex_reply(self, m): host_key = m.get_string() self.f = m.get_mpint() sig = m.get_string() if (self.f < 1) or (self.f > self.p - 1): raise SSHException('Server kex "f" is out of range') K = pow(self.f, self.x, self.p) # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K) hm = Message() hm.add(self.transport.local_version, self.transport.remote_version, self.transport.local_kex_init, self.transport.remote_kex_init, host_key) if not self.old_style: hm.add_int(self.min_bits) hm.add_int(self.preferred_bits) if not self.old_style: hm.add_int(self.max_bits) hm.add_mpint(self.p) hm.add_mpint(self.g) hm.add_mpint(self.e) hm.add_mpint(self.f) hm.add_mpint(K) self.transport._set_K_H(K, SHA.new(str(hm)).digest()) self.transport._verify_key(host_key, sig) self.transport._activate_outbound()
Example #26
Source File: rsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(bits, progress_func=None): """ Generate a new private RSA key. This factory function can be used to generate a new host key or authentication key. @param bits: number of bits the generated key should be. @type bits: int @param progress_func: an optional function to call at key points in key generation (used by C{pyCrypto.PublicKey}). @type progress_func: function @return: new private key @rtype: L{RSAKey} """ rsa = RSA.generate(bits, rng.read, progress_func) key = RSAKey(vals=(rsa.e, rsa.n)) key.d = rsa.d key.p = rsa.p key.q = rsa.q return key
Example #27
Source File: _DSA.py From earthengine with MIT License | 6 votes |
def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=bord(hash1[i])^bord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise RuntimeError('Bad q value generated')
Example #28
Source File: qNEW.py From python-for-android with Apache License 2.0 | 5 votes |
def publickey(self): """Return a new key object containing only the public information.""" return construct((self.p, self.q, self.g, self.y))
Example #29
Source File: transport.py From imoocc with GNU General Public License v2.0 | 5 votes |
def open_session(self): """ Request a new channel to the server, of type C{"session"}. This is just an alias for C{open_channel('session')}. @return: a new L{Channel} @rtype: L{Channel} @raise SSHException: if the request is rejected or the session ends prematurely """ return self.open_channel('session')
Example #30
Source File: randpool.py From python-for-android with Apache License 2.0 | 5 votes |
def _measureTickSize(self): # _measureTickSize() tries to estimate a rough average of the # resolution of time that you can see from Python. It does # this by measuring the time 100 times, computing the delay # between measurements, and taking the median of the resulting # list. (We also hash all the times and add them to the pool) interval = [None] * 100 h = self._hash.new(`(id(self),id(interval))`) # Compute 100 differences t=time.time() h.update(`t`) i = 0 j = 0 while i < 100: t2=time.time() h.update(`(i,j,t2)`) j += 1 delta=int((t2-t)*1e6) if delta: interval[i] = delta i += 1 t=t2 # Take the median of the array of intervals interval.sort() self._ticksize=interval[len(interval)/2] h.update(`(interval,self._ticksize)`) # mix in the measurement times and wash the random pool self.stir(h.digest())