def test_self_verification(self): policyManager = SelfVerifyPolicyManager(self.identityStorage) keyChain = KeyChain(self.identityManager, policyManager) identityName = Name('TestValidator/RsaSignatureVerification') keyChain.createIdentityAndCertificate(identityName) data = Data(Name('/TestData/1')) keyChain.signByIdentity(data, identityName) vr = doVerify(policyManager, data) self.assertFalse(vr.hasFurtherSteps, "SelfVerifyPolicyManager returned a ValidationRequest") self.assertEqual(vr.failureCount, 0, "Verification of identity-signed data failed") self.assertEqual(vr.successCount, 1, "Verification success called {} times instead of 1".format( vr.successCount)) data2 = Data(Name('/TestData/2')) vr = doVerify(policyManager, data2) self.assertFalse(vr.hasFurtherSteps, "SelfVerifyPolicyManager returned a ValidationRequest") self.assertEqual(vr.successCount, 0, "Verification of unsigned data succeeded") self.assertEqual(vr.failureCount, 1, "Verification failure callback called {} times instead of 1".format( vr.failureCount))
def __init__(self): self.identityStorage = MemoryIdentityStorage() self.privateKeyStorage = MemoryPrivateKeyStorage() self.keyChain = KeyChain( IdentityManager(self.identityStorage, self.privateKeyStorage), SelfVerifyPolicyManager(self.identityStorage)) keyName = Name("/testname/DSK-123") self.defaultCertName = keyName[:-1].append("KEY").append( keyName[-1]).append("ID-CERT").append("0") ecdsaKeyName = Name("/testEcdsa/DSK-123") self.ecdsaCertName = ecdsaKeyName[:-1].append("KEY").append( ecdsaKeyName[-1]).append("ID-CERT").append("0") self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER)) self.privateKeyStorage.setKeyPairForKeyName( keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER) self.identityStorage.addKey(ecdsaKeyName, KeyType.ECDSA, Blob(DEFAULT_EC_PUBLIC_KEY_DER)) self.privateKeyStorage.setKeyPairForKeyName( ecdsaKeyName, KeyType.ECDSA, DEFAULT_EC_PUBLIC_KEY_DER, DEFAULT_EC_PRIVATE_KEY_DER)
def benchmarkDecodeDataSeconds(nIterations, useCrypto, encoding): """ Loop to decode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useCrypto: If true, verify the signature. If false, don't verify. :param Blob encoding: The wire encoding to decode. """ # Initialize the private key storage in case useCrypto is true. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) 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)) start = getNowSeconds() for i in range(nIterations): data = Data() data.wireDecode(encoding) if useCrypto: keyChain.verifyData(data, onVerified, onVerifyFailed) finish = getNowSeconds() return finish - start
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding): """ Loop to decode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useCrypto: If true, verify the signature. If false, don't verify. :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True. :param Blob encoding: The wire encoding to decode. :return: The number of seconds for all iterations. :rtype: float """ # Initialize the private key storage in case useCrypto is true. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) keyName = Name("/testname/DSK-123") identityStorage.addKey( keyName, keyType, Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER)) start = getNowSeconds() for i in range(nIterations): data = Data() data.wireDecode(encoding) if useCrypto: keyChain.verifyData(data, onVerified, onValidationFailed) finish = getNowSeconds() return finish - start
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest( Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() freshInterest.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # 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))) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest(reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnValidationFailed("Freshly-signed Interest"))
def setUp(self): # Reuse the policy_config subdirectory for the temporary SQLite file. self.databaseFilePath = "policy_config/test-public-info.db" try: os.remove(self.databaseFilePath) except OSError: # no such file pass self.identityStorage = BasicIdentityStorage(self.databaseFilePath) self.identityManager = IdentityManager(self.identityStorage, FilePrivateKeyStorage()) self.policyManager = SelfVerifyPolicyManager(self.identityStorage) self.keyChain = KeyChain(self.identityManager, self.policyManager)
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(): backboneFace = Face() 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))) backboneFace.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) prefix = Name("/farm1") backboneFace.registerPrefix(prefix, onInterest, onRegisterFailed) print("Ready to go...") while 1: try: backboneFace.processEvents() e.acquire() frame = ieee.wait_read_frame(0.01) e.release() if frame is not None: if frame['rf_data'][0] == b'\x06' or frame['rf_data'][ 0] == b'\x05': #if Data or Interest buffData[0] = frame['rf_data'][0] buffData[1] = ord(frame['rf_data'][1]) + lCP buffData[2] = frame['rf_data'][2] buffData[3] = ord(frame['rf_data'][3]) + lCP buffData[4:lCP + 4] = eCP buffData[lCP + 4:] = frame['rf_data'][4:] print(str(datetime.now().strftime('%X.%f'))) backboneFace.send(buffData) else: print(frame['rf_data'][:]) #time.sleep(0.1) gc.collect() except KeyboardInterrupt: backboneFace.shutdown() ser.close() break
def test_verify_digest_sha256(self): # Create a KeyChain but we don't need to add keys. identityStorage = MemoryIdentityStorage() keyChain = KeyChain( IdentityManager(identityStorage, MemoryPrivateKeyStorage()), SelfVerifyPolicyManager(identityStorage)) interest = Interest(Name("/test/signed-interest")) keyChain.signWithSha256(interest) # We create 'mock' objects to replace callbacks since we're not # interested in the effect of the callbacks themselves. failedCallback = Mock() verifiedCallback = Mock() keyChain.verifyInterest(interest, verifiedCallback, failedCallback) self.assertEqual(failedCallback.call_count, 0, 'Signature verification failed') self.assertEqual(verifiedCallback.call_count, 1, 'Verification callback was not used.')
def createVerifyKeyChain(): """ Create an in-memory KeyChain with a default public key for verifying. :return: A new KeyChain. :rtype: KeyChain """ identityStorage = MemoryIdentityStorage() keyChain = KeyChain( IdentityManager(identityStorage, MemoryPrivateKeyStorage()), SelfVerifyPolicyManager(identityStorage)) # Initialize the storage. keyName = Name("/testname/DSK-123") identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)) return keyChain
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"))
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding): """ Loop to decode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useCrypto: If true, verify the signature. If false, don't verify. :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True. :param Blob encoding: The wire encoding to decode. :return: The number of seconds for all iterations. :rtype: float """ # Initialize the private key storage in case useCrypto is true. 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_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER, False))) start = getNowSeconds() for i in range(nIterations): data = Data() data.wireDecode(encoding) if useCrypto: keyChain.verifyData(data, onVerified, onValidationFailed) finish = getNowSeconds() return finish - start
def main(): interest = Interest() interest.wireDecode(TlvInterest) dump("Interest:") dumpInterest(interest) # Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()) encoding = interest.wireEncode() dump("") dump("Re-encoded interest", encoding.toHex()) reDecodedInterest = Interest() reDecodedInterest.wireDecode(encoding) dump("Re-decoded Interest:") dumpInterest(reDecodedInterest) freshInterest = (Interest( Name("/ndn/abc")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST) freshInterest.getKeyLocator().setKeyData( bytearray([ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F ])) freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny() dump(freshInterest.toUri()) 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) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, certificateName) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest(reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnVerifyFailed("Freshly-signed Interest"))
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto): """ Loop to encode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useComplex: If true, use a large name, large content and all fields. If false, use a small name, small content and only required fields. :param bool useCrypto: If true, sign the data packet. If false, use a blank signature. :return: A tuple (duration, encoding) where duration is the number of seconds for all iterations and encoding is the wire encoding. :rtype: (float, Blob) """ if useComplex: # Use a large name and content. name = Name( "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00" ) contentString = "" count = 1 contentString += "%d" % count count += 1 while len(contentString) < 1115: contentString += " %d" % count count += 1 content = Name.fromEscapedString(contentString) else: # Use a small name and content. name = Name("/test") content = Name.fromEscapedString("abc") finalBlockId = Name("/%00")[0] # Initialize the private key storage in case useCrypto is true. identityStorage = MemoryIdentityStorage() privateKeyStorage = MemoryPrivateKeyStorage() keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage)) 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) # Set up signatureBits in case useCrypto is false. signatureBits = Blob(bytearray(256)) emptyBlob = Blob([]) start = getNowSeconds() for i in range(nIterations): data = Data(name) data.setContent(content) if useComplex: data.getMetaInfo().setFreshnessPeriod(1000) data.getMetaInfo().setFinalBlockId(finalBlockId) if useCrypto: # This sets the signature fields. keyChain.sign(data, certificateName) else: # Imitate IdentityManager.signByCertificate to set up the signature # fields, but don't sign. sha256Signature = data.getSignature() keyLocator = sha256Signature.getKeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.setKeyName(certificateName) sha256Signature.setSignature(signatureBits) encoding = data.wireEncode() finish = getNowSeconds() return (finish - start, encoding)
if __name__ == '__main__': rp = RepoCommandParameter() dataPrefix = Name("/example/data/1/test/test1") rp.setName(dataPrefix) rp.setStartBlockId(0) interest = Interest( Name("/example/repo/1").append("insert").append(rp.wireEncode())) 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) # Make a Face just so that we can sign the interest. face = Face("localhost")
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto, keyType): """ Loop to encode a data packet nIterations times. :param int nIterations: The number of iterations. :param bool useComplex: If true, use a large name, large content and all fields. If false, use a small name, small content and only required fields. :param bool useCrypto: If true, sign the data packet. If false, use a blank signature. :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True. :return: A tuple (duration, encoding) where duration is the number of seconds for all iterations and encoding is the wire encoding. :rtype: (float, Blob) """ if useComplex: # Use a large name and content. name = Name( "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00" ) contentString = "" count = 1 contentString += "%d" % count count += 1 while len(contentString) < 1115: contentString += " %d" % count count += 1 content = Name.fromEscapedString(contentString) else: # Use a small name and content. name = Name("/test") content = Name.fromEscapedString("abc") finalBlockId = Name("/%00")[0] # Initialize the private key storage in case useCrypto is true. pibImpl = PibMemory() keyChain = KeyChain(pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) keyChain.importSafeBag( SafeBag( Name("/testname/KEY/123"), Blob( DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob( DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER, False))) certificateName = keyChain.getDefaultCertificateName() # Set up signatureBits in case useCrypto is false. signatureBits = Blob(bytearray(256)) start = getNowSeconds() for i in range(nIterations): data = Data(name) data.setContent(content) if useComplex: data.getMetaInfo().setFreshnessPeriod(1000) data.getMetaInfo().setFinalBlockId(finalBlockId) if useCrypto: # This sets the signature fields. keyChain.sign(data) else: # Imitate IdentityManager.signByCertificate to set up the signature # fields, but don't sign. sha256Signature = data.getSignature() keyLocator = sha256Signature.getKeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.setKeyName(certificateName) sha256Signature.setSignature(signatureBits) encoding = data.wireEncode() finish = getNowSeconds() return (finish - start, encoding)