def __init__(self, pubkey=None, raw=False, flags=None, ctx=None): if USE_SECP: if flags == None: flags = secp256k1.FLAG_VERIFY self.obj = secp256k1.PublicKey(pubkey, raw, flags, ctx) else: if not raw: raise Exception("Non raw init unsupported") pubkey = pubkey[1:] x = int.from_bytes(pubkey[0:32], 'big') y = int.from_bytes(pubkey[32:], 'big') self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
def get_count(self): """ Get the number of datasets in the bootloader memory @return number of datasets in bootloader memory """ if not self._count: self._connect() data = self._query(GET_HEADER, 21) if self._checksum(data): if self._mode == CAN_MODE: frame_count = struct.unpack('<{}B'.format(len(data)), data)[5] (type, version, timestamp, frame_count, _, start_address, end_address, checksum) = struct.unpack( '<BB3sB{}s3s3sB'.format(frame_count), data) self._address_inc = 64 * frame_count self._can_frames = frame_count self._actual_size = 57 self._fetch_size = 4 + 61 * frame_count elif self._mode == DL_MODE: (_, device, start_address, end_address, checksum) = struct.unpack('<5sB3s3sB') self._address_inc = 64 self._can_frames = 1 self._actual_size = 57 self._fetch_size = 65 elif self._mode == DL2_MODE: (_, device, start_address, end_address, checksum) = struct.unpack('<5s2s3s3sB') self._address_inc = 128 self._can_frames = 1 self._actual_size = 113 self._fetch_size = 126 self._address_end = ((0x07FFFF // self._address_inc) * self._address_inc) # check address validity if (start_address != b'0xFFFFFF' and end_address != b'0xFFFFFF'): start_address = int.from_bytes(start_address, byteorder='little') end_address = int.from_bytes(end_address, byteorder='little') # fix addresses if end_address > start_address: # calculate count self._count = ((end_address - start_address) / self._address_inc) + 1 else: self._count = ( (self._address_end + start_address - end_address) / self._address_inc) self._address = end_address if self._count: self._count = int(self._count) return self._count else: raise ConnectionError('Could not retreive count')
def Bob_Step_2(self, Alice_IP, Bob_IP, Alice_message): b = secrets.randbits(2048) Rb = int(secrets.randbits(256)).to_bytes(32, byteorder=u'big') Gb = int(pow(self.g, b, self.m)).to_bytes(256, byteorder=u'big') Alice = Alice_IP.encode() Bob = Bob_IP.encode() Ra = Alice_message[:32] Ga = Alice_message[32:] Ga_int = int.from_bytes(Ga, byteorder=u'big') Gab = int(pow(Ga_int, b, self.m)).to_bytes(256, byteorder=u'big') Concat_H = Alice + Bob + Ra + Rb + Ga + Gb + Gab hashed_key = sha256() hashed_key.update(Concat_H) self.H_Bob = hashed_key.digest() Decrypted_Sb = self.H_Bob + Bob Decrypted_Sb_int = int.from_bytes(Decrypted_Sb, byteorder=u'big') Sb_int_Sign = pow(Decrypted_Sb_int, RSA_Bob.dBob, RSA_Bob.nBob) Sb = int(Sb_int_Sign).to_bytes(512, byteorder=u'big') message2 = Rb + Gb + Sb print "\n b = " print b del b print "\n Ra (in byte) = " print Ra print "\n Rb (in byte )= " print Rb hashed_key = sha256() hashed_key.update(Gab) self.hashed_key = hashed_key.digest() print "\nBob new hashed key" print binascii.hexlify(bytearray(self.hashed_key)) return message2
def decrypt(encrypted_payload: str, passphrase: str): decoded_payload = decode_base64(encrypted_payload) version = decoded_payload[0] if isinstance(version, str): version = ord(version) if version != 1: raise ValueError("Unsupported export format version.") salt = decoded_payload[1:17] iv = int.from_bytes(decoded_payload[17:33], byteorder="big") count = int.from_bytes(decoded_payload[33:37], byteorder="big") encrypted_data = decoded_payload[37:-32] expected_hmac = decoded_payload[-32:] derived_key = PBKDF2(passphrase, salt, 64, count, prf) # type: ignore aes_key = derived_key[:32] hmac_key = derived_key[32:64] hmac = HMAC.new(hmac_key, decoded_payload[:-32], SHA256).digest() if hmac != expected_hmac: raise ValueError("HMAC check failed for encrypted payload.") ctr = Counter.new(128, initial_value=iv) cipher = AES.new(aes_key, AES.MODE_CTR, counter=ctr) return cipher.decrypt(encrypted_data)
def borromean_verify(pubkeys, rings_size, ring_count, msg, sig): tell("*** BORROMEAN VERIFY ***") curve = Curve.get_curve('secp256k1') G = curve.generator order = curve.order e0 = sig[0] s = sig[1] sha256_e0 = hashlib.sha256() r0 = 0 for i in range(0, ring_count): tell("\nstep2-3 / ring %d" % i) e_ij = borromean_hash(m, e0, i, 0) for j in range(0, rings_size[i]): tell("\n step2-3 / ring %d / sec %d" % (i, j)) e_ij = int.from_bytes(e_ij, 'big') s_ij = int.from_bytes(s[r0 + j], 'big') tell(" index : %d" % (r0 + j)) tell(" pubkeys[]: %s" % pubkeys[r0 + j]) tell(" s[] : %x" % s_ij) tell(" e_ij : %x" % e_ij) sG_eP = s_ij * G + e_ij * pubkeys[r0 + j].W tell(" sG_eP :\n %s" % sG_eP) e_ij = point_to_bytes(sG_eP) if j != rings_size[i] - 1: e_ij = borromean_hash(m, e_ij, i, j + 1) else: tell(" e_ij0 : %s" % h(e_ij)) sha256_e0.update(e_ij) r0 += rings_size[i] sha256_e0.update(m) e0x = sha256_e0.digest() return e0 == e0x
def verify(self, msg, sig, pu_key): """ Verifies a message signature. Args: msg (bytes) : the message hash to verify the signature sig (bytes) : signature to verify pu_key (ecpy.keys.ECPublicKey): key to use for verifying """ curve = pu_key.curve n = pu_key.curve.order G = pu_key.curve.generator size = curve.size >> 3 r, s = decode_sig(sig, self.fmt) if (r == None or r > (pow(2, size * 8) - 1) or s == 0 or s > n - 1): return False hasher = self._hasher() if self.option == "ISO": sG = s * G rW = r * pu_key.W Q = sG - rW xQ = Q.x.to_bytes(size, 'big') yQ = Q.y.to_bytes(size, 'big') hasher.update(xQ + yQ + msg) v = hasher.digest() v = int.from_bytes(v, 'big') elif self.option == "ISOx": sG = s * G rW = r * pu_key.W Q = sG - rW xQ = Q.x.to_bytes(size, 'big') hasher.update(xQ + msg) v = hasher.digest() v = int.from_bytes(v, 'big') elif self.option == "BSI": sG = s * G rW = r * pu_key.W Q = sG + rW xQ = (Q.x).to_bytes(size, 'big') hasher.update(msg + xQ) v = hasher.digest() v = int.from_bytes(v, 'big') elif self.option == "LIBSECP": rb = r.to_bytes(size, 'big') hasher.update(rb + msg) h = hasher.digest() h = int.from_bytes(h, 'big') if h == 0 or h > n: return 0 sG = s * G hW = h * pu_key.W R = sG + hW v = R.x % n return v == r
def str_encode(src): i = 0 c = '' for byte in src.encode('ascii'): c += chr( int.from_bytes([byte]) ^ int.from_bytes(['Encrypt'.encode('ascii')[i]])) i = (i + 1) % 7 return base64.b64encode(c).decode('utf-8')
def __init__(self, pubkey=None, raw=False): if USE_SECP: self.obj = secp256k1.PublicKey(pubkey, raw) else: if not raw: raise Exception("Non raw init unsupported") pubkey = pubkey[1:] x = int.from_bytes(pubkey[0:32], 'big') y = int.from_bytes(pubkey[32:], 'big') self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
def from_der(der): """Return HexSig object from a DER signature string.""" sig = bytearray(binascii.unhexlify(der)) sig_len = sig[1] + 2 r_offset, r_len = 4, sig[3] s_offset, s_len = 4 + r_len + 2, sig[4 + r_len + 1] if (sig[0] != 0x30 or sig_len != r_len + s_len + 6 or sig[s_offset - 2] != 0x02): return HexSig(b"%064x" % 0, b"%064x" % 0) return HexSig( b"%064x" % int.from_bytes(sig[r_offset:r_offset + r_len], "big"), b"%064x" % int.from_bytes(sig[s_offset:s_offset + s_len], "big"))
def _do_sign(self,msg,pv_key): curve = pv_key.curve B = curve.generator n = curve.order size = curve._coord_size() a, A, prefix = EDDSA._get_materials(pv_key, self._hasher, self._hash_len) eA = curve.encode_point(A) #compute R hasher = self._hasher() if curve.name =='Ed448': hasher.update(b'SigEd448\x00\x00') hasher.update(prefix) hasher.update(msg) r = hasher.digest(self._hash_len) elif curve.name =='Ed25519': hasher.update(prefix) hasher.update(msg) r = hasher.digest() else : assert False, '%s not supported'%curve.name r = int.from_bytes(r,'little') r = r % n R = r*B eR = curve.encode_point(R) #compute S hasher = self._hasher() if curve.name =='Ed448': hasher.update(b'SigEd448\x00\x00') hasher.update(eR) hasher.update(eA) hasher.update(msg) H_eR_eA_m = hasher.digest(self._hash_len) elif curve.name =='Ed25519': hasher.update(eR) hasher.update(eA) hasher.update(msg) H_eR_eA_m = hasher.digest() else: assert False, '%s not supported'%curve.name i = int.from_bytes(H_eR_eA_m, 'little') S = (r + i*a)%n #S = S.to_bytes(size,'little') #return eR+S eR = int.from_bytes(eR,'little') sig = encode_sig(eR,S,self.fmt,size) return sig
def _do_sign(self, msg, pv_key, k): if (pv_key.curve == None): raise ECPyException('private key haz no curve') curve = pv_key.curve n = curve.order G = curve.generator size = curve.size >> 3 Q = G * k hasher = self._hasher() if self.option == "ISO": xQ = (Q.x).to_bytes(size, 'big') yQ = (Q.y).to_bytes(size, 'big') hasher.update(xQ + yQ + msg) r = hasher.digest() r = int.from_bytes(r, 'big') s = (k + r * pv_key.d) % n if r == 0 or s == 0: return None elif self.option == "ISOx": xQ = (Q.x).to_bytes(size, 'big') hasher.update(xQ + msg) r = hasher.digest() r = int.from_bytes(r, 'big') s = (k + r * pv_key.d) % n if r == 0 or s == 0: return None elif self.option == "BSI": xQ = Q.x.to_bytes(size, 'big') hasher.update(msg + xQ) r = hasher.digest() r = int.from_bytes(r, 'big') s = (k - r * pv_key.d) % n if r == 0 or s == 0: return None elif self.option == "LIBSECP": if Q.y & 1: k = n - k Q = G * k r = (Q.x % n).to_bytes(size, 'big') hasher.update(r + msg) h = hasher.digest() h = int.from_bytes(h, 'big') r = Q.x % n s = (k - h * pv_key.d) % n return encode_sig(r, s, self.fmt)
def verify(self, msg, sig, pu_key): """ Verifies a message signature. Args: msg (bytes) : the message to verify the signature sig (bytes) : signature to verify pu_key (ecpy.keys.ECPublicKey): key to use for verifying """ curve = pu_key.curve n = curve.order size = curve.size >> 3 #eR = sig[0:size] #S = int.from_bytes(sig[size:],'little') eR, S = decode_sig(sig, self.fmt) #left eR = eR.to_bytes(size, 'little') R = curve.decode_point(eR) hasher = self._hasher() eA = curve.encode_point(pu_key.W) hasher.update(eR + eA + msg) h = hasher.digest() h = int.from_bytes(h, 'little') h = h % n A = pu_key.W left = R + h * A #right right = S * curve.generator return left == right
def verify(self, msg, sig, pu_key): """ Verifies a message signature. Args: msg (bytes) : the message hash to verify the signature sig (bytes) : signature to verify pu_key (ecpy.keys.ECPublicKey): key to use for verifying """ curve = pu_key.curve n = curve.order G = curve.generator r, s = decode_sig(sig, self.fmt) if (r == None or s == None or r == 0 or r >= n or s == 0 or s >= n): return False h = int.from_bytes(msg, 'big') if n.bit_length() < h.bit_length(): # h is the 'n.bit_length()' leftmost bits of the received h value, # leading zeroes included (if any). hbyteslen = (h.bit_length() + 7) // 8 h = int(format(h, f'0{8*hbyteslen}b')[:n.bit_length()], 2) c = pow(s, n - 2, n) u1 = (h * c) % n u2 = (r * c) % n u1G = u1 * G u2Q = u2 * pu_key.W GQ = u1G + u2Q if GQ.is_infinity: return False x = GQ.x % n return x == r
def _do_sign(self, msg, pv_key, k): if (pv_key.curve == None): raise ECPyException('private key haz no curve') curve = pv_key.curve n = curve.order G = curve.generator k = k % n msg = int.from_bytes(msg, 'big') Q = G * k kinv = pow(k, n - 2, n) r = Q.x % n if r == 0: return None s = (kinv * (msg + pv_key.d * r)) % n if s == 0: return None sig = encode_sig(r, s, self.fmt) # r = r.to_bytes((r.bit_length()+7)//8, 'big') # s = s.to_bytes((s.bit_length()+7)//8, 'big') # if (r[0] & 0x80) == 0x80 : # r = b'\0'+r # if (s[0] & 0x80) == 0x80 : # s = b'\0'+s # sig = (b'\x30'+int((len(r)+len(s)+4)).to_bytes(1,'big') + # b'\x02'+int(len(r)).to_bytes(1,'big') + r + # b'\x02'+int(len(s)).to_bytes(1,'big') + s ) return sig
def tweak_add(self, scalar): if USE_SECP: self.obj = self.obj.tweak_add(scalar) else: scalar = int.from_bytes(scalar, 'big') privKey = ECPrivateKey(scalar, CURVE_SECP256K1) self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W)
def seed_gen(n=261): global STATE STATE = list( map( int, bin(int.from_bytes(os.urandom(n // 8 + 1), byteorder="little"))[2:][:n]))
def rfc6979_k(msg, secret0, V=None): """Generate a deterministic rfc6967 integer.""" hasher = hashlib.sha256 if (V is None): h1 = msg hsize = len(h1) V = b'\x01' * hsize K = b'\x00' * hsize x = secret0 K = hmac.new(K, V + b'\x00' + x + h1, hasher).digest() V = hmac.new(K, V, hasher).digest() K = hmac.new(K, V + b'\x01' + x + h1, hasher).digest() V = hmac.new(K, V, hasher).digest() while True: T = b'' p_blen = p.bit_length() while len(T) * 8 < p_blen: V = hmac.new(K, V, hasher).digest() T = T + V k = int.from_bytes(T, "big") k_blen = k.bit_length() if k_blen > p_blen: k = k >> (k_blen - p_blen) if k > 0 and k < (p - 1): return k, V K = hmac.new(K, V + b'\x00', hasher).digest() V = hmac.new(K, V, hasher).digest()
def decryptTurnoverCounter(self, receipt, encTurnoverCounter, key): iv = utils.sha256( receipt.registerId.encode("utf-8") + receipt.receiptId.encode("utf-8"))[0:16] decCtr = utils.aes256ctr(iv, key, encTurnoverCounter) return int.from_bytes(decCtr, byteorder='big', signed=True)
def encrypt(data: bytes, passphrase: str, count: int = 100000): # 128 bits salt salt = Random.new().read(16) # 512 bits derived key derived_key = PBKDF2(passphrase, salt, 64, count, prf) # type: ignore aes_key = derived_key[:32] hmac_key = derived_key[32:64] # 128 bits IV, which will be the initial value initial iv = int.from_bytes(Random.new().read(16), byteorder="big") # Set bit 63 to 0, as specified iv &= ~(1 << 63) ctr = Counter.new(128, initial_value=iv) cipher = AES.new(aes_key, AES.MODE_CTR, counter=ctr) encrypted_data = cipher.encrypt(data) payload = b"".join(( bytes([1]), # Version salt, int.to_bytes(iv, length=16, byteorder="big"), # 32 bits big-endian round count int.to_bytes(count, length=4, byteorder="big"), encrypted_data, )) hmac = HMAC.new(hmac_key, payload, SHA256).digest() return encode_base64(payload + hmac)
def verify(self,msg,sig,pu_key): """ Verifies a message signature. Args: msg (bytes) : the message hash to verify the signature sig (bytes) : signature to verify pu_key (ecpy.keys.ECPublicKey): key to use for verifying """ curve = pu_key.curve n = curve.order G = curve.generator r,s = decode_sig(sig, self.fmt) if (r == None or s == None or r == 0 or r >= n or s == 0 or s >= n ) : return False h = int.from_bytes(msg,'big') c = pow(s, n-2, n) u1 = (h*c)%n u2 = (r*c)%n u1G = u1*G u2Q = u2*pu_key.W GQ = u1G+u2Q if GQ.is_infinity: return False x = GQ.x % n return x == r
def tweak_add(self, scalar): if USE_SECP: self.obj = self.obj.tweak_add(scalar) else: scalar = int.from_bytes(scalar, 'big') privKey = ECPrivateKey(scalar, CURVE_SECP256K1) self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W)
def serialize(trace_id): parent_ctx = SpanContext(trace_id=trace_id, span_id=int.from_bytes(os.urandom(8)), parent_id=0, flags=1) parent = Span(context=parent_ctx, operation_name='x', tracer=tracer) span = tracer.start_span(operation_name='x', references=child_of(parent.context)) span.finish() _marshall_span(span)
def calcChecksum(self, inData): """calculates checksum used for protocol, expects a byte array""" checksum = 0 for inByte in inData: if type(inData) is list: inByte = int.from_bytes(inByte, byteorder='big') checksum = (((checksum & 0xFF) >> 1) + ((checksum & 0x1) << 7) + inByte) & 0xff return checksum
def _do_sign(self, msg, pv_key): curve = pv_key.curve B = curve.generator n = curve.order size = curve.size >> 3 k = pv_key.d.to_bytes(size, 'big') hasher = self._hasher() hasher.update(k) h = hasher.digest() #retrieve encoded pub key a = bytearray(h[size - 1::-1]) a[0] &= ~0x40 a[0] |= 0x40 a[31] &= 0xF8 a = bytes(a) a = int.from_bytes(a, 'big') A = a * B eA = curve.encode_point(A) #OK #compute R hasher = self._hasher() hasher.update(h[size:] + msg) r = hasher.digest() r = int.from_bytes(r, 'little') r = r % n R = r * B eR = curve.encode_point(R) #compute S hasher = self._hasher() hasher.update(eR + eA + msg) H_eR_eA_m = hasher.digest() i = int.from_bytes(H_eR_eA_m, 'little') S = (r + i * a) % n #S = S.to_bytes(size,'little') #return eR+S eR = int.from_bytes(eR, 'little') sig = encode_sig(eR, S, self.fmt, size) return sig
def _get_materials(pv_key, hasher=hashlib.sha512, hash_len=None): """ Returns the internal private scalar a(int), the public point A(ECPoint) = a.B and the signature prefix h(bytes) The hash parameter shall be the same as the one used for signing and verifying. Args: hasher (hashlib): callable constructor returning an object with update(), digest() interface. Example: hashlib.sha256, hashlib.sha512... pv_key (ecpy.keys.ECPrivateKey): key to use for signing Returns: ECPrivateKey : internal private key """ curve = pv_key.curve B = curve.generator n = curve.order size = curve._coord_size() k = pv_key.d.to_bytes(size, 'big') hasher = hasher() hasher.update(k) if hash_len: h = hasher.digest(hash_len) else: h = hasher.digest() #retrieve encoded pub key if curve.name == 'Ed25519': a = bytearray(h[:32]) h = h[32:] a[0] &= 0xF8 a[31] = (a[31] & 0x7F) | 0x40 elif curve.name == 'Ed448': a = bytearray(h[:57]) h = h[57:] a[0] &= 0xFC a[56] = 0 a[55] |= 0x80 elif curve.name == 'Ed521': a = bytearray(h[:66]) h = h[66:] a[0] &= 0xFC a[65] = 0 a[65] |= 0x80 else: assert False, '%s not supported' % curve.name a = bytes(a) a = int.from_bytes(a, 'little') A = a * B return a, A, h
def bits2int(bs): """ bs(bytes): binary value """ i = int.from_bytes(bs, 'big') blen = len(bs) * 8 qlen = q.bit_length() if blen > qlen: i = i >> (blen - qlen) return i
def ecdh(self, scalar): if USE_SECP: return self.obj.ecdh(scalar) else: scalar = int.from_bytes(scalar, 'big') point = self.obj.W * scalar # libsecp256k1 style secret out = b"\x03" if ((point.y & 1) != 0) else b"\x02" out += point.x.to_bytes(32, 'big') hash = hashlib.sha256() hash.update(out) return hash.digest()
def ecdh(self, scalar): if USE_SECP: return self.obj.ecdh(scalar) else: scalar = int.from_bytes(scalar, 'big') point = self.obj.W * scalar # libsecp256k1 style secret out = b"\x03" if ((point.y & 1) != 0) else b"\x02" out += point.x.to_bytes(32, 'big') hash = hashlib.sha256() hash.update(out) return hash.digest()
def verify(self, msg, sig, rings): """ Verifies a message signature. Args: msg (bytes) : the message hash to verify the signature sig (bytes) : signature to verify rings (key.ECPublicKey): key to use for verifying Returns: boolean : True if signature is verified, False else """ #shortcuts G = self._curve.generator #set up locals ring_count = len(rings) pubkeys = [] rsizes = [] for r in rings: pubkeys = pubkeys + r rsizes.append(len(r)) #verify e0 = sig[0] s = sig[1] sha256_e0 = self._hash() r0 = 0 for i in range(0, ring_count): e_ij = _borromean_hash(m, e0, i, 0, self._hash) for j in range(0, rsizes[i]): e_ij = int.from_bytes(e_ij, 'big') s_ij = int.from_bytes(s[r0 + j], 'big') sG_eP = s_ij * G + e_ij * pubkeys[r0 + j].W e_ij = _point_to_bytes(sG_eP) if j != rsizes[i] - 1: e_ij = _borromean_hash(m, e_ij, i, j + 1, self._hash) else: sha256_e0.update(e_ij) r0 += rsizes[i] sha256_e0.update(m) e0x = sha256_e0.digest() return e0 == e0x
def decode_point(self, eP): """ Decodes a point P according to *RFC7748*. Args: eP (bytes) : encoded point curve (Curve) : curve on witch point is Returns: Point : decoded point """ x = bytearray(eP) x[len(x) - 1] &= ~0x80 x = int.from_bytes(x, 'little') return Point(x, None, self)
def Bob_Step_4(self, Alice_IP, Alice_message): #Bob computes Alice H and compares it to his own. Return signal if true or false #Fix message message = self.Decryption_Byte(Alice_message, self.hashed_key) Alice_Address_Length = len(Alice_IP) Sa = message[Alice_Address_Length:] Sa_int = int.from_bytes(Sa, byteorder=u'big') Decrypted_Sa_int = pow(Sa_int, RSA_Bob.eAlice, RSA_Bob.nAlice) Decrypted_Sa = int(Decrypted_Sa_int).to_bytes(512 + Alice_Address_Length, byteorder=u'big') H = Decrypted_Sa[512 - 32:512] return self.H_Bob == H
def Alice_Step_3(self, Alice_IP, Bob_IP, Bob_message): Rb = Bob_message[:32] Gb = Bob_message[32:256 + 32] Sb = Bob_message[256 + 32:] Bob_Address_Length = len(Bob_IP) Sb_int_Sign = int.from_bytes(Sb, byteorder=u'big') Decrypted_Sb_int = pow(Sb_int_Sign, RSA_Alice.eBob, RSA_Alice.nBob) Decrypted_Sb = int(Decrypted_Sb_int).to_bytes(512 + Bob_Address_Length, byteorder=u'big') H = Decrypted_Sb[512 - 32:512] Bob = Decrypted_Sb[512:] Gb_int = int.from_bytes(Gb, byteorder=u'big') Gab = int(pow(Gb_int, self.a, self.m)).to_bytes(256, byteorder=u'big') Alice = Alice_IP.encode() Concat_H = Alice + Bob + self.Ra + Rb + self.Ga + Gb + Gab hashed_key = sha256() hashed_key.update(Concat_H) My_H = hashed_key.digest() check = H == My_H Decrypted_Sa = My_H + Alice Decrypted_Sa_int = int.from_bytes(Decrypted_Sa, byteorder=u'big') Sa_int_Sign = pow(Decrypted_Sa_int, RSA_Alice.dAlice, RSA_Alice.nAlice) Sa = int(Sa_int_Sign).to_bytes(512, byteorder=u'big') hashed_key = sha256() hashed_key.update(Gab) message3 = Alice + Sa print "\n a = " print self.a del self.a print "\n Ra (in byte) = " print self.Ra print "\n Rb (in byte) = " print Rb self.hashed_key = hashed_key.digest() print "\nAlice new hashed key" print binascii.hexlify(bytearray(self.hashed_key)) ##### ENCRYPT THIS MESSAGE USING K ##### message3 = self.Encryption_Byte(message3, self.hashed_key, self.iv) return message3, check
def _do_sign(self, msg, pv_key, k, canonical=False): if (pv_key.curve == None): raise ECPyException('private key haz no curve') curve = pv_key.curve n = curve.order G = curve.generator k = k % n # if "msg (hash) bit length" is greater that the "domain bit length", # we only consider the left most "domain bit length" of message. msg_len = len(msg) * 8 msg = int.from_bytes(msg, 'big') if msg_len > curve.size: msg = msg >> (msg_len - curve.size) if n.bit_length() < msg.bit_length(): # msg is the 'n.bit_length()' leftmost bits of the received msg, # leading zeroes included (if any). mbyteslen = (msg.bit_length() + 7) // 8 msg = int(format(msg, f'0{8*mbyteslen}b')[:n.bit_length()], 2) Q = G * k if Q.is_infinity: return None kinv = pow(k, n - 2, n) r = Q.x % n if r == 0: return None s = (kinv * (msg + pv_key.d * r)) % n if s == 0: return None if canonical and (s > (n // 2)): s = n - s sig = encode_sig(r, s, self.fmt) # r = r.to_bytes((r.bit_length()+7)//8, 'big') # s = s.to_bytes((s.bit_length()+7)//8, 'big') # if (r[0] & 0x80) == 0x80 : # r = b'\0'+r # if (s[0] & 0x80) == 0x80 : # s = b'\0'+s # sig = (b'\x30'+int((len(r)+len(s)+4)).to_bytes(1,'big') + # b'\x02'+int(len(r)).to_bytes(1,'big') + r + # b'\x02'+int(len(s)).to_bytes(1,'big') + s ) return sig
def __init__(self, privkey=None, raw=True, flags=None, ctx=None): if USE_SECP: if flags == None: flags = secp256k1.ALL_FLAGS self.obj = secp256k1.PrivateKey(privkey, raw, flags, ctx) self.pubkey = self.obj.pubkey else: if not raw: raise Exception("Non raw init unsupported") if privkey == None: privkey = ecpy.ecrand.rnd(CURVE_SECP256K1.order) else: privkey = int.from_bytes(privkey,'big') self.obj = ECPrivateKey(privkey, CURVE_SECP256K1) pubkey = self.obj.get_public_key().W out = b"\x04" out += pubkey.x.to_bytes(32, 'big') out += pubkey.y.to_bytes(32, 'big') self.pubkey = PublicKey(out, raw=True)
def scp_derive_key(self, ecdh_secret, keyindex): retry = 0 # di = sha256(i || retrycounter || ecdh secret) while True: sha256 = hashlib.new('sha256') sha256.update(struct.pack(">IB", keyindex, retry)) sha256.update(ecdh_secret) # compare di with order CURVE_SECP256K1 = Curve.get_curve('secp256k1') if int.from_bytes(sha256.digest(), 'big') < CURVE_SECP256K1.order: break #regenerate a new di satisfying order upper bound retry+=1 # Pi = di*G privkey = PrivateKey(bytes(sha256.digest())) pubkey = bytearray(privkey.pubkey.serialize(compressed=False)) # ki = sha256(Pi) sha256 = hashlib.new('sha256') sha256.update(pubkey) #print ("Key " + str (keyindex) + ": " + sha256.hexdigest()) return sha256.digest()
def _send_command(self, command, reply_length=0, output_as_bytes=False, reply_is_string=False): """Send a command and return status and reply Args: command (bytes): The command to send e.g. b'\xFF\xCD' to clear the screen reply_length (int): The length of the expected reply i.e. WITHOUT an acknowledge. output_as_bytes (bool): Return bytes instead of int reply_is_string (bool): Overrides the `reply_length` and read the reply length from the reply itself. Applicaple only to variable length strings. Returns: bytes or int: If a return value is requested (with reply_length) a int will be returned formed from the bytes. If output_as_bytes is set, then the raw bytes are returned Raises: PicasoException: If the command fails or if the reply does not have the requested length """ if self.debug: print("Repr of command to send", repr(command)) self.serial.write(command) # Special case for baud rate change command_as_bytes = bytes(command) if command_as_bytes[0: 2] == b'\x00\x26': baudrate_index = int.from_bytes(command_as_bytes[2:], byteorder='big') baudrate = {v: k for k, v in BAUD_RATES.items()}[baudrate_index] sleep(1) self.serial.baudrate = baudrate while True: if self.serial.inWaiting() > 0: ack = self.serial.read(1) # For some reason, it doesn't seem to return ACK, but it has done it, # which is why we return after getting a byte back break sleep(0.1) return # First check if it succeded acknowledge_as_byte = self.serial.read(1) if acknowledge_as_byte != b'\x06': message = 'The command \'{}\' failed with code: {}'.format(command, acknowledge_as_byte) raise PicasoException(message, exception_type='failed') # The read reply is any if reply_is_string: reply_length = 0 string_length_as_bytes = self.serial.read(2) string_length = int.from_bytes(string_length_as_bytes, byteorder='big') reply_raw = self.serial.read(string_length) else: if reply_length > 0: reply_raw = self.serial.read(reply_length) else: reply_raw = b'' # Make sure there is nothing waiting if self.debug: in_waiting = self.serial.inWaiting() if in_waiting != 0: message = 'Wrong reply length. There are still {0} bytes '\ 'left waiting on the serial port'.format(in_waiting) raise PicasoException(message, exception_type='bytes_still_waiting') # Return appropriate value if reply_length > 0: if len(reply_raw) != reply_length: message = 'The reply length {0} bytes, did not match the '\ 'requested reply length {1} bytes'.format( len(reply_raw) - 1, reply_length) raise PicasoException(message, exception_type='unexpected_reply') reply = None if output_as_bytes or reply_is_string: reply = reply_raw else: reply = int.from_bytes(reply_raw, byteorder='big') return reply
def seed_gen(n=261): global STATE STATE = list(map(int, bin(int.from_bytes(os.urandom(n // 8 + 1), byteorder="little"))[2:][:n]))