def generateKeyAndSendNewInterest(self, probeTokenData): """ """ pib = self.keyChain.getPib() try: identity = pib.getIdentity(self.identityName) self.key = self.keyChain.createKey(identity) except Exception as e: identity = self.keyChain.createIdentityV2(self.identityName) self.key = identity.getDefaultKey() cert = CertificateV2() cert.setName( Name(self.key.getName()).append("cert-request").appendVersion( int(time.time()))) cert.getMetaInfo().setType(ContentType.KEY) cert.getMetaInfo().setFreshnessPeriod(24 * 3600) cert.setContent(self.key.getPublicKey()) signingInfo = SigningInfo(self.key) now = Common.getNowMilliseconds() signingInfo.setValidityPeriod( ValidityPeriod(now, now + 24 * 3600 * 1000.0)) self.keyChain.sign(cert, signingInfo) #cert = self.keyChain.selfSign(self.key) # Does not work because validity period is greater than certserver default interestName = Name(self.caPrefix).append("CA").append("_NEW") newInterest = Interest(interestName) newInterest.setMustBeFresh(True) newInterest.setCanBePrefix(False) ecdhPub = "{}\n".format(self.ecdh.getBase64PubKey()) ecdhCertReq = "{}\n".format( b64encode(cert.wireEncode().toBytes()).decode('utf-8')) probeToken = "{}\n".format( b64encode(probeTokenData.wireEncode().toBytes()).decode('utf-8')) jsonDump = json.dumps( { "ecdh-pub": ecdhPub, "cert-request": ecdhCertReq, "probe-token": probeToken }, indent=4) print(jsonDump) newInterest.setApplicationParameters(jsonDump) newInterest.appendParametersDigestToName() self.keyChain.sign(newInterest, SigningInfo(self.key)) print(newInterest.getName()) self.face.expressInterest(newInterest, self.onNewData, self.onTimeout)
def main(): face = Face() keychain = KeyChain() face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName()) running = True # The following line doesn't work sometimes # interest = Interest("/icear-server/calc") interest = Interest(Name("/icear-server/calc")) param_msg = SegmentParameterMessage() param_msg.segment_parameter.name.component.append( bytes("example-data", "utf-8")) param_msg.segment_parameter.start_frame = 2 param_msg.segment_parameter.end_frame = 3 op = param_msg.segment_parameter.operations.components.add() op.model = bytes("deeplab", "utf-8") op.flags = 0 op = param_msg.segment_parameter.operations.components.add() op.model = bytes("la_muse", "utf-8") op.flags = 0 interest.name.append(ProtobufTlv.encode(param_msg)) interest.mustBeFresh = True interest.interestLifetimeMilliseconds = 4000.0 interest.setCanBePrefix(True) def on_data(_, data): # type: (Interest, Data) -> None nonlocal running print(data.name.toUri()) print(data.content.toBytes()) running = False def on_timeout(_): nonlocal running print("Timeout") running = False def on_nack(_, nack): # type: (Interest, NetworkNack) -> None nonlocal running print("NACK") print(nack.getReason()) running = False face.expressInterest(interest, on_data, on_timeout, on_nack) while running: face.processEvents() time.sleep(0.01) face.shutdown()
def sendProbeInterest(self): probeInterest = Interest( Name(self.caPrefix).append("CA").append("_PROBE")) probeInterest.setMustBeFresh(True) probeInterest.setCanBePrefix(False) probeInterest.setApplicationParameters( json.dumps({"email": "*****@*****.**"}, indent=4)) probeInterest.appendParametersDigestToName() print("Expressing interest: {}".format(probeInterest.getName())) self.face.expressInterest(probeInterest, self.onProbeData, self.onTimeout)
def onNewData(self, interest, data): """ !! Again \n in public key?? Got data: { "ecdh-pub": "Aqxofe3QdsAfgbtS8TMxv31oudNKoSV307ci5gNXm88h\n", "salt": "12935684137560555161", "request-id": "14275252044236690531", "status": "0", "challenges": [ { "challenge-id": "Email" } ] } 1. Verify data 2. Derive shared secret """ content = data.getContent() print("Got data: ", content) if not VerificationHelpers.verifyDataSignature(data, self.anchor): print("Cannot verify signature from: {}".format(self.caPrefix)) else: print("Successfully verified data with hard-coded certificate") contentJson = json.loads(content.__str__()) peerKeyBase64 = contentJson['ecdh-pub'] self.status = contentJson['status'] self.requestId = contentJson['request-id'] self.challenges = contentJson['challenges'] print(peerKeyBase64) serverPubKey = ec.EllipticCurvePublicKey.from_encoded_point( ec.SECP256R1(), b64decode(peerKeyBase64)) shared_key = self.ecdh.private_key.exchange(ec.ECDH(), serverPubKey) derived_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=contentJson['salt'].encode(), info=b'handshake data', backend=default_backend()).derive(shared_key) self.ecdh.derived_key = derived_key print(shared_key) for t in shared_key: print(t) challengeInterestName = Name( self.caPrefix).append("CA").append("_CHALLENGE").append( self.requestId) challengeInterest = Interest(challengeInterestName) challengeInterest.setMustBeFresh(True) challengeInterest.setCanBePrefix(False) # Encrypt the interest parameters challengeJson = json.dumps( { "selected-challenge": "Email", "email": "*****@*****.**" }, indent=4) raw = self.pad(challengeJson, 16) print("raw", raw) iv = Random.new().read(AES.block_size) #cipher = AES.new(self.ecdh.derived_key, AES.MODE_CBC, iv) cipher = AES.new(shared_key, AES.MODE_CBC, iv) print(iv) xx = cipher.encrypt(raw) print(cipher.decrypt(xx)) print("Printing iv:") for t in iv: print(t) encoder = TlvEncoder(256) saveLength = len(encoder) encoder.writeBlobTlv(632, iv) encoder.writeBlobTlv(630, cipher.encrypt(raw)) #encoder.writeTypeAndLength(36, len(encoder) - saveLength) challengeInterest.setApplicationParameters(Blob(encoder.getOutput())) challengeInterest.appendParametersDigestToName() self.keyChain.sign(challengeInterest, SigningInfo(self.key)) with open('foobar.tlv', 'wb') as f: f.write(challengeInterest.wireEncode().buf()) self.face.expressInterest(challengeInterest, self.onChallengeData, self.onTimeout)
def test_matches_data(self): interest = Interest(Name("/A")) interest.setCanBePrefix(False) # Check violating CanBePrefix. data = Data(Name("/A/D")) self.assertEqual(interest.matchesData(data), False) # Check violating PublisherPublicKeyLocator. data3 = Data(data) signature3 = Sha256WithRsaSignature() signature3.getKeyLocator().setType(KeyLocatorType.KEYNAME) signature3.getKeyLocator().setKeyName(Name("/G")) data3.setSignature(signature3) self.assertEqual(interest.matchesData(data3), False) # Do not test keylocator in interest packet #interest3 = Interest(interest) #interest3.getKeyLocator().setType(KeyLocatorType.KEYNAME) #interest3.getKeyLocator().setKeyName(Name("/G")) #self.assertEqual(interest3.matchesData(data3), True) data4 = Data(data) data4.setSignature(DigestSha256Signature()) self.assertEqual(interest.matchesData(data4), False) # Do not test keylocator in interest packet #interest4 = Interest(interest) #interest4.setKeyLocator(KeyLocator()) #self.assertEqual(interest4.matchesData(data4), True) # Check violating Exclude. data5 = Data(data) data5.setName(Name("/A/J")) self.assertEqual(interest.matchesData(data5), False) # Check violating Name. data6 = Data(data) data6.setName(Name("/H/I")) self.assertEqual(interest.matchesData(data6), False) data7 = Data(data) data7.setName(Name("/A/B")) interest7 = Interest( Name( "/A/B/sha256digest=" + "54008e240a7eea2714a161dfddf0dd6ced223b3856e9da96792151e180f3b128" )) self.assertEqual(interest7.matchesData(data7), True) # Check violating the implicit digest. interest7b = Interest( Name("/A/B/%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00" + "%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00")) self.assertEqual(interest7b.matchesData(data7), False) # Check excluding the implicit digest. interest8 = Interest(Name("/A/B")) interest8.getExclude().appendComponent(interest7.getName().get(2)) self.assertEqual(interest8.matchesData(data7), False)