Exemple #1
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:", initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
        #initInterest = interest.getName()
        d = Data(interest.getName().append(self.deviceComponent))
        try:
            print "start to set data's content"

            currentString = ','.join(currentList)
            d.setContent("songList of " + self.device + ":" + currentString +
                         "\n")
            self.face.registerPrefix(self.changePrefix, self.onInterest,
                                     self.onRegisterFailed)

        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
        print d.getName().toUri()
        print d.getContent()

        self.stop()
        '''print"remove register"
Exemple #2
0
        def after_fetched(data: Data):
            nonlocal recv_window, b_array, seq_to_bytes_unordered
            """
            Reassemble data packets in sequence.
            """
            if not isinstance(data, Data):
                return
            try:
                seq = int(str(data.getName()).split('/')[-1])
                logging.info('seq: {}'.format(seq))
            except ValueError:
                logging.warning('Sequence number decoding error')
                return

            # Temporarily store out-of-order packets
            if seq <= recv_window:
                return
            elif seq == recv_window + 1:
                b_array.extend(data.getContent().toBytes())
                logging.info('saved packet: seq {}'.format(seq))
                recv_window += 1
                while recv_window + 1 in seq_to_bytes_unordered:
                    b_array.extend(seq_to_bytes_unordered[recv_window + 1])
                    seq_to_bytes_unordered.pop(recv_window + 1)
                    logging.info('saved packet: seq {}'.format(recv_window +
                                                               1))
                    recv_window += 1
            else:
                logging.info(
                    'Received out of order packet: seq {}'.format(seq))
                seq_to_bytes_unordered[seq] = data.getContent().toBytes()
Exemple #3
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	try:
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)	



	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()

	self.loop.close()
     
        self.face.shutdown()
        self.face = None
Exemple #4
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:", initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
        #initInterest = interest.getName()
        d = Data(interest.getName().append(self.deviceComponent))

        try:
            if (initInterest == self.prefix):

                print "start to set data's content"

                currentString = ','.join(currentList)
                d.setContent("songList of " + self.device + ":" +
                             currentString + "\n")

            else:
                self.excludeDevice = initInterest.get(prefix.size())
                print "excludeDevice", self.excludeDevice.toEscapedString()
                if (self.excludeDevice != self.deviceComponent):
                    print "start to set data's content"

                    currentString = ','.join(currentList)
                    d.setContent("songList of " + self.device + ":" +
                                 currentString + "\n")
                else:

                    print "remove register"
                    self.face.removeRegisteredPrefix(registeredPrefixId)
                    time.sleep(30)
                    #sleep 30s which means user cannot update the song list twice within 1 minutes
                    print "register again"
                    self.face.registerPrefix(self.prefix, self.onInterest,
                                             self.onRegisterFailed)

        except KeyboardInterrupt:
            print "key interrupt"
            sys.exit(1)
        except Exception as e:
            print e
            d.setContent("Bad command\n")
        finally:
            self.keychain.sign(d, self.certificateName)

        encodedData = d.wireEncode()
        transport.send(encodedData.toBuffer())
        print d.getName().toUri()
        print d.getContent()
Exemple #5
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
	print "received interest"
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
        #d = Data(interest.getName().getPrefix(prefix.size()+1))
        #self.excludeDevice = interest.getName().get(prefix.size())
	#initInterest = interest.getName()
	d = Data(interest.getName().append(self.deviceComponent))
	
		  
        try:
	    if(initInterest == self.prefix):
	    
		print "start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent("songList of " +self.device+":"+currentString+ "\n")
		
		
            else:
		self.excludeDevice = initInterest.get(prefix.size())
		print "excludeDevice",self.excludeDevice.toEscapedString()
		if(self.excludeDevice != self.deviceComponent):
			print "start to set data's content"
                
			currentString = ','.join(currentList)
			d.setContent("songList of " +self.device+":"+currentString+ "\n")
		else:

			print"remove register"
                	self.face.removeRegisteredPrefix(registeredPrefixId)
                	time.sleep(30)
                	#sleep 30s which means user cannot update the song list twice within 1 minutes
			print"register again"
                	self.face.registerPrefix(self.prefix, self.onInterest, self.onRegisterFailed)
	    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)

	encodedData = d.wireEncode()
	transport.send(encodedData.toBuffer())
	print d.getName().toUri()
	print d.getContent()
Exemple #6
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        initInterest = Name(interest.getName())
        print "interest name:",initInterest.toUri()
	d = Data(interest.getName().append(self.deviceComponent))
	
		  
        try:
	    if(initInterest == self.listPrefix):
	    
		print "initial db,start to set data's content"
                
		currentString = ','.join(currentList)
		d.setContent(currentString)
		encodedData = d.wireEncode()
		transport.send(encodedData.toBuffer())
		print d.getName().toUri()
		print d.getContent()
		
		
		
            else:
		self.excludeDevice = initInterest.get(self.listPrefix.size())
		excDevice = self.excludeDevice.toEscapedString()
		if(excDevice != str("exc")+self.device):
			print "not init db,start to set data's content"
                
			currentString = ','.join(currentList)
			d.setContent(currentString)
			encodedData = d.wireEncode()
			transport.send(encodedData.toBuffer())
			print d.getName().toUri()
			print d.getContent()
			
		else:
			
			print"controller has exclude me, I have to remove register!!!!!!!"
                	self.face.removeRegisteredPrefix(registeredPrefixId)
			print"register again"
                	self.face.registerPrefix(self.listPrefix,self.onInterest,self.onRegisterFailed)
    

	except KeyboardInterrupt:
		print "key interrupt"
		sys.exit(1)
	except Exception as e:
		print e
		d.setContent("Bad command\n")
	finally:
		self.keychain.sign(d,self.certificateName)
Exemple #7
0
    def process_temp_data(self, data: Data):
        """
        Parse the received Data packet containing temperature info
        """
        content_bytes = data.getContent().toBytes()
        temperature = int.from_bytes(content_bytes, byteorder='little')
        logging.info('Received {}: {} degrees'.format(str(data.getName()), temperature))
        print('Received {}: {} degrees'.format(str(data.getName()), temperature))

        self.data_frame = self.data_frame.append({
            'Time': datetime.now().strftime('%Y-%m-%d-%H'),
            'DistrictCode': random.randint(0, 5),
            'TypeCode': random.randint(0, 5),
            'Popularity': temperature
        }, ignore_index=True)

        # If collected a batch of data, perform incremental learning on it
        print('len: {}'.format(len(self.data_frame)))
        if len(self.data_frame) >= self.batch_size + 24:
            csv_name = str(int(time.time())) + '.csv'
            csv_path = os.path.join('data', csv_name)
            self.data_frame.to_csv(csv_path, index=False)
            self.data_frame = self.data_frame[-24:]
            
            logging.info('Start incremental training on batch {}'.format(csv_name))

            self.learner.load_data(csv_path)
            self.learner.train_once()
Exemple #8
0
    def testEmptyContent(self):
        state = PSyncState()

        # Simulate getting a buffer of content from a segment fetcher.
        data = Data()
        data.setContent(state.wireEncode())

        state2 = PSyncState(data.getContent())
        self.assertEqual(0, len(state2.getContent()))
Exemple #9
0
    def test_encode_decode(self):
        data = Data()
        data.wireDecode(codedData2)
        data.setContent(data.getContent())
        encoding = data.wireEncode()

        reDecodedData = Data()
        reDecodedData.wireDecode(encoding)
        self.assertEqual(dumpData(reDecodedData), initialDump2, 'Re-decoded data does not match original dump')
Exemple #10
0
    def test_encode_decode(self):
        data = Data()
        data.wireDecode(codedData)
        data.setContent(data.getContent())
        encoding = data.wireEncode()

        reDecodedData = Data()
        reDecodedData.wireDecode(encoding)
        self.assertEqual(dumpData(reDecodedData), initialDump, 'Re-decoded data does not match original dump')
Exemple #11
0
    def test_content_symmetric_encrypt(self):
        for input in encryptorAesTestInputs:
            data = Data()
            Encryptor.encryptData(
              data, input.plainText, input.keyName, input.key, input.encryptParams)

            self.assertTrue(data.getName().equals(Name("/FOR").append(input.keyName)),
                            input.testName)

            self.assertTrue(input.encryptedContent.equals(data.getContent()),
                            input.testName)

            content = EncryptedContent()
            content.wireDecode(data.getContent())
            decryptedOutput = AesAlgorithm.decrypt(
              input.key, content.getPayload(), input.encryptParams)

            self.assertTrue(input.plainText.equals(decryptedOutput), input.testName)
    def contentCacheAddEntityData(self, name, entityInfo):
        content = self._serializer.serialize(entityInfo)
        data = Data(Name(name))

        data.setContent(content)

        data.getMetaInfo().setFreshnessPeriod(self._entityDataFreshnessPeriod)
        self._keyChain.sign(data, self._certificateName)
        self._memoryContentCache.add(data)
        print "added entity to cache: " + data.getName().toUri() + "; " + data.getContent().toRawStr()
 def decode_cmd_response_blob(data: Data) -> RepoCommandResponseMessage:
     """
     Decode the command response and return a RepoCommandResponseMessage object.
     Throw RuntimeError on decoding failure.
     """
     response = RepoCommandResponseMessage()
     response_blob = data.getContent()
     try:
         ProtobufTlv.decode(response, response_blob)
     except RuntimeError as exc:
         raise exc
     return response
Exemple #14
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)
        dt = datetime.now()

        if (interestName.toUri() == "/vanet-ndn/iklan1"):
            data.setContent(
                "\nLakukan Pengisian Pulsa Telkomsel sekarang juga \nDapatkan pulsa 5000 dan kelipatan untuk setiap pembelian pulsa 10000 dan kelipatannya\n"
            )  #bagian ini bisa diganti dengan informasi dari sensor
            global iklan1
            iklan1 = data.getContent()
        elif (interestName.toUri() == "/vanet-ndn/iklan2"):
            data.setContent(
                "\nLakukan Pengisian Kuota Indosat sekarang juga! \nDapatkan kemudahan dalam berinternet digenggamanmu\n"
            )  #bagian ini bisa diganti dengan informasi dari sensor
            global iklan2
            iklan2 = data.getContent()
        elif (interestName.toUri() == "/vanet-ndn/iklan3"):
            data.setContent(
                "\nIngin memiliki Smartphone baru? \nDapatkan smartphone impian mu dengan XL\nCek xl.co.id untuk penawaran menarik\n"
            )  #bagian ini bisa diganti dengan informasi dari sensor
            global iklan3
            iklan3 = data.getContent()

        hourMilliseconds = 30
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        transport.send(data.wireEncode().toBuffer())

        print("Replied to: %s - Time: %s " % (interestName.toUri(), dt))
        print(
            "==================================================================\n"
        )
        pass
Exemple #15
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(
        0,
        keyName.size() - 1).append("KEY").append(
            keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA,
                           Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                           DEFAULT_RSA_PUBLIC_KEY_DER,
                                           DEFAULT_RSA_PRIVATE_KEY_DER)

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnVerifyFailed("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData, certificateName)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnVerifyFailed("Freshly-signed Data"))
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnVerifyFailed("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData, certificateName)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnVerifyFailed("Freshly-signed Data"))
Exemple #17
0
    def test_content_asymmetric_encrypt_small(self):
        for input in encryptorRsaTestInputs:
            rawContent = Blob(
                bytearray([
                    0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc,
                    0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x63, 0x6f, 0x6e, 0x74,
                    0x65, 0x6e, 0x74, 0x73
                ]), False)

            data = Data()
            rsaParams = RsaKeyParams(1024)

            keyName = Name("test")

            decryptKey = RsaAlgorithm.generateKey(rsaParams)
            encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

            eKey = encryptKey.getKeyBits()
            dKey = decryptKey.getKeyBits()

            encryptParams = EncryptParams(input.type)

            Encryptor.encryptData(data, rawContent, keyName, eKey,
                                  encryptParams)

            self.assertTrue(
                data.getName().equals(Name("/FOR").append(keyName)),
                input.testName)

            extractContent = EncryptedContent()
            extractContent.wireDecode(data.getContent())
            self.assertTrue(
                keyName.equals(extractContent.getKeyLocator().getKeyName()),
                input.testName)
            self.assertEqual(extractContent.getInitialVector().size(), 0,
                             input.testName)
            self.assertEqual(extractContent.getAlgorithmType(), input.type,
                             input.testName)

            recovered = extractContent.getPayload()
            decrypted = RsaAlgorithm.decrypt(dKey, recovered, encryptParams)
            self.assertTrue(rawContent.equals(decrypted), input.testName)
Exemple #18
0
    def testEncodeDecode(self):
        state = PSyncState()
        state.addContent(Name("test1"))
        state.addContent(Name("test2"))

        # Simulate getting a buffer of content from a segment fetcher.
        data = Data()
        encoding = state.wireEncode()
        expectedEncoding = [
          0x80, 0x12, # PSyncContent
            0x07, 0x07, 0x08, 0x05, 0x74, 0x65, 0x73, 0x74, 0x31, # Name = "/test1"
            0x07, 0x07, 0x08, 0x05, 0x74, 0x65, 0x73, 0x74, 0x32  # Name = "/test2"
        ]
        self.assertTrue(encoding.equals(Blob(expectedEncoding)))
        data.setContent(encoding)

        receivedState = PSyncState()
        receivedState.wireDecode(data.getContent())

        self.assertTrue(state.getContent() == receivedState.getContent())
Exemple #19
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(
      pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnValidationFailed("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnValidationFailed("Freshly-signed Data"))
Exemple #20
0
    def test_content_asymmetric_encrypt_small(self):
        for input in encryptorRsaTestInputs:
            rawContent = Blob(bytearray([
                0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
                0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
                0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73
              ]), False)

            data = Data()
            rsaParams = RsaKeyParams(1024)

            keyName = Name("test")

            decryptKey = RsaAlgorithm.generateKey(rsaParams)
            encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

            eKey = encryptKey.getKeyBits()
            dKey = decryptKey.getKeyBits()

            encryptParams = EncryptParams(input.type)

            Encryptor.encryptData(data, rawContent, keyName, eKey, encryptParams)

            self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)),
                            input.testName)

            extractContent = EncryptedContent()
            extractContent.wireDecode(data.getContent())
            self.assertTrue(
              keyName.equals(extractContent.getKeyLocator().getKeyName()),
              input.testName)
            self.assertEqual(
              extractContent.getInitialVector().size(), 0, input.testName)
            self.assertEqual(
              extractContent.getAlgorithmType(), input.type, input.testName)

            recovered = extractContent.getPayload()
            decrypted = RsaAlgorithm.decrypt(dKey, recovered, encryptParams)
            self.assertTrue(rawContent.equals(decrypted), input.testName)
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"),
      makeFailureCallback("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
      makeFailureCallback("Freshly-signed Data"))
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"),
                       makeFailureCallback("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
                       makeFailureCallback("Freshly-signed Data"))
Exemple #23
0
    def calculateAggregation(self, dataType, aggregationType, childrenList, startTime, interval, publishingPrefix, repeat = False):
        doCalc = True
        dataList = []

        # TODO: an intermediate node cannot produce raw data for now
        if len(childrenList.keys()) != 0:
            for childName in childrenList.keys():
                dataDictKey = self.getDataDictKey(startTime, (startTime + interval), childName)
                if dataDictKey in self._dataQueue[dataType + aggregationType]._dataDict:
                    data = self._dataQueue[dataType + aggregationType]._dataDict[dataDictKey]
                    dataList.append(float(data.getContent().toRawStr()))
                else:
                    #print('Child ' + childName + ' has not replied yet')
                    doCalc = False
                    break
        else:
            for inst in self._dataQueue[dataType]._dataDict.keys():
                if int(inst) >= startTime and int(inst) < startTime + interval:
                    dataList.append(self._dataQueue[dataType]._dataDict[inst])
        if doCalc:
            content = self._aggregation.getAggregation(aggregationType, dataList)
            if content:
                publishData = Data(Name(publishingPrefix).append(str(startTime)).append(str(startTime + interval)))
                publishData.setContent(str(content))
                publishData.getMetaInfo().setFreshnessPeriod(DEFAULT_DATA_LIFETIME)
                self._keyChain.sign(publishData, self._certificateName)
                self._memoryContentCache.add(publishData)
                for childName in childrenList.keys():
                    dataDictKey = self.getDataDictKey(startTime, (startTime + interval), childName)
                    if dataDictKey in self._dataQueue[dataType + aggregationType]._dataDict:
                        del self._dataQueue[dataType + aggregationType]._dataDict[dataDictKey]
                if __debug__:
                    print("Produced: " + publishData.getName().toUri() + "; " + publishData.getContent().toRawStr())

        # repetition of this function only happens for raw data producer, otherwise calculateAggregation is called by each onData
        if repeat:
            self._loop.call_later(interval, self.calculateAggregation, dataType, aggregationType, childrenList, startTime + interval, interval, publishingPrefix, repeat)
        return
Exemple #24
0
    def test_content_asymmetric_encrypt_large(self):
        for input in encryptorRsaTestInputs:
            largeContent = Blob(bytearray([
                0x73, 0x5a, 0xbd, 0x47, 0x0c, 0xfe, 0xf8, 0x7d,
                0x2e, 0x17, 0xaa, 0x11, 0x6f, 0x23, 0xc5, 0x10,
                0x23, 0x36, 0x88, 0xc4, 0x2a, 0x0f, 0x9a, 0x72,
                0x54, 0x31, 0xa8, 0xb3, 0x51, 0x18, 0x9f, 0x0e,
                0x1b, 0x93, 0x62, 0xd9, 0xc4, 0xf5, 0xf4, 0x3d,
                0x61, 0x9a, 0xca, 0x05, 0x65, 0x6b, 0xc6, 0x41,
                0xf9, 0xd5, 0x1c, 0x67, 0xc1, 0xd0, 0xd5, 0x6f,
                0x7b, 0x70, 0xb8, 0x8f, 0xdb, 0x19, 0x68, 0x7c,
                0xe0, 0x2d, 0x04, 0x49, 0xa9, 0xa2, 0x77, 0x4e,
                0xfc, 0x60, 0x0d, 0x7c, 0x1b, 0x93, 0x6c, 0xd2,
                0x61, 0xc4, 0x6b, 0x01, 0xe9, 0x12, 0x28, 0x6d,
                0xf5, 0x78, 0xe9, 0x99, 0x0b, 0x9c, 0x4f, 0x90,
                0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f,
                0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48,
                0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5,
                0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde,
                0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9,
                0x22, 0xf1, 0x67, 0x76, 0x71, 0x0c, 0xff, 0x99,
                0x7b, 0x94, 0x9b, 0x24, 0x20, 0x80, 0xe3, 0xcc,
                0x06, 0x4a, 0xed, 0xdf, 0xec, 0x50, 0xd5, 0x87,
                0x3d, 0xa0, 0x7d, 0x9c, 0xe5, 0x13, 0x10, 0x98,
                0x14, 0xc3, 0x90, 0x10, 0xd9, 0x25, 0x9a, 0x59,
                0xe9, 0x37, 0x26, 0xfd, 0x87, 0xd7, 0xf4, 0xf9,
                0x11, 0x91, 0xad, 0x5c, 0x00, 0x95, 0xf5, 0x2b,
                0x37, 0xf7, 0x4e, 0xb4, 0x4b, 0x42, 0x7c, 0xb3,
                0xad, 0xd6, 0x33, 0x5f, 0x0b, 0x84, 0x57, 0x7f,
                0xa7, 0x07, 0x73, 0x37, 0x4b, 0xab, 0x2e, 0xfb,
                0xfe, 0x1e, 0xcb, 0xb6, 0x4a, 0xc1, 0x21, 0x5f,
                0xec, 0x92, 0xb7, 0xac, 0x97, 0x75, 0x20, 0xc9,
                0xd8, 0x9e, 0x93, 0xd5, 0x12, 0x7a, 0x64, 0xb9,
                0x4c, 0xed, 0x49, 0x87, 0x44, 0x5b, 0x4f, 0x90,
                0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f,
                0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48,
                0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5,
                0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde,
                0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9
              ]), False)

            data = Data()
            rsaParams = RsaKeyParams(1024)

            keyName = Name("test")

            decryptKey = RsaAlgorithm.generateKey(rsaParams)
            encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

            eKey = encryptKey.getKeyBits()
            dKey = decryptKey.getKeyBits()

            encryptParams = EncryptParams(input.type)
            Encryptor.encryptData(data, largeContent, keyName, eKey, encryptParams)

            self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)),
                            input.testName)

            largeDataContent = data.getContent()

            # largeDataContent is a sequence of the two EncryptedContent.
            encryptedNonce = EncryptedContent()
            encryptedNonce.wireDecode(largeDataContent)
            self.assertTrue(keyName.equals(encryptedNonce.getKeyLocator().getKeyName()),
                            input.testName)
            self.assertEqual(encryptedNonce.getInitialVector().size(), 0,
                             input.testName)
            self.assertEqual(encryptedNonce.getAlgorithmType(), input.type,
                             input.testName)

            # Use the size of encryptedNonce to find the start of encryptedPayload.
            payloadContent = largeDataContent.buf()[encryptedNonce.wireEncode().size():]
            encryptedPayload = EncryptedContent()
            encryptedPayload.wireDecode(payloadContent)
            nonceKeyName = Name(keyName)
            nonceKeyName.append("nonce")
            self.assertTrue(nonceKeyName.equals(encryptedPayload.getKeyLocator().getKeyName()),
                            input.testName)
            self.assertEqual(encryptedPayload.getInitialVector().size(), 16,
                             input.testName)
            self.assertEqual(encryptedPayload.getAlgorithmType(), EncryptAlgorithmType.AesCbc,
                             input.testName)

            self.assertEqual(
              largeDataContent.size(),
              encryptedNonce.wireEncode().size() + encryptedPayload.wireEncode().size(),
              input.testName)

            blobNonce = encryptedNonce.getPayload()
            nonce = RsaAlgorithm.decrypt(dKey, blobNonce, encryptParams)

            encryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
            encryptParams.setInitialVector(encryptedPayload.getInitialVector())
            bufferPayload = encryptedPayload.getPayload()
            largePayload = AesAlgorithm.decrypt(nonce, bufferPayload, encryptParams)

            self.assertTrue(largeContent.equals(largePayload), input.testName)
Exemple #25
0
    def test_content_key_request(self):
        prefix = Name("/prefix")
        suffix = Name("/a/b/c")
        expectedInterest = Name(prefix)
        expectedInterest.append(Encryptor.NAME_COMPONENT_READ)
        expectedInterest.append(suffix)
        expectedInterest.append(Encryptor.NAME_COMPONENT_E_KEY)

        cKeyName = Name(prefix)
        cKeyName.append(Encryptor.NAME_COMPONENT_SAMPLE)
        cKeyName.append(suffix)
        cKeyName.append(Encryptor.NAME_COMPONENT_C_KEY)

        timeMarker = Name("20150101T100000/20150101T120000")
        testTime1 = Schedule.fromIsoString("20150101T100001")
        testTime2 = Schedule.fromIsoString("20150101T110001")
        testTimeRounded1 = Name.Component("20150101T100000")
        testTimeRounded2 = Name.Component("20150101T110000")
        testTimeComponent2 = Name.Component("20150101T110001")

        # Create content keys required for this test case:
        for i in range(suffix.size()):
            self.createEncryptionKey(expectedInterest, timeMarker)
            expectedInterest = expectedInterest.getPrefix(-2).append(
                Encryptor.NAME_COMPONENT_E_KEY)

        expressInterestCallCount = [0]

        # Prepare a TestFace to instantly answer calls to expressInterest.
        class TestFace(object):
            def __init__(self, handleExpressInterest):
                self.handleExpressInterest = handleExpressInterest

            def expressInterest(self, interest, onData, onTimeout,
                                onNetworkNack):
                return self.handleExpressInterest(interest, onData, onTimeout,
                                                  onNetworkNack)

        def handleExpressInterest(interest, onData, onTimeout, onNetworkNack):
            expressInterestCallCount[0] += 1

            interestName = Name(interest.getName())
            interestName.append(timeMarker)
            self.assertTrue(interestName in self.encryptionKeys)
            onData(interest, self.encryptionKeys[interestName])

            return 0

        face = TestFace(handleExpressInterest)

        # Verify that the content key is correctly encrypted for each domain, and
        # the produce method encrypts the provided data with the same content key.
        testDb = Sqlite3ProducerDb(self.databaseFilePath)
        producer = Producer(prefix, suffix, face, self.keyChain, testDb)
        contentKey = [None]  # Blob

        def checkEncryptionKeys(result, testTime, roundedTime,
                                expectedExpressInterestCallCount):
            self.assertEqual(expectedExpressInterestCallCount,
                             expressInterestCallCount[0])

            self.assertEqual(True, testDb.hasContentKey(testTime))
            contentKey[0] = testDb.getContentKey(testTime)

            params = EncryptParams(EncryptAlgorithmType.RsaOaep)
            for i in range(len(result)):
                key = result[i]
                keyName = key.getName()
                self.assertEqual(cKeyName, keyName.getSubName(0, 6))
                self.assertEqual(keyName.get(6), roundedTime)
                self.assertEqual(keyName.get(7), Encryptor.NAME_COMPONENT_FOR)
                self.assertEqual(True,
                                 keyName.getSubName(8) in self.decryptionKeys)

                decryptionKey = self.decryptionKeys[keyName.getSubName(8)]
                self.assertEqual(True, decryptionKey.size() != 0)
                encryptedKeyEncoding = key.getContent()

                content = EncryptedContent()
                content.wireDecode(encryptedKeyEncoding)
                encryptedKey = content.getPayload()
                retrievedKey = RsaAlgorithm.decrypt(decryptionKey,
                                                    encryptedKey, params)

                self.assertTrue(contentKey[0].equals(retrievedKey))

            self.assertEqual(3, len(result))

        # An initial test to confirm that keys are created for this time slot.
        contentKeyName1 = producer.createContentKey(
            testTime1, lambda keys: checkEncryptionKeys(
                keys, testTime1, testTimeRounded1, 3))

        # Verify that we do not repeat the search for e-keys. The total
        #   expressInterestCallCount should be the same.
        contentKeyName2 = producer.createContentKey(
            testTime2, lambda keys: checkEncryptionKeys(
                keys, testTime2, testTimeRounded2, 3))

        # Confirm content key names are correct
        self.assertEqual(cKeyName, contentKeyName1.getPrefix(-1))
        self.assertEqual(testTimeRounded1, contentKeyName1.get(6))
        self.assertEqual(cKeyName, contentKeyName2.getPrefix(-1))
        self.assertEqual(testTimeRounded2, contentKeyName2.get(6))

        # Confirm that produce encrypts with the correct key and has the right name.
        testData = Data()
        producer.produce(testData, testTime2, Blob(DATA_CONTENT, False))

        producedName = testData.getName()
        self.assertEqual(cKeyName.getPrefix(-1), producedName.getSubName(0, 5))
        self.assertEqual(testTimeComponent2, producedName.get(5))
        self.assertEqual(Encryptor.NAME_COMPONENT_FOR, producedName.get(6))
        self.assertEqual(cKeyName, producedName.getSubName(7, 6))
        self.assertEqual(testTimeRounded2, producedName.get(13))

        dataBlob = testData.getContent()

        dataContent = EncryptedContent()
        dataContent.wireDecode(dataBlob)
        encryptedData = dataContent.getPayload()
        initialVector = dataContent.getInitialVector()

        params = EncryptParams(EncryptAlgorithmType.AesCbc, 16)
        params.setInitialVector(initialVector)
        decryptTest = AesAlgorithm.decrypt(contentKey[0], encryptedData,
                                           params)
        self.assertTrue(decryptTest.equals(Blob(DATA_CONTENT, False)))
Exemple #26
0
    def test_content_key_request(self):
        prefix = Name("/prefix")
        suffix = Name("/a/b/c")
        expectedInterest = Name(prefix)
        expectedInterest.append(Encryptor.NAME_COMPONENT_READ)
        expectedInterest.append(suffix)
        expectedInterest.append(Encryptor.NAME_COMPONENT_E_KEY)

        cKeyName = Name(prefix)
        cKeyName.append(Encryptor.NAME_COMPONENT_SAMPLE)
        cKeyName.append(suffix)
        cKeyName.append(Encryptor.NAME_COMPONENT_C_KEY)

        timeMarker = Name("20150101T100000/20150101T120000")
        testTime1 = Schedule.fromIsoString("20150101T100001")
        testTime2 = Schedule.fromIsoString("20150101T110001")
        testTimeRounded1 = Name.Component("20150101T100000")
        testTimeRounded2 = Name.Component("20150101T110000")

        # Create content keys required for this test case:
        for i in range(suffix.size()):
          self.createEncryptionKey(expectedInterest, timeMarker)
          expectedInterest = expectedInterest.getPrefix(-2).append(
            Encryptor.NAME_COMPONENT_E_KEY)

        expressInterestCallCount = [0]

        # Prepare a TestFace to instantly answer calls to expressInterest.
        class TestFace(object):
            def __init__(self, handleExpressInterest):
                self.handleExpressInterest = handleExpressInterest
            def expressInterest(self, interest, onData, onTimeout):
                return self.handleExpressInterest(interest, onData, onTimeout)

        def handleExpressInterest(interest, onData, onTimeout):
            expressInterestCallCount[0] += 1

            interestName = Name(interest.getName())
            interestName.append(timeMarker)
            self.assertTrue(interestName in self.encryptionKeys)
            onData(interest, self.encryptionKeys[interestName])

            return 0
        face = TestFace(handleExpressInterest)

        # Verify that the content key is correctly encrypted for each domain, and
        # the produce method encrypts the provided data with the same content key.
        testDb = Sqlite3ProducerDb(self.databaseFilePath)
        producer = Producer(prefix, suffix, face, self.keyChain, testDb)
        contentKey = [None] # Blob

        def checkEncryptionKeys(
          result, testTime, roundedTime, expectedExpressInterestCallCount):
            self.assertEqual(expectedExpressInterestCallCount,
                             expressInterestCallCount[0])

            self.assertEqual(True, testDb.hasContentKey(testTime))
            contentKey[0] = testDb.getContentKey(testTime)

            params = EncryptParams(EncryptAlgorithmType.RsaOaep)
            for i in range(len(result)):
                key = result[i]
                keyName = key.getName()
                self.assertEqual(cKeyName, keyName.getSubName(0, 6))
                self.assertEqual(keyName.get(6), roundedTime)
                self.assertEqual(keyName.get(7), Encryptor.NAME_COMPONENT_FOR)
                self.assertEqual(
                  True, keyName.getSubName(8) in self.decryptionKeys)

                decryptionKey = self.decryptionKeys[keyName.getSubName(8)]
                self.assertEqual(True, decryptionKey.size() != 0)
                encryptedKeyEncoding = key.getContent()

                content = EncryptedContent()
                content.wireDecode(encryptedKeyEncoding)
                encryptedKey = content.getPayload()
                retrievedKey = RsaAlgorithm.decrypt(
                  decryptionKey, encryptedKey, params)

                self.assertTrue(contentKey[0].equals(retrievedKey))

            self.assertEqual(3, len(result))

        # An initial test to confirm that keys are created for this time slot.
        contentKeyName1 = producer.createContentKey(
          testTime1,
          lambda keys: checkEncryptionKeys(keys, testTime1, testTimeRounded1, 3))

        # Verify that we do not repeat the search for e-keys. The total
        #   expressInterestCallCount should be the same.
        contentKeyName2 = producer.createContentKey(
          testTime2,
          lambda keys: checkEncryptionKeys(keys, testTime2, testTimeRounded2, 3))

        # Confirm content key names are correct
        self.assertEqual(cKeyName, contentKeyName1.getPrefix(-1))
        self.assertEqual(testTimeRounded1, contentKeyName1.get(6))
        self.assertEqual(cKeyName, contentKeyName2.getPrefix(-1))
        self.assertEqual(testTimeRounded2, contentKeyName2.get(6))

        # Confirm that produce encrypts with the correct key and has the right name.
        testData = Data()
        producer.produce(testData, testTime2, Blob(DATA_CONTENT, False))

        producedName = testData.getName()
        self.assertEqual(cKeyName.getPrefix(-1), producedName.getSubName(0, 5))
        self.assertEqual(testTimeRounded2, producedName.get(5))
        self.assertEqual(Encryptor.NAME_COMPONENT_FOR, producedName.get(6))
        self.assertEqual(cKeyName, producedName.getSubName(7, 6))
        self.assertEqual(testTimeRounded2, producedName.get(13))

        dataBlob = testData.getContent()

        dataContent = EncryptedContent()
        dataContent.wireDecode(dataBlob)
        encryptedData = dataContent.getPayload()
        initialVector = dataContent.getInitialVector()

        params = EncryptParams(EncryptAlgorithmType.AesCbc, 16)
        params.setInitialVector(initialVector)
        decryptTest = AesAlgorithm.decrypt(contentKey[0], encryptedData, params)
        self.assertTrue(decryptTest.equals(Blob(DATA_CONTENT, False)))
Exemple #27
0
    def calculateAggregation(self,
                             dataType,
                             aggregationType,
                             childrenList,
                             startTime,
                             interval,
                             publishingPrefix,
                             repeat=False):
        doCalc = True
        dataList = []

        # TODO: an intermediate node cannot produce raw data for now
        if len(childrenList.keys()) != 0:
            for childName in childrenList.keys():
                dataDictKey = self.getDataDictKey(startTime,
                                                  (startTime + interval),
                                                  childName)
                if dataDictKey in self._dataQueue[dataType +
                                                  aggregationType]._dataDict:
                    data = self._dataQueue[
                        dataType + aggregationType]._dataDict[dataDictKey]
                    dataList.append(float(data.getContent().toRawStr()))
                else:
                    #print('Child ' + childName + ' has not replied yet')
                    doCalc = False
                    break
        else:
            for inst in self._dataQueue[dataType]._dataDict.keys():
                if int(inst) >= startTime and int(inst) < startTime + interval:
                    dataList.append(self._dataQueue[dataType]._dataDict[inst])
        if doCalc:
            content = self._aggregation.getAggregation(aggregationType,
                                                       dataList)
            if content:
                publishData = Data(
                    Name(publishingPrefix).append(str(startTime)).append(
                        str(startTime + interval)))
                publishData.setContent(str(content))
                publishData.getMetaInfo().setFreshnessPeriod(
                    DEFAULT_DATA_LIFETIME)
                self._keyChain.sign(publishData, self._certificateName)
                self._memoryContentCache.add(publishData)
                for childName in childrenList.keys():
                    dataDictKey = self.getDataDictKey(startTime,
                                                      (startTime + interval),
                                                      childName)
                    if dataDictKey in self._dataQueue[
                            dataType + aggregationType]._dataDict:
                        del self._dataQueue[
                            dataType + aggregationType]._dataDict[dataDictKey]
                if __debug__:
                    print("Produced: " + publishData.getName().toUri() + "; " +
                          publishData.getContent().toRawStr())

        # repetition of this function only happens for raw data producer, otherwise calculateAggregation is called by each onData
        if repeat:
            self._loop.call_later(interval, self.calculateAggregation,
                                  dataType, aggregationType, childrenList,
                                  startTime + interval, interval,
                                  publishingPrefix, repeat)
        return