예제 #1
0
    def __init__(self, face, encryptResult, link = None):
        # Set up face
        self.face = face
        self._encryptResult = encryptResult
        self._link = link

        self.databaseFilePath = "policy_config/test_consumer_dpu.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupName = Name("/org/openmhealth/haitao")

        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())
        # Authorized identity
        identityName = Name("/ndn/edu/basel/dpu")
        # Function name: the function that this DPU provides
        self._functionName = "bounding_box"
        self._identityName = identityName
        
        self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
        # TODO: if using BasicIdentityStorage and FilePrivateKeyStorage
        #   For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error
        #self.keyChain.installIdentityCertificate()
        
        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName)
        consumerCertificate = identityStorage.getCertificate(self.certificateName)
        self.consumer = Consumer(
          face, self.keyChain, self.groupName, identityName,
          Sqlite3ConsumerDb(self.databaseFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile:
            print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")
            base64Content = keyFile.read()
            #print base64Content
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
        self.memoryContentCache.add(consumerCertificate)

        accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time())))
        self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout)
        print "Access request interest name: " + accessRequestInterest.getName().toUri()

        self._tasks = dict()

        return
예제 #2
0
    def __init__(self, face, groupManagerName, dataType, dKeyDatabaseFilePath):
        # Set up face
        self.face = face
        #self.loop = eventLoop

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            groupManagerName)

        self.dKeyDatabaseFilePath = dKeyDatabaseFilePath

        self.manager = GroupManager(
            groupManagerName, dataType,
            Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1,
            self.keyChain)

        self.memoryContentCache = MemoryContentCache(self.face)

        self.memoryContentCache.registerPrefix(groupManagerName,
                                               self.onRegisterFailed,
                                               self.onDataNotFound)

        self.needToPublishGroupKeys = False
        return
예제 #3
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    #print("key1")
    #keyChain = KeyChain()
    #print("key2")
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    identityName = Name("TestProducer")
    certificateName = keyChain.createIdentityAndCertificate(identityName)
    keyChain.getIdentityManager().setDefaultIdentity(identityName)

    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    ubicdn = UbiCDN(keyChain, certificateName)
    prefix = Name("/ubicdn/video")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, ubicdn.onInterest, ubicdn.onRegisterFailed)

    while 1:
        #while ubicdn._responseCount < 1:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
예제 #4
0
def createKeyChain():
    """
    Create an in-memory KeyChain with default keys.

    :return: A tuple with the new KeyChain and certificate name.
    :rtype: (KeyChain,Name)
    """
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())

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

    return keyChain, certificateName
예제 #5
0
    def setUp(self):
        self.decryptionKeys = {}  # key: Name, value: Blob
        self.encryptionKeys = {}  # key: Name, value: Data

        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.databaseFilePath = "policy_config/test.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupName = Name("/Prefix/READ")
        self.contentName = Name("/Prefix/SAMPLE/Content")
        self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        self.eKeyName = Name("/Prefix/READ/E-KEY/1/2")
        self.dKeyName = Name("/Prefix/READ/D-KEY/1/2")
        self.uKeyName = Name("/U/Key")
        self.uName = Name("/U")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            self.fixtureDKeyBlob).getKeyBits()

        # Generate the user key.
        self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            self.fixtureUDKeyBlob).getKeyBits()

        # Load the C-KEY.
        self.fixtureCKeyBlob = Blob(AES_KEY, False)

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())

        # Initialize the storage.
        keyName = Name("/testname/DSK-123")
        self.certificateName = keyName.getSubName(
            0,
            keyName.size() - 1).append("KEY").append(
                keyName.get(-1)).append("ID-CERT").append("0")
        identityStorage.addKey(keyName, KeyType.RSA,
                               Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
        privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                               DEFAULT_RSA_PUBLIC_KEY_DER,
                                               DEFAULT_RSA_PRIVATE_KEY_DER)
    def __init__(self, face, username, memoryContentCache):
        # Set up face
        self.face = face

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())

        identityName = Name(username)
        self.certificateName = self.keyChain.createIdentityAndCertificate(
            identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)

        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        self.databaseFilePath = "../policy_config/test_producer.db"
        self.catalogDatabaseFilePath = "../policy_config/test_producer_catalog.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass
        try:
            os.remove(self.catalogDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.testDb = Sqlite3ProducerDb(self.databaseFilePath)
        self.catalogDb = Sqlite3ProducerDb(self.catalogDatabaseFilePath)

        # TODO: as of right now, catalog has a different suffix, so need another instance of producer; that producer cannot share
        # the same DB with the first producer, otherwise there won't be a self.onEncryptedKeys call; as the catalog producer uses
        # its own C-key, and that key won't be encrypted by an E-key as no interest goes out
        # This sounds like something problematic from the library
        prefix = Name(username)
        suffix = Name("fitness/physical_activity/time_location")

        self.producer = Producer(Name(prefix), suffix, self.face,
                                 self.keyChain, self.testDb)

        catalogSuffix = Name(suffix).append("catalog")
        self.catalogProducer = Producer(Name(prefix), catalogSuffix, self.face,
                                        self.keyChain, self.catalogDb)

        self.memoryContentCache = memoryContentCache
        return
예제 #7
0
 def __init__(self, face):
     # Set up face
     self.face = face
     identityStorage = BasicIdentityStorage()
     privateKeyStorage = FilePrivateKeyStorage()
     self.keyChain = KeyChain(
         IdentityManager(identityStorage, privateKeyStorage),
         NoVerifyPolicyManager())
     self.face.setCommandSigningInfo(
         self.keyChain,
         Name(
             "/org/openmhealth/KEY/ksk-1490231565751/ID-CERT/%FD%00%00%01Z%F8%B9%1Et"
         ))
     self.face.registerPrefix(Name("/org/openmhealth"), self.onInterest,
                              self.onRegisterFailed)
예제 #8
0
    def test_no_verify(self):
        policyManager = NoVerifyPolicyManager()
        identityName = Name('TestValidator/Null').appendVersion(int(time.time()))

        keyChain = KeyChain(self.identityManager, policyManager)
        keyChain.createIdentityAndCertificate(identityName)
        data = Data(Name(identityName).append('data'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "NoVerifyPolicyManager returned a ValidationRequest")

        self.assertEqual(vr.failureCount, 0,
            "Verification failed with NoVerifyPolicyManager")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))
예제 #9
0
    def setUp(self):
        self.decryptionKeys = {} # key: Name, value: Blob
        self.encryptionKeys = {} # key: Name, value: Data

        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.databaseFilePath = "policy_config/test.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())
        identityName = Name("TestProducer")
        self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
예제 #10
0
    def __init__(self, face, groupManagerName, dataType, readAccessName,
                 dKeyDatabaseFilePath):
        # Set up face
        self.face = face
        #self.loop = eventLoop

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            groupManagerName)

        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        self.dKeyDatabaseFilePath = dKeyDatabaseFilePath
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.manager = GroupManager(
            groupManagerName, dataType,
            Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1,
            self.keyChain)

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(
            Name(groupManagerName).append("READ"), self.onRegisterFailed,
            self.onDataNotFound)
        self.face.registerPrefix(readAccessName, self.onAccessInterest,
                                 self.onAccessTimeout)

        self.updateGroupKeys = False
        return
예제 #11
0
import os, time, base64, re, json, sys, getopt
from pyndn import Name, Data, Face, Interest, Link
from pyndn.util import Blob, MemoryContentCache
from pyndn.encrypt import Schedule, Consumer, Sqlite3ConsumerDb, EncryptedContent

from pyndn.security import KeyType, KeyChain, RsaKeyParams, SecurityException
from pyndn.security.certificate import IdentityCertificate
from pyndn.security.identity import IdentityManager
from pyndn.security.identity import BasicIdentityStorage, FilePrivateKeyStorage, MemoryIdentityStorage, MemoryPrivateKeyStorage
from pyndn.security.policy import NoVerifyPolicyManager

# Set up the keyChain.
identityStorage = BasicIdentityStorage()
privateKeyStorage = FilePrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                    NoVerifyPolicyManager())

# dvu identity
identityName = Name("/org/openmhealth/dvu")
certificateName = keyChain.createIdentityAndCertificate(identityName)
keyName = IdentityCertificate.certificateNameToPublicKeyName(certificateName)
certificate = identityStorage.getCertificate(certificateName)
print keyName
print certificateName
print certificate
print privateKeyStorage.nameTransform(keyName.toUri(), ".pri")
#with open(privateKeyStorage.nameTransform(keyName.toUri(), ".pri")) as keyFile:
#    base64Content = keyFile.read()
#    decoded = base64.b64decode(base64Content)
#    print decoded
#    for i in range(0, len(decoded)):
예제 #12
0
    def setUp(self):
        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db"
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db"
        try:
            os.remove(self.eKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db"
        try:
            os.remove(self.intervalDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db"
        try:
            os.remove(self.groupKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        params = RsaKeyParams()
        memberDecryptKey = RsaAlgorithm.generateKey(params)
        self.decryptKeyBlob = memberDecryptKey.getKeyBits()
        memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob)
        self.encryptKeyBlob = memberEncryptKey.getKeyBits()

        # Generate the certificate.
        self.certificate = IdentityCertificate()
        self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
        contentPublicKey = PublicKey(self.encryptKeyBlob)
        self.certificate.setPublicKeyInfo(contentPublicKey)
        self.certificate.setNotBefore(0)
        self.certificate.setNotAfter(0)
        self.certificate.encode()

        signatureInfoBlob = Blob(SIG_INFO, False)
        signatureValueBlob = Blob(SIG_VALUE, False)

        signature = TlvWireFormat.get().decodeSignatureInfoAndValue(
            signatureInfoBlob.buf(), signatureValueBlob.buf())
        self.certificate.setSignature(signature)

        self.certificate.wireEncode()

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        identityName = Name("TestGroupManager")
        self.keyChain.createIdentityAndCertificate(identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
예제 #13
0
    def __init__(self, face):
        # Set up face
        self.face = face

        self.databaseFilePath = "policy_config/test_consumer.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupName = Name("/org/openmhealth/haitao")

        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        # Authorized identity
        identityName = Name("/org/openmhealth/dvu-python-3")
        # Unauthorized identity
        #identityName = Name("/org/openmhealth/dvu-python-1")

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            identityName)

        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(
            self.certificateName)
        consumerCertificate = identityStorage.getCertificate(
            self.certificateName)
        self.consumer = Consumer(face, self.keyChain, self.groupName,
                                 identityName,
                                 Sqlite3ConsumerDb(self.databaseFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(
                privateKeyStorage.nameTransform(consumerKeyName.toUri(),
                                                ".pri")) as keyFile:
            print privateKeyStorage.nameTransform(consumerKeyName.toUri(),
                                                  ".pri")
            base64Content = keyFile.read()
            #print base64Content
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(identityName,
                                               self.onRegisterFailed,
                                               self.onDataNotFound)
        self.memoryContentCache.add(consumerCertificate)

        accessRequestInterest = Interest(
            Name(self.groupName).append("read_access_request").append(
                self.certificateName).appendVersion(int(time.time())))
        self.face.expressInterest(accessRequestInterest,
                                  self.onAccessRequestData,
                                  self.onAccessRequestTimeout)
        print "Access request interest name: " + accessRequestInterest.getName(
        ).toUri()

        self.consumeCatalog = True
        return
예제 #14
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix +
                               "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom +
                              "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom +
          ", Username: "******"")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    chat = Chat(screenName, chatRoom, Name(hubPrefix), face, keyChain,
                certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
예제 #15
0
    def __init__(self,
                 face,
                 identityName,
                 groupName,
                 catalogPrefix,
                 rawDataPrefix,
                 producerDbFilePath,
                 consumerDbFilePath,
                 encrypted=False):
        self.face = face
        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        self.identityName = Name(identityName)
        self.groupName = Name(groupName)
        self.rawDataPrefix = rawDataPrefix
        self.catalogPrefix = catalogPrefix

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            self.identityName)
        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        # Set up the memoryContentCache
        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(self.identityName,
                                               self.onRegisterFailed,
                                               self.onDataNotFound)

        self.producerPrefix = Name(identityName)
        self.producerSuffix = Name()

        self.producer = DPUProducer(face, self.memoryContentCache,
                                    self.producerPrefix, self.producerSuffix,
                                    self.keyChain, self.certificateName,
                                    producerDbFilePath)

        # Put own (consumer) certificate in memoryContentCache
        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(
            self.certificateName)
        consumerCertificate = identityStorage.getCertificate(
            self.certificateName, True)

        # TODO: request that this DPU be added as a trusted group member

        self.remainingTasks = dict()

        try:
            os.remove(consumerDbFilePath)
        except OSError:
            # no such file
            pass

        self.consumer = Consumer(face, self.keyChain, self.groupName,
                                 consumerKeyName,
                                 Sqlite3ConsumerDb(consumerDbFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(
                privateKeyStorage.nameTransform(consumerKeyName.toUri(),
                                                ".pri")) as keyFile:
            base64Content = keyFile.read()
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache.add(consumerCertificate)

        self.encrypted = encrypted

        self.rawData = []

        self.catalogFetchFinished = False
        self.remainingData = 0
        return
예제 #16
0
def startFileSync():
    global EXIT
    screenName = promptAndInput("Enter your name: ")

    defaultHubPrefix = "ndn/no/ntnu"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultpkList = "pklist"
    pkListName = promptAndInput("Sync with public key list [" + defaultpkList + "]: ")
    if pkListName == "":
        pkListName = defaultpkList

    host = "localhost" 
    # host = "129.241.208.115"
    logging.info("Connecting to " + host + ", public Key List: " + pkListName + ", Name: " + screenName)

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    # privateKeyStorage = OSXPrivateKeyStorage()
    identityManager = IdentityManager(identityStorage, privateKeyStorage)
    # identityManager.createIdentity(Name("/name/"))
    keyChain = KeyChain(identityManager, NoVerifyPolicyManager())
    keyChain.setFace(face)
    
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    # keyName = Name("/ndn/no/ntnu/stud/haakonmo/ksk-1426537450856")
    # certificateName = Name("/ndn/no/ntnu/KEY/stud/haakonmo/ksk-1426537450856/ID-CERT/%FD%00%00%01L%26%D9E%92")

    # publicKey = privateKeyStorage.getPublicKey(keyName)
    # identityStorage.addKey(keyName, publicKey.getKeyType(), publicKey.getKeyDer())
    # face.setCommandSigningInfo(keyChain, certificateName)

    # print(identityStorage.getCertificate(certificateName))
    # print(identityStorage.getKey(keyName))

    path = './files/'
    fileSyncer = FileSync(screenName, pkListName, Name(hubPrefix), face, keyChain, certificateName, path)
    fileSyncer.initial()    

    fileWatcher = FileWatch(fileSyncer, path)
    # TODO:
    #    1. Generate new public key or use existing?
    #    2. Watch new public key
    #    3. sendUpdatedPublicKey if key is changed
    #    4. Download and store other keys
    #    5. Verify data packet
    while not EXIT:
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                EXIT = True
                break
            #fileSyncer.onFileUpdate(input)

        fileSyncer.face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    fileSyncer.unsubscribe()
    startTime = FileSync.getNowMilliseconds()
    while True:
        if FileSync.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)

    # Shutdown all services
    fileSyncer.face.shutdown()
    fileWatcher.stopFileWatch()
예제 #17
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    defaultUserPrefix = "com/newspaper/USER/bob"
    userPrefix = promptAndInput("Enter user prefix: [" + defaultUserPrefix + "]")
    if userPrefix == "":
        userPrefix = defaultUserPrefix

    defaultNamespacePrefix = "/ndn/hackathon/cnl-demo/slides" #"com/newspaper"
    namespacePrefix = promptAndInput("Enter namespace prefix [" + defaultNamespacePrefix + "]: ")
    if namespacePrefix == "":
        namespacePrefix = defaultNamespacePrefix

    host = "localhost" #"memoria.ndn.ucla.edu"
    print("Connecting to " + host)
    print("")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    newspaper = Namespace(namespacePrefix)
    
    def onContentSet(namespace, contentNamespace, callbackId):
        global currentSlideName
        if contentNamespace == namespace:
            print("content size "+str(contentNamespace.content.size()))
            currentSlideName = contentNamespace.getName()
            displayImage(contentNamespace.content.toRawStr(), contentNamespace.getName().toUri())
            # dump("Got segmented content ", contentNamespace.content.toRawStr())

    def onNewName(namespace, addedNamespace, callbackId):
        print("namespace ("+addedNamespace.getName().toUri()+") added to "+namespace.getName().toUri())
        if addedNamespace.getName().get(-1).isSegment() and addedNamespace.getName().get(-1).toSegment() == 0:
            addedNamespace.getParent().addOnContentSet(onContentSet)
            SegmentedContent(addedNamespace.getParent()).start()

    newspaper.addOnNameAdded(onNewName)
    newspaper.setFace(face)

    namesync = NameSyncHandler(newspaper, userPrefix, keyChain, certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your namespace update. To quit, enter \"exit\".")

    def process():
        # while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "exit":
                stopGui()
                # We will send the leave message below.
                # break

            # before producer has namespace.publish call, we manually call onNameAdded as a hack to publish
            namesync.onNameAdded(None, Namespace(Name(input)), 0, True)
        face.processEvents()
        if root: 
            root.after(100, process)

    def leftKey(event):
        global currentSlideName
        allVersions = newspaper.getChildComponents()
        currentVersion = currentSlideName[-1]
        selected = allVersions[0]
        for c in allVersions:
            print(str(c.toVersion()))
            if c.toVersion() == currentVersion.toVersion():
                break
            selected = c
        currentSlideName = Name(newspaper.getName()).append(selected)
        displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())

    def rightKey(event):
        global currentSlideName
        allVersions = newspaper.getChildComponents()
        currentVersion = currentSlideName[-1]
        selected = None
        for c in allVersions[::-1]:
            if c.toVersion() == currentVersion.toVersion():
                break
            selected = c
        if selected:
            currentSlideName = Name(newspaper.getName()).append(selected)
            displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())
        else:
            print("no slides to show")

    runGui(process, leftKey, rightKey)