Beispiel #1
0
    def signByCertificate(self, target, certificateName, wireFormat=None):
        """
        Sign the target based on the certificateName. If it is a Data object,
        set its signature. If it is an array, return a signature object.

        :param target: If this is a Data object, wire encode for signing,
          update its signature and key locator field and wireEncoding. If it is
          an array, sign it and return a Signature object.
        :param Name certificateName: The Name identifying the certificate which
          identifies the signing key.
        :param wireFormat: (optional) The WireFormat for calling encodeData, or
          WireFormat.getDefaultWireFormat() if omitted.
        :type wireFormat: A subclass of WireFormat
        :return: The Signature object (only if the target is an array).
        :rtype: An object of a subclass of Signature
        """
        if wireFormat == None:
            # Don't use a default argument since getDefaultWireFormat can change.
            wireFormat = WireFormat.getDefaultWireFormat()

        if isinstance(target, Data):
            data = target
            digestAlgorithm = [0]
            signature = self._makeSignatureByCertificate(
                certificateName, digestAlgorithm)

            data.setSignature(signature)
            # Encode once to get the signed portion.
            encoding = data.wireEncode(wireFormat)

            data.getSignature().setSignature(
                self._privateKeyStorage.sign(
                    encoding.toSignedBuffer(),
                    IdentityCertificate.certificateNameToPublicKeyName(
                        certificateName), digestAlgorithm[0]))

            # Encode again to include the signature.
            data.wireEncode(wireFormat)
        else:
            digestAlgorithm = [0]
            signature = self._makeSignatureByCertificate(
                certificateName, digestAlgorithm)

            signature.setSignature(
                self._privateKeyStorage.sign(
                    target,
                    IdentityCertificate.certificateNameToPublicKeyName(
                        certificateName), digestAlgorithm[0]))

            return signature
Beispiel #2
0
    def signByCertificate(self, target, certificateName, wireFormat = None):
        """
        Sign the target based on the certificateName. If it is a Data object,
        set its signature. If it is an array, return a signature object.

        :param target: If this is a Data object, wire encode for signing,
          update its signature and key locator field and wireEncoding. If it is
          an array, sign it and return a Signature object.
        :param Name certificateName: The Name identifying the certificate which
          identifies the signing key.
        :param wireFormat: (optional) The WireFormat for calling encodeData, or
          WireFormat.getDefaultWireFormat() if omitted.
        :type wireFormat: A subclass of WireFormat
        :return: The Signature object (only if the target is an array).
        :rtype: An object of a subclass of Signature
        """
        if wireFormat == None:
            # Don't use a default argument since getDefaultWireFormat can change.
            wireFormat = WireFormat.getDefaultWireFormat()

        if isinstance(target, Data):
            data = target
            digestAlgorithm = [0]
            signature = self._makeSignatureByCertificate(
              certificateName, digestAlgorithm)

            data.setSignature(signature)
            # Encode once to get the signed portion.
            encoding = data.wireEncode(wireFormat)

            data.getSignature().setSignature(self._privateKeyStorage.sign
              (encoding.toSignedBuffer(),
               IdentityCertificate.certificateNameToPublicKeyName(certificateName),
               digestAlgorithm[0]))

            # Encode again to include the signature.
            data.wireEncode(wireFormat)
        else:
            digestAlgorithm = [0]
            signature = self._makeSignatureByCertificate(
              certificateName, digestAlgorithm)

            signature.setSignature(
              self._privateKeyStorage.sign(
                target,
                IdentityCertificate.certificateNameToPublicKeyName(certificateName),
                digestAlgorithm[0]))

            return signature
Beispiel #3
0
    def _makeSignatureByCertificate(self, certificateName, digestAlgorithm):
        """
        Return a new Signature object based on the signature algorithm of the
        public key with keyName (derived from certificateName).

        :param Name certificateName: The full certificate name.
        :param Array digestAlgorithm: Set digestAlgorithm[0] to the signature
          algorithm's digest algorithm, e.g. DigestAlgorithm.SHA256 .
        :return: The related public key name.
        :rtype: Signature
        """
        keyName = IdentityCertificate.certificateNameToPublicKeyName(certificateName)
        publicKey = self._privateKeyStorage.getPublicKey(keyName)
        keyType = publicKey.getKeyType()

        if keyType == KeyType.RSA:
            signature = Sha256WithRsaSignature()
            digestAlgorithm[0] = DigestAlgorithm.SHA256

            signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
            signature.getKeyLocator().setKeyName(certificateName.getPrefix(-1))

            return signature
        elif keyType == KeyType.ECDSA:
            signature = Sha256WithEcdsaSignature()
            digestAlgorithm[0] = DigestAlgorithm.SHA256

            signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
            signature.getKeyLocator().setKeyName(certificateName.getPrefix(-1))

            return signature
        else:
            raise SecurityException("Key type is not recognized")
Beispiel #4
0
    def _makeSignatureByCertificate(self, certificateName, digestAlgorithm):
        """
        Return a new Signature object based on the signature algorithm of the
        public key with keyName (derived from certificateName).

        :param Name certificateName: The full certificate name.
        :param Array digestAlgorithm: Set digestAlgorithm[0] to the signature
          algorithm's digest algorithm, e.g. DigestAlgorithm.SHA256 .
        :return: The related public key name.
        :rtype: Signature
        """
        keyName = IdentityCertificate.certificateNameToPublicKeyName(
            certificateName)
        publicKey = self._privateKeyStorage.getPublicKey(keyName)
        keyType = publicKey.getKeyType()

        if keyType == KeyType.RSA:
            signature = Sha256WithRsaSignature()
            digestAlgorithm[0] = DigestAlgorithm.SHA256

            signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
            signature.getKeyLocator().setKeyName(certificateName.getPrefix(-1))

            return signature
        elif keyType == KeyType.ECDSA:
            signature = Sha256WithEcdsaSignature()
            digestAlgorithm[0] = DigestAlgorithm.SHA256

            signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
            signature.getKeyLocator().setKeyName(certificateName.getPrefix(-1))

            return signature
        else:
            raise SecurityException("Key type is not recognized")
Beispiel #5
0
    def setDefaultCertificateNameForKey(self, keyName, certificateName):        
        """
        Set the default certificate name for the corresponding key
                
        :param Name keyName: not used
        :param Name certificateName: The certificate name.
        """
        
        if not self.doesCertificateExist(certificateName):
            raise SecurityException("Certificate does not exist")

        keyName = IdentityCertificate.certificateNameToPublicKeyName(certificateName)
        identityUri = keyName.getPrefix(-1).toUri()
        keyId = keyName.get(-1).toEscapedString()

        try:
            cursor = None
            currentDefault = self.getDefaultCertificateNameForKey(keyName)
        except SecurityException:
            pass
        else:
            cursor = self._database.cursor()
            cursor.execute("UPDATE Certificate SET default_cert=0 WHERE cert_name=? AND identity_name=? AND key_identifier=?",
                (currentDefault.toUri(), identityUri, keyId))

        if cursor is None:
            cursor = self._database.cursor()
        
        cursor.execute("UPDATE Certificate SET default_cert=1 WHERE cert_name=? AND identity_name=? AND key_identifier=?",
                (certificateName.toUri(), identityUri, keyId))

        self._database.commit()
        cursor.close()
Beispiel #6
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
    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/zhehao")

        # 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
Beispiel #8
0
    def _updateDeviceCapabilities(self, interest):
        """
        Take the received capabilities update interest and update our directory listings.
        """
        # we assume the sender is the one who signed the interest...
        signature = self._policyManager._extractSignature(interest)
        certificateName = signature.getKeyLocator().getKeyName()
        senderIdentity = IdentityCertificate.certificateNameToPublicKeyName(
            certificateName).getPrefix(-1)

        self.log.info('Updating capabilities for {}'.format(
            senderIdentity.toUri()))

        # get the params from the interest name
        messageComponent = interest.getName().get(self.prefix.size() + 1)
        message = UpdateCapabilitiesCommandMessage()
        ProtobufTlv.decode(message, messageComponent.getValue())
        # we remove all the old capabilities for the sender
        tempDirectory = defaultdict(list)
        for keyword in self._directory:
            tempDirectory[keyword] = [
                cap for cap in self._directory[keyword]
                if not senderIdentity.match(Name(cap['name']))
            ]

        # then we add the ones from the message
        for capability in message.capabilities:
            capabilityPrefix = Name()
            for component in capability.commandPrefix.components:
                capabilityPrefix.append(component)
            commandUri = capabilityPrefix.toUri()
            if not senderIdentity.match(capabilityPrefix):
                self.log.error(
                    "Node {} tried to register another prefix: {} - ignoring update"
                    .format(senderIdentity.toUri(), commandUri))
            else:
                for keyword in capability.keywords:
                    allUris = [info['name'] for info in tempDirectory[keyword]]
                    if capabilityPrefix not in allUris:
                        listing = {
                            'signed': capability.needsSignature,
                            'name': commandUri
                        }
                        tempDirectory[keyword].append(listing)
        self._directory = tempDirectory
Beispiel #9
0
    def createIdentity(self, identityName, params):
        """
        Create an identity by creating a pair of Key-Signing-Key (KSK) for this
        identity and a self-signed certificate of the KSK. If a key pair or
        certificate for the identity already exists, use it.

        :deprecated: Use createIdentityAndCertificate which returns the
          certificate name instead of the key name. You can use
          IdentityCertificate.certificateNameToPublicKeyName to convert the
          certificate name to the key name.
        :param Name identityName: The name of the identity.
        :param KeyParams params: The key parameters if a key needs to be
          generated for the identity.
        :return: The key name of the auto-generated KSK of the identity.
        :rtype: Name
        """
        return IdentityCertificate.certificateNameToPublicKeyName(
          self.createIdentityAndCertificate(identityName, params))
Beispiel #10
0
    def createIdentity(self, identityName, params):
        """
        Create an identity by creating a pair of Key-Signing-Key (KSK) for this
        identity and a self-signed certificate of the KSK. If a key pair or
        certificate for the identity already exists, use it.

        :deprecated: Use createIdentityAndCertificate which returns the
          certificate name instead of the key name. You can use
          IdentityCertificate.certificateNameToPublicKeyName to convert the
          certificate name to the key name.
        :param Name identityName: The name of the identity.
        :param KeyParams params: The key parameters if a key needs to be
          generated for the identity.
        :return: The key name of the auto-generated KSK of the identity.
        :rtype: Name
        """
        return IdentityCertificate.certificateNameToPublicKeyName(
            self.createIdentityAndCertificate(identityName, params))
Beispiel #11
0
    def signInterestByCertificate(self,
                                  interest,
                                  certificateName,
                                  wireFormat=None):
        """
        Append a SignatureInfo to the Interest name, sign the name components
        and append a final name component with the signature bits.

        :param Interest interest: The Interest object to be signed. This appends
          name components of SignatureInfo and the signature bits.
        :param Name certificateName: The certificate name of the key to use for
          signing.
        :param wireFormat: (optional) A WireFormat object used to encode the
           input. If omitted, use WireFormat.getDefaultWireFormat().
        :type wireFormat: A subclass of WireFormat
        """
        if wireFormat == None:
            # Don't use a default argument since getDefaultWireFormat can change.
            wireFormat = WireFormat.getDefaultWireFormat()

        digestAlgorithm = [0]
        signature = self._makeSignatureByCertificate(certificateName,
                                                     digestAlgorithm)

        # Append the encoded SignatureInfo.
        interest.getName().append(wireFormat.encodeSignatureInfo(signature))

        # Append an empty signature so that the "signedPortion" is correct.
        interest.getName().append(Name.Component())
        # Encode once to get the signed portion, and sign.
        encoding = interest.wireEncode(wireFormat)
        signature.setSignature(
            self._privateKeyStorage.sign(
                encoding.toSignedBuffer(),
                IdentityCertificate.certificateNameToPublicKeyName(
                    certificateName), digestAlgorithm[0]))

        # Remove the empty signature and append the real one.
        interest.setName(interest.getName().getPrefix(-1).append(
            wireFormat.encodeSignatureValue(signature)))
Beispiel #12
0
    def _updateDeviceCapabilities(self, interest):
        """
        Take the received capabilities update interest and update our directory listings.
        """
        # we assume the sender is the one who signed the interest...
        signature = self._policyManager._extractSignature(interest)
        certificateName = signature.getKeyLocator().getKeyName()
        senderIdentity = IdentityCertificate.certificateNameToPublicKeyName(certificateName).getPrefix(-1)

        self.log.info('Updating capabilities for {}'.format(senderIdentity.toUri()))

        # get the params from the interest name
        messageComponent = interest.getName().get(self.prefix.size()+1)
        message = UpdateCapabilitiesCommandMessage()
        ProtobufTlv.decode(message, messageComponent.getValue())
        # we remove all the old capabilities for the sender
        tempDirectory = defaultdict(list)
        for keyword in self._directory:
            tempDirectory[keyword] = [cap for cap in self._directory[keyword] 
                    if not senderIdentity.match(Name(cap['name']))]

        # then we add the ones from the message
        for capability in message.capabilities:
            capabilityPrefix = Name()
            for component in capability.commandPrefix.components:
                capabilityPrefix.append(component)
            commandUri = capabilityPrefix.toUri()
            if not senderIdentity.match(capabilityPrefix):
                self.log.error("Node {} tried to register another prefix: {} - ignoring update".format(
                    senderIdentity.toUri(),commandUri))
            else:    
                for keyword in capability.keywords:
                    allUris = [info['name'] for info in tempDirectory[keyword]]
                    if capabilityPrefix not in allUris:
                        listing = {'signed':capability.needsSignature,
                                'name':commandUri}
                        tempDirectory[keyword].append(listing)
        self._directory= tempDirectory
Beispiel #13
0
    def signInterestByCertificate(self, interest, certificateName, wireFormat = None):
        """
        Append a SignatureInfo to the Interest name, sign the name components
        and append a final name component with the signature bits.

        :param Interest interest: The Interest object to be signed. This appends
          name components of SignatureInfo and the signature bits.
        :param Name certificateName: The certificate name of the key to use for
          signing.
        :param wireFormat: (optional) A WireFormat object used to encode the
           input. If omitted, use WireFormat.getDefaultWireFormat().
        :type wireFormat: A subclass of WireFormat
        """
        if wireFormat == None:
            # Don't use a default argument since getDefaultWireFormat can change.
            wireFormat = WireFormat.getDefaultWireFormat()

        digestAlgorithm = [0]
        signature = self._makeSignatureByCertificate(
          certificateName, digestAlgorithm)

        # Append the encoded SignatureInfo.
        interest.getName().append(wireFormat.encodeSignatureInfo(signature))

        # Append an empty signature so that the "signedPortion" is correct.
        interest.getName().append(Name.Component())
        # Encode once to get the signed portion, and sign.
        encoding = interest.wireEncode(wireFormat)
        signature.setSignature(self._privateKeyStorage.sign
          (encoding.toSignedBuffer(),
           IdentityCertificate.certificateNameToPublicKeyName(certificateName),
           digestAlgorithm[0]))

        # Remove the empty signature and append the real one.
        interest.setName(interest.getName().getPrefix(-1).append(
          wireFormat.encodeSignatureValue(signature)))
Beispiel #14
0
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)):
#        print int(decoded[i])
face = Face()
face.setCommandSigningInfo(keyChain, certificateName)
certificateNamePrefix = Name(identityName).append("KEY")
    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
Beispiel #16
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
Beispiel #17
0
    def __init__(self, face, encryptResult, defaultPrefix, 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(defaultPrefix)

        # 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.memoryContentCache = MemoryContentCache(self.face)

        try:
            commandSigningKeyChain = KeyChain()
            print "Default certificate name is: " + self.keyChain.getDefaultCertificateName().toUri()
            self.face.setCommandSigningInfo(commandSigningKeyChain, commandSigningKeyChain.getDefaultCertificateName())
            self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
        except SecurityException as e:
            print str(e)
            print "Cannot use default certificate, use created certificate in FilePrivateKeyStorage"
            self.face.setCommandSigningInfo(self.keyChain, self.certificateName)
            self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)

        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.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