def test_box(self): msg = b'Are you suggesting coconuts migrate?' # run 1 vk1, sk1 = libnacl.crypto_sign_keypair() sig = libnacl.crypto_sign(msg, sk1) self.assertEqual(msg, sig[libnacl.crypto_sign_BYTES:]) sig_msg = libnacl.crypto_sign_open(sig, vk1) self.assertEqual(msg, sig_msg)
def testSimpleSigning(): sik = SigningKey(randombytes(32)) sigkey = sik._signing_key assert len(sigkey) == 64 # why is a signing key 64 bytes and not 32? verkey = sik.verify_key._key assert len(verkey) == 32 msg = b'1234' cmsg = crypto_sign(msg, sigkey) dmsg = crypto_sign_open(cmsg, verkey) assert msg == dmsg
def validateSignature(signature, key, data): try: verificationData = loads(data) original = libnacl.crypto_sign_open(base64.b64decode(signature), base64.b64decode(key)) if bytes(verificationData['message'], 'utf-8') == original: return True, 'Success' return False, SIGNATURE_MESSAGE_MISMATCH except ValueError: raise SignatureError(INVALID_SIGNATURE)
def verify(self, vk, msg): # type: (str, str) -> None """ Throws ValueError on failure :return: """ if vk != self.vk: raise ValueError("Mismatch verification key") expected_msg = libnacl.crypto_sign_open(self._signed_document, self.vk) if expected_msg != msg: raise ValueError("Mismatch message")
def verify(sig, msg, vk): """ Returns True if signature sig of message msg is verified with verification key vk Otherwise False All of sig, msg, vk are bytes """ try: result = libnacl.crypto_sign_open(sig + msg, vk) except Exception as ex: return False return (True if result else False)
def has_valid_signature(self) -> bool: """ Checks whether the event has a valid signature :return: bool """ signature_byte = base64_decode(self.signature.encode("UTF-8")) verify_key_byte = base64_decode(self.verify_key.encode("UTF-8")) try: message = crypto_sign_open(signature_byte, verify_key_byte) return message.decode('UTF-8') == self.body except ValueError: return False
def testSimpleSigningIsHasConsistentVerKey(): seed = randombytes(32) sik = SigningKey(seed) sigkey = sik._signing_key verkey = sik.verify_key._key msg = b'1234' cmsg = crypto_sign(msg, sigkey) dmsg = crypto_sign_open(cmsg, verkey) cmsg2 = crypto_sign(msg, sigkey) dmsg2 = crypto_sign_open(cmsg2, verkey) assert msg == dmsg assert dmsg == dmsg2 sik2 = SigningKey(seed) sigkey2 = sik2._signing_key verkey2 = sik2.verify_key._key assert sigkey2 == sigkey assert verkey2 == verkey
def _verify(self, data, sig): """Verify EdDSA signature.""" assert self.key[0] is not None assert len(self.key[0]) == libnacl.crypto_sign_PUBLICKEYBYTES # compute sha512 of data h = libnacl.crypto_hash_sha512(data) # construct signed message to use with crypto_sign_open smsg = sig + h # check message integrity try: return libnacl.crypto_sign_open(smsg, self.key[0]) == h except: # if an exception happens it's not return False
def verify(sig, msg, vk): """ Returns True if signature sig of message msg is verified with verification key vk Otherwise False :param sig: utf-8 encoded byte string signature :param msg: utf-8 encoded byte string message :param vk: utf-8 encoded byte string message :return: boolean True if valid False otherwise """ try: result = libnacl.crypto_sign_open(sig + msg, vk) except Exception as ex: return False return True if result else False
def fromBinary(binary, providerFP): if len(binary) != 124: raise Exception("Invalid binary certificate") certMagic = binary[0:4] esVersion = binary[4:6] protocolMinVersion = binary[6:8] if certMagic != DNSCryptResolverCertificate.DNSCRYPT_CERT_MAGIC or esVersion != DNSCryptResolverCertificate.DNSCRYPT_ES_VERSION or protocolMinVersion != DNSCryptResolverCertificate.DNSCRYPT_PROTOCOL_MIN_VERSION: raise Exception("Invalid binary certificate") orig = libnacl.crypto_sign_open(binary[8:124], providerFP) resolverPK = orig[0:32] clientMagic = orig[32:40] serial = struct.unpack_from("I", orig[40:44])[0] validFrom = struct.unpack_from("!I", orig[44:48])[0] validUntil = struct.unpack_from("!I", orig[48:52])[0] return DNSCryptResolverCertificate(serial, validFrom, validUntil, resolverPK, clientMagic)
def fromBinary(binary, providerFP): if len(binary) != 124: raise Exception("Invalid binary certificate") certMagic = binary[0:4] esVersion = binary[4:6] protocolMinVersion = binary[6:8] if certMagic != DNSCryptResolverCertificate.DNSCRYPT_CERT_MAGIC or esVersion != DNSCryptResolverCertificate.DNSCRYPT_ES_VERSION or protocolMinVersion != DNSCryptResolverCertificate.DNSCRYPT_PROTOCOL_MIN_VERSION: raise Exception("Invalid binary certificate") orig = libnacl.crypto_sign_open(binary[8:124], providerFP) resolverPK = orig[0:32] clientMagic = orig[32:40] serial = struct.unpack_from("I", orig[40:44]) validFrom = struct.unpack_from("!I", orig[44:48])[0]; validUntil = struct.unpack_from("!I", orig[48:52])[0]; return DNSCryptResolverCertificate(serial, validFrom, validUntil, resolverPK, clientMagic)
def verify(sig, msg, vk): """ Checks if signature sig of message msg is verifiable with verification key vk. Parameters: sig - Signature byte string msg - Message byte string vk - Verification key byte string Return: Boolean """ try: result = libnacl.crypto_sign_open(sig + msg.decode('utf-8').encode(), vk) except Exception as exception: return False return (True if result else False)
def verify(self, smessage, signature=None, encoder=encoding.RawEncoder): """ Verifies the signature of a signed message, returning the message if it has not been tampered with else raising :class:`~ValueError`. :param smessage: [:class:`bytes`] Either the original messaged or a signature and message concated together. :param signature: [:class:`bytes`] If an unsigned message is given for smessage then the detached signature must be provded. :param encoder: A class that is able to decode the secret message and signature. :rtype: :class:`bytes` """ if signature is not None: # If we were given the message and signature separately, combine # them. smessage = signature + smessage # Decode the signed message smessage = encoder.decode(smessage) return libnacl.crypto_sign_open(smessage, self._key)
def verify(self, msg): ''' Verify the message with tis key ''' return libnacl.crypto_sign_open(msg, self.vk)
def _verify(self, message: bytes, signature: bytes) -> bool: try: libnacl.crypto_sign_open(signature + message, self._pubkey) return True except ValueError: return False
def nacl_verify(m, s, pk): """ verify message m with signature s for public key pk """ if libnacl: libnacl.crypto_sign_open(s+m, pk)
def handleBinaryAPICall(self, a, sessionObject=None): # Process one incoming binary API message. If part of a sesson, using a sesson objert enables certain features. #Get the key hint k = a[:16] a = a[16:] # Get timestamp which is also the nonce remoteNodeID = a[:32] a = a[32:] #Verify that it is from who we think a = libnacl.crypto_sign_open(a, remoteNodeID) tbytes = a[:8] t = struct.unpack("<Q", tbytes)[0] # reject very old stuff if t < (time.time() - 3600) * 1000000: return {} # Get the data d = a[8:] #We can use either the real key, or the write password, which is only used for "centralized mode" if k == libnacl.crypto_generichash( self.syncKey.encode("utf8").ljust(32, b'\0'))[:16]: openingKey = self.syncKey writePassword = False elif k == libnacl.crypto_generichash( self.writePassword.encode("utf8").ljust(32, b'\0'))[:16]: openingKey = self.writePassword writePassword = True else: raise RuntimeError("Bad key hint") openingKey = openingKey.encode("utf8").ljust(32, b'\0') d = libnacl.crypto_secretbox_open(d, a[:8] + b'\0' * 16, openingKey) d = json.loads(d) r = {'records': []} if sessionObject and not sessionObject.alreadyDidInitialSync: cur = self.threadLocal.conn.cursor() cur.execute("SELECT lastArrival FROM peers WHERE peerID=?", (remoteNodeID, )) c = cur.fetchone() if c: c = c[0] else: c = 0 #No falsy value allowed, that would mean don't get new arrivals r['getNewArrivals'] = c or 1 sessionObject.alreadyDidInitialSync = True if "getNewArrivals" in d: cur = self.threadLocal.conn.cursor() #Avoid dumping way too much at once cur.execute( "SELECT json,signature FROM document WHERE json_extract(json,'$.arrival')>? LIMIT 100", (d['getNewArrivals'], )) #Declares that there are no records left out in between this time and the first time we actually send r['recordsStartFrom'] = d['getNewArrivals'] for i in cur: if not 'records' in r: r['records'] = [] print(i) r['records'].append([i[0], base64.b64encode(i[1]).decode()]) sessionObject.lastResyncFlushTime = max( sessionObject.lastResyncFlushTime, json.loads(i[0])['arrival']) if "records" in d and d['records']: for i in d['records']: #No need sig verify, if we are using PW verification. #Set a flag to request that the server send us any records that came after the last one, self.setDocument(i[0], None if writePassword else i[1]) r['getNewArrivals'] = i[0]['arrival'] #Set a flag saying that cur = self.threadLocal.conn.cursor() #If the recorded lastArrival is less than the incoming recordsStartFrom, it would mean that there is a gap in which records #That we don't know about could be hiding. Don't update the timestamp in that case, as the chain is broken. #We can still accept new records, but we will need to request everything all over again starting at the breakpoint to fix this. cur.execute( "UPDATE peers SET lastArrival=? WHERE peerID=? AND lastArrival !=? AND lastArrival>=?", (r['getNewArrivals'], remoteNodeID, r['getNewArrivals'], r.get("recordsStartFrom"))) return self.encodeMessage(r)