Esempio n. 1
0
    def encodeEncryptedContent(self, encryptedContent):
        """
        Encode the EncryptedContent in NDN-TLV and return the encoding.

        :param EncryptedContent encryptedContent: The EncryptedContent object to
          encode.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeBlobTlv(
          Tlv.Encrypt_EncryptedPayload, encryptedContent.getPayload().buf())
        encoder.writeOptionalBlobTlv(
          Tlv.Encrypt_InitialVector, encryptedContent.getInitialVector().buf())
        # Assume the algorithmType value is the same as the TLV type.
        encoder.writeNonNegativeIntegerTlv(
          Tlv.Encrypt_EncryptionAlgorithm, encryptedContent.getAlgorithmType())
        Tlv0_1_1WireFormat._encodeKeyLocator(
          Tlv.KeyLocator, encryptedContent.getKeyLocator(), encoder)

        encoder.writeTypeAndLength(
          Tlv.Encrypt_EncryptedContent, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 2
0
    def wireEncode(self):
        """
        Encode this Schedule.

        :return: The encoded buffer.
        :rtype: Blob
        """
        # For now, don't use WireFormat and hardcode to use TLV since the
        # encoding doesn't go out over the wire, only into the local SQL database.
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        # Encode the blackIntervalList.
        saveLengthForList = len(encoder)
        for i in range(len(self._blackIntervalList) - 1, -1, -1):
            Schedule._encodeRepetitiveInterval(self._blackIntervalList[i],
                                               encoder)
        encoder.writeTypeAndLength(Tlv.Encrypt_BlackIntervalList,
                                   len(encoder) - saveLengthForList)

        # Encode the whiteIntervalList.
        saveLengthForList = len(encoder)
        for i in range(len(self._whiteIntervalList) - 1, -1, -1):
            Schedule._encodeRepetitiveInterval(self._whiteIntervalList[i],
                                               encoder)
        encoder.writeTypeAndLength(Tlv.Encrypt_WhiteIntervalList,
                                   len(encoder) - saveLengthForList)

        encoder.writeTypeAndLength(Tlv.Encrypt_Schedule,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 3
0
    def encodeData(self, data):
        """
        Encode data in NDN-TLV and return the encoding and signed offsets.

        :param Data data: The Data object to encode.
        :return: A Tuple of (encoding, signedPortionBeginOffset,
          signedPortionEndOffset) where encoding is a Blob containing the
          encoding, signedPortionBeginOffset is the offset in the encoding of
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion.
        :rtype: (Blob, int, int)
        """
        encoder = TlvEncoder(1500)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeBlobTlv(Tlv.SignatureValue,
                             data.getSignature().getSignature().buf())
        signedPortionEndOffsetFromBack = len(encoder)

        self._encodeSignatureInfo(data.getSignature(), encoder)
        encoder.writeBlobTlv(Tlv.Content, data.getContent().buf())
        self._encodeMetaInfo(data.getMetaInfo(), encoder)
        self._encodeName(data.getName(), encoder)
        signedPortionBeginOffsetFromBack = len(encoder)

        encoder.writeTypeAndLength(Tlv.Data, len(encoder) - saveLength)
        signedPortionBeginOffset = (len(encoder) -
                                    signedPortionBeginOffsetFromBack)
        signedPortionEndOffset = len(encoder) - signedPortionEndOffsetFromBack

        return (Blob(encoder.getOutput(),
                     False), signedPortionBeginOffset, signedPortionEndOffset)
Esempio n. 4
0
    def encodeName(self, name):
        """
        Encode name in NDN-TLV and return the encoding.

        :param Name name: The Name object to encode.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        self._encodeName(name, encoder)
        return Blob(encoder.getOutput(), False)
Esempio n. 5
0
    def encodeName(self, name):
        """
        Encode name in NDN-TLV and return the encoding.

        :param Name name: The Name object to encode.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        self._encodeName(name, encoder)
        return Blob(encoder.getOutput(), False)
Esempio n. 6
0
    def encodeControlParameters(self, controlParameters):
        """
        Encode controlParameters and return the encoding.

        :param controlParameters: The ControlParameters object to encode.
        :type controlParameters: ControlParameters
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        self._encodeControlParameters(controlParameters, encoder)
        return Blob(encoder.getOutput(), False)
Esempio n. 7
0
        def fromNumber(number):
            """
            Create a component whose value is the nonNegativeInteger encoding of
            the number.

            :param int number: The number to be encoded.
            :return: The component value.
            :rtype: Name.Component
            """
            encoder = TlvEncoder(8)
            encoder.writeNonNegativeInteger(number)
            return Name.Component(Blob(encoder.getOutput(), False))
    def wireEncode(self):
        #    if self.m_wire.hasWire():
        #       return m_wire;

        #    EncodingEstimator estimator;
        #    size_t estimatedSize = wireEncode(estimator);

        buffer = TlvEncoder()

        # Ummm, this is not how polymorphism should look
        self.wireEncodeX(buffer)
        output = buffer.getOutput()
        return Blob((output), False)
    def wireEncode(self):
    #    if self.m_wire.hasWire():
    #       return m_wire;

    #    EncodingEstimator estimator;
    #    size_t estimatedSize = wireEncode(estimator);

        buffer = TlvEncoder()
        
        # Ummm, this is not how polymorphism should look
        self.wireEncodeX(buffer)
        output = buffer.getOutput()
        return Blob((output), False)
Esempio n. 10
0
    def encodeSignatureInfo(self, signature):
        """
        Encode signature as an NDN-TLV SignatureInfo and return the encoding.

        :param signature: An object of a subclass of Signature to encode.
        :type signature: An object of a subclass of Signature
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        self._encodeSignatureInfo(signature, encoder)

        return Blob(encoder.getOutput(), False)
Esempio n. 11
0
    def encodeSignatureInfo(self, signature):
        """
        Encode signature as an NDN-TLV SignatureInfo and return the encoding.

        :param signature: An object of a subclass of Signature to encode.
        :type signature: An object of a subclass of Signature
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        self._encodeSignatureInfo(signature, encoder)

        return Blob(encoder.getOutput(), False)
Esempio n. 12
0
    def encodeData(self, data):
        """
        Encode data in NDN-TLV and return the encoding and signed offsets.

        :param Data data: The Data object to encode.
        :return: A Tuple of (encoding, signedPortionBeginOffset,
          signedPortionEndOffset) where encoding is a Blob containing the
          encoding, signedPortionBeginOffset is the offset in the encoding of
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion.
        :rtype: (Blob, int, int)
        """
        encoder = TlvEncoder(1500)
        saveLength = len(encoder)

        # Encode backwards.
        # TODO: The library needs to handle other signature types than
        #   SignatureSha256WithRsa.
        encoder.writeBlobTlv(Tlv.SignatureValue,
                             data.getSignature().getSignature().buf())
        signedPortionEndOffsetFromBack = len(encoder)

        self._encodeSignatureSha256WithRsa(data.getSignature(), encoder)
        encoder.writeBlobTlv(Tlv.Content, data.getContent().buf())
        self._encodeMetaInfo(data.getMetaInfo(), encoder)
        self._encodeName(data.getName(), encoder)
        signedPortionBeginOffsetFromBack = len(encoder)

        encoder.writeTypeAndLength(Tlv.Data, len(encoder) - saveLength)
        signedPortionBeginOffset = (len(encoder) -
                                    signedPortionBeginOffsetFromBack)
        signedPortionEndOffset = len(encoder) - signedPortionEndOffsetFromBack

        return (Blob(encoder.getOutput(), False), signedPortionBeginOffset,
                signedPortionEndOffset)
Esempio n. 13
0
    def encodeControlResponse(self, controlResponse):
        """
        Encode controlResponse and return the encoding.

        :param controlResponse: The ControlResponse object to encode.
        :type controlResponse: ControlResponse
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.

        # Encode the body.
        if controlResponse.getBodyAsControlParameters() != None:
            self._encodeControlParameters(
              controlResponse.getBodyAsControlParameters(), encoder)

        encoder.writeBlobTlv(
          Tlv.NfdCommand_StatusText, Blob(controlResponse.getStatusText()).buf())
        encoder.writeNonNegativeIntegerTlv(
          Tlv.NfdCommand_StatusCode, controlResponse.getStatusCode())

        encoder.writeTypeAndLength(Tlv.NfdCommand_ControlResponse,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 14
0
    def wireEncode(self):
        """
        Encode this Schedule.

        :return: The encoded buffer.
        :rtype: Blob
        """
        # For now, don't use WireFormat and hardcode to use TLV since the
        # encoding doesn't go out over the wire, only into the local SQL database.
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        # Encode the blackIntervalList.
        saveLengthForList = len(encoder)
        for i in range(len(self._blackIntervalList) - 1, -1, -1):
            Schedule._encodeRepetitiveInterval(self._blackIntervalList[i], encoder)
        encoder.writeTypeAndLength(Tlv.Encrypt_BlackIntervalList, len(encoder) - saveLengthForList)

        # Encode the whiteIntervalList.
        saveLengthForList = len(encoder)
        for i in range(len(self._whiteIntervalList) - 1, -1, -1):
            Schedule._encodeRepetitiveInterval(self._whiteIntervalList[i], encoder)
        encoder.writeTypeAndLength(Tlv.Encrypt_WhiteIntervalList, len(encoder) - saveLengthForList)

        encoder.writeTypeAndLength(Tlv.Encrypt_Schedule, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 15
0
    def encodeSignatureValue(self, signature):
        """
        Encode the signatureValue in the Signature object as an NDN-TLV
        SignatureValue (the signature bits) and return the encoding.

        :param signature: An object of a subclass of Signature with the
          signature value to encode.
        :type signature: An object of a subclass of Signature
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        encoder.writeBlobTlv(Tlv.SignatureValue, signature.getSignature().buf())

        return Blob(encoder.getOutput(), False)
    def generate(self, interest, keyChain, certificateName, wireFormat = None):
        """
        Append a timestamp component and a random value component to interest's
        name. This ensures that the timestamp is greater than the timestamp used 
        in the previous call. Then use keyChain to sign the interest which 
        appends a SignatureInfo component and a component with the signature 
        bits. If the interest lifetime is not set, this sets it.

        :param Interest interest: The interest whose name is append with 
          components.
        :param KeyChain keyChain: The KeyChain for calling sign.
        :param Name certificateName: The certificate name of the key to use for 
          signing.
        :param wireFormat: (optional) A WireFormat object used to encode the 
          SignatureInfo and to encode interest name for signing. 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()

        timestamp =  round(Common.getNowMilliseconds())
        while timestamp <= self._lastTimestamp:
          timestamp += 1.0

        # The timestamp is encoded as a TLV nonNegativeInteger.
        encoder = TlvEncoder(8)
        encoder.writeNonNegativeInteger(int(timestamp))
        interest.getName().append(Blob(encoder.getOutput(), False))
        
        # The random value is a TLV nonNegativeInteger too, but we know it is 8 
        # bytes, so we don't need to call the nonNegativeInteger encoder.        
        randomBuffer = bytearray(8)
        for i in range(len(randomBuffer)):
            randomBuffer[i] = _systemRandom.randint(0, 0xff)                
        interest.getName().append(Blob(randomBuffer, False))

        keyChain.sign(interest, certificateName, wireFormat)

        if (interest.getInterestLifetimeMilliseconds() == None or
            interest.getInterestLifetimeMilliseconds()< 0):
          # The caller has not set the interest lifetime, so set it here.
          interest.setInterestLifetimeMilliseconds(1000.0)

        # We successfully signed the interest, so update the timestamp.
        self._lastTimestamp = timestamp
        
Esempio n. 17
0
        def fromNumberWithMarker(number, marker):
            """
            Create a component whose value is the marker appended with the
            nonNegativeInteger encoding of the number.

            :param int number: The number to be encoded.
            :param int marker: The marker to use as the first byte of the
              component.
            :return: The component value.
            :rtype: Name.Component
            """
            encoder = TlvEncoder(9)
            # Encode backwards.
            encoder.writeNonNegativeInteger(number)
            encoder.writeNonNegativeInteger(marker)
            return Name.Component(Blob(encoder.getOutput(), False))
Esempio n. 18
0
    def encodeSignatureValue(self, signature):
        """
        Encode the signatureValue in the Signature object as an NDN-TLV
        SignatureValue (the signature bits) and return the encoding.

        :param signature: An object of a subclass of Signature with the
          signature value to encode.
        :type signature: An object of a subclass of Signature
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        encoder.writeBlobTlv(Tlv.SignatureValue,
                             signature.getSignature().buf())

        return Blob(encoder.getOutput(), False)
Esempio n. 19
0
        def fromNumberWithMarker(number, marker):
            """
            Create a component whose value is the marker appended with the
            nonNegativeInteger encoding of the number.

            :param int number: The number to be encoded.
            :param int marker: The marker to use as the first byte of the
              component.
            :return: The component value.
            :rtype: Name.Component
            """
            encoder = TlvEncoder(9)
            # Encode backwards.
            encoder.writeNonNegativeInteger(number)
            encoder.writeNonNegativeInteger(marker)
            return Name.Component(Blob(encoder.getOutput(), False))
Esempio n. 20
0
    def encode(message):
        """
        Encode the Protobuf message object as NDN-TLV.

        :param google.protobuf.message message: The Protobuf message object.
          This calls message.IsInitialized() to ensure that all required fields
          are present and raises an exception if not.
        :return: The encoded buffer in a Blob object.
        :rtype: Blob
        """
        if not message.IsInitialized():
            raise RuntimeError("message is not initialized")
        encoder = TlvEncoder(256)

        ProtobufTlv._encodeMessageValue(message, encoder)
        return Blob(encoder.getOutput(), False)
Esempio n. 21
0
    def encode(message):
        """
        Encode the Protobuf message object as NDN-TLV.

        :param google.protobuf.message message: The Protobuf message object.
          This calls message.IsInitialized() to ensure that all required fields
          are present and raises an exception if not.
        :return: The encoded buffer in a Blob object.
        :rtype: Blob
        """
        if not message.IsInitialized():
            raise RuntimeError("message is not initialized")
        encoder = TlvEncoder(256)

        ProtobufTlv._encodeMessageValue(message, encoder)
        return Blob(encoder.getOutput(), False)
Esempio n. 22
0
    def generate(self, interest, keyChain, certificateName, wireFormat=None):
        """
        Append a timestamp component and a random value component to interest's
        name. This ensures that the timestamp is greater than the timestamp used
        in the previous call. Then use keyChain to sign the interest which
        appends a SignatureInfo component and a component with the signature
        bits. If the interest lifetime is not set, this sets it.

        :param Interest interest: The interest whose name is append with
          components.
        :param KeyChain keyChain: The KeyChain for calling sign.
        :param Name certificateName: The certificate name of the key to use for
          signing.
        :param wireFormat: (optional) A WireFormat object used to encode the
          SignatureInfo and to encode interest name for signing. 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()

        timestamp = round(Common.getNowMilliseconds())
        while timestamp <= self._lastTimestamp:
            timestamp += 1.0

        # The timestamp is encoded as a TLV nonNegativeInteger.
        encoder = TlvEncoder(8)
        encoder.writeNonNegativeInteger(int(timestamp))
        interest.getName().append(Blob(encoder.getOutput(), False))

        # The random value is a TLV nonNegativeInteger too, but we know it is 8
        # bytes, so we don't need to call the nonNegativeInteger encoder.
        randomBuffer = bytearray(8)
        for i in range(len(randomBuffer)):
            randomBuffer[i] = _systemRandom.randint(0, 0xff)
        interest.getName().append(Blob(randomBuffer, False))

        keyChain.sign(interest, certificateName, wireFormat)

        if (interest.getInterestLifetimeMilliseconds() == None
                or interest.getInterestLifetimeMilliseconds() < 0):
            # The caller has not set the interest lifetime, so set it here.
            interest.setInterestLifetimeMilliseconds(1000.0)

        # We successfully signed the interest, so update the timestamp.
        self._lastTimestamp = timestamp
Esempio n. 23
0
    def wireEncode(self):
        """
        Encode this as an NDN-TLV PSyncContent.

        :return: The encoding as a Blob.
        :rtype: Blob
        """
        # Encode directly as TLV. We don't support the WireFormat abstraction
        # because this isn't meant to go directly on the wire.
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        for i in range(len(self._content) - 1, -1, -1):
            Tlv0_3WireFormat._encodeName(self._content[i], encoder)

        encoder.writeTypeAndLength(
          PSyncState.Tlv_PSyncContent, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 24
0
    def _encodeLpNack(interest, networkNack):
        """
        Encode the interest into an NDN-TLV LpPacket as a NACK with the reason
        code in the networkNack object.
        TODO: Generalize this and move to WireFormat.encodeLpPacket.
        
        :param Interest interest: The Interest to put in the LpPacket fragment.
        :param NetworkNack networkNack: The NetworkNack with the reason code.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        # Encode the fragment with the Interest.
        encoder.writeBlobTlv(
          Tlv.LpPacket_Fragment, interest.wireEncode(TlvWireFormat.get()).buf())

        # Encode the reason.
        if (networkNack.getReason() == NetworkNack.Reason.NONE or
             networkNack.getReason() == NetworkNack.Reason.CONGESTION or
             networkNack.getReason() == NetworkNack.Reason.DUPLICATE or
             networkNack.getReason() == NetworkNack.Reason.NO_ROUTE):
            # The Reason enum is set up with the correct integer for each NDN-TLV Reason.
            reason = networkNack.getReason()
        elif networkNack.getReason() == NetworkNack.Reason.OTHER_CODE:
            reason = networkNack.getOtherReasonCode()
        else:
            # We don't expect this to happen.
            raise RuntimeError("unrecognized NetworkNack.getReason() value")

        nackSaveLength = len(encoder)
        encoder.writeNonNegativeIntegerTlv(Tlv.LpPacket_NackReason, reason)
        encoder.writeTypeAndLength(
          Tlv.LpPacket_Nack, len(encoder) - nackSaveLength)

        encoder.writeTypeAndLength(
          Tlv.LpPacket_LpPacket, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 25
0
        def fromNumber(number, type=None, otherTypeCode=None):
            """
            Create a component whose value is the nonNegativeInteger encoding of
            the number.

            :param int number: The number to be encoded.
            :param int type: (optional) The component type as an int from the
              ComponentType enum. If name component type is not a recognized
              ComponentType enum value, then set this to ComponentType.OTHER_CODE
              and use the otherTypeCode parameter. If omitted, use
              ComponentType.GENERIC.
            :param int otherTypeCode: (optional) If type is
              ComponentType.OTHER_CODE, then this is the packet's unrecognized
              content type code, which must be non-negative.
            :return: The new component value.
            :rtype: Name.Component
            """
            encoder = TlvEncoder(8)
            encoder.writeNonNegativeInteger(number)
            return Name.Component(Blob(encoder.getOutput(), False), type,
                                  otherTypeCode)
Esempio n. 26
0
    def encodeDelegationSet(self, delegationSet):
        """
        Encode the DelegationSet in NDN-TLV and return the encoding. Note that
        the sequence of Delegation does not have an outer TLV type and length
        because it is intended to use the type and length of a Data packet's
        Content.

        :param DelegationSet delegationSet: The DelegationSet object to
          encode.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)

        # Encode backwards.
        for i in range(delegationSet.size() - 1, -1, -1):
            saveLength = len(encoder)

            Tlv0_1_1WireFormat._encodeName(delegationSet.get(i).getName(), encoder)
            encoder.writeNonNegativeIntegerTlv(
              Tlv.Link_Preference, delegationSet.get(i).getPreference())

            encoder.writeTypeAndLength(
              Tlv.Link_Delegation, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
    def wireEncode(self):
        encoder = TlvEncoder(500)
        saveLength = len(encoder)
        
        # if self.getValidityPeriod().hasPeriod():
        #     Tlv0_2WireFormat._encodeValidityPeriod(self.getValidityPeriod(), encoder)
        Tlv0_2WireFormat._encodeKeyLocator(Tlv.KeyLocator, self.getKeyLocator(), encoder)
        encoder.writeNonNegativeIntegerTlv(Tlv.SignatureType, Tlv.SignatureType_Sha256WithAbsSignature)
        encoder.writeTypeAndLength(Tlv.SignatureInfo, len(encoder) - saveLength)

        self.setSignatureInfoEncoding(Blob(encoder.getOutput(), False), Tlv.SignatureType_Sha256WithAbsSignature)
Esempio n. 28
0
    def _signInterest(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()

        # TODO: Handle signature algorithms other than Sha256WithRsa.
        signature = Sha256WithRsaSignature()
        signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        signature.getKeyLocator().setKeyName(certificateName.getPrefix(-1))

        # 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.
        encoding = interest.wireEncode(wireFormat)
        signedSignature = self.sign(encoding.toSignedBuffer(), certificateName)

        # Remove the empty signature and append the real one.
        encoder = TlvEncoder(256)
        encoder.writeBlobTlv(
          Tlv.SignatureValue, signedSignature.getSignature().buf())
        interest.setName(interest.getName().getPrefix(-1).append(
          wireFormat.encodeSignatureValue(signedSignature)))
Esempio n. 29
0
    def _signInterest(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()

        # TODO: Handle signature algorithms other than Sha256WithRsa.
        signature = Sha256WithRsaSignature()
        signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
        signature.getKeyLocator().setKeyName(certificateName.getPrefix(-1))

        # 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.
        encoding = interest.wireEncode(wireFormat)
        signedSignature = self.sign(encoding.toSignedBuffer(), certificateName)

        # Remove the empty signature and append the real one.
        encoder = TlvEncoder(256)
        encoder.writeBlobTlv(Tlv.SignatureValue,
                             signedSignature.getSignature().buf())
        interest.setName(interest.getName().getPrefix(-1).append(
            wireFormat.encodeSignatureValue(signedSignature)))
    def prepareCommandInterestName(self, interest, wireFormat = None):
        """
        Append a timestamp component and a random nonce component to interest's
        name. This ensures that the timestamp is greater than the timestamp used
        in the previous call.

        :param Interest interest: The interest whose name is append with
          components.
        :param WireFormat wireFormat: (optional) A WireFormat object used to
          encode the SignatureInfo. If omitted, use WireFormat
          getDefaultWireFormat().
        """
        if wireFormat == None:
            wireFormat = WireFormat.getDefaultWireFormat()

        # _nowOffsetMilliseconds is only used for testing.
        now = Common.getNowMilliseconds() + self._nowOffsetMilliseconds
        timestamp =  round(now)
        while timestamp <= self._lastUsedTimestamp:
          timestamp += 1.0

        # Update the timestamp now. In the small chance that signing fails, it
        # just means that we have bumped the timestamp.
        self._lastUsedTimestamp = timestamp

        # The timestamp is encoded as a TLV nonNegativeInteger.
        encoder = TlvEncoder(8)
        encoder.writeNonNegativeInteger(int(timestamp))
        interest.getName().append(Blob(encoder.getOutput(), False))

        # The random value is a TLV nonNegativeInteger too, but we know it is 8
        # bytes, so we don't need to call the nonNegativeInteger encoder.
        randomBuffer = bytearray(8)
        for i in range(len(randomBuffer)):
            randomBuffer[i] = _systemRandom.randint(0, 0xff)
        interest.getName().append(Blob(randomBuffer, False))
Esempio n. 31
0
    def prepareCommandInterestName(self, interest, wireFormat=None):
        """
        Append a timestamp component and a random nonce component to interest's
        name. This ensures that the timestamp is greater than the timestamp used
        in the previous call.

        :param Interest interest: The interest whose name is append with
          components.
        :param WireFormat wireFormat: (optional) A WireFormat object used to
          encode the SignatureInfo. If omitted, use WireFormat
          getDefaultWireFormat().
        """
        if wireFormat == None:
            wireFormat = WireFormat.getDefaultWireFormat()

        # _nowOffsetMilliseconds is only used for testing.
        now = Common.getNowMilliseconds() + self._nowOffsetMilliseconds
        timestamp = round(now)
        while timestamp <= self._lastUsedTimestamp:
            timestamp += 1.0

        # Update the timestamp now. In the small chance that signing fails, it
        # just means that we have bumped the timestamp.
        self._lastUsedTimestamp = timestamp

        # The timestamp is encoded as a TLV nonNegativeInteger.
        encoder = TlvEncoder(8)
        encoder.writeNonNegativeInteger(int(timestamp))
        interest.getName().append(Blob(encoder.getOutput(), False))

        # The random value is a TLV nonNegativeInteger too, but we know it is 8
        # bytes, so we don't need to call the nonNegativeInteger encoder.
        randomBuffer = bytearray(8)
        for i in range(len(randomBuffer)):
            randomBuffer[i] = _systemRandom.randint(0, 0xff)
        interest.getName().append(Blob(randomBuffer, False))
Esempio n. 32
0
    def wireEncode(self, wireFormat=None):
        """
        Encode this as an NDN-TLV SafeBag.

        :return: The encoded byte array as a Blob.
        :rtype: Blob
        """
        # Encode directly as TLV. We don't support the WireFormat abstraction
        # because this isn't meant to go directly on the wire.
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeBlobTlv(Tlv.SafeBag_EncryptedKeyBag,
                             self._privateKeyBag.buf())
        # Add the entire Data packet encoding as is.
        encoder.writeBuffer(
            self._certificate.wireEncode(TlvWireFormat.get()).buf())

        encoder.writeTypeAndLength(Tlv.SafeBag_SafeBag,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 33
0
    def wireEncode(self, wireFormat = None):
        """
        Encode this as an NDN-TLV SafeBag.

        :return: The encoded byte array as a Blob.
        :rtype: Blob
        """
        # Encode directly as TLV. We don't support the WireFormat abstraction
        # because this isn't meant to go directly on the wire.
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeBlobTlv(
          Tlv.SafeBag_EncryptedKeyBag, self._privateKeyBag.buf())
        # Add the entire Data packet encoding as is.
        encoder.writeBuffer(
          self._certificate.wireEncode(TlvWireFormat.get()).buf())

        encoder.writeTypeAndLength(
          Tlv.SafeBag_SafeBag, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 34
0
    def encodeControlParameters(self, controlParameters):
        """
        Encode controlParameters and return the encoding.

        :param controlParameters: The ControlParameters object to encode.
        :type controlParameters: ControlParameters
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
            Tlv.ControlParameters_ExpirationPeriod,
            controlParameters.getExpirationPeriod())

        # TODO: Encode Strategy.

        flags = controlParameters.getForwardingFlags().getNfdForwardingFlags()
        if (flags != ForwardingFlags().getNfdForwardingFlags()):
            # The flags are not the default value.
            encoder.writeNonNegativeIntegerTlv(Tlv.ControlParameters_Flags,
                                               flags)

        encoder.writeOptionalNonNegativeIntegerTlv(Tlv.ControlParameters_Cost,
                                                   controlParameters.getCost())
        encoder.writeOptionalNonNegativeIntegerTlv(
            Tlv.ControlParameters_Origin, controlParameters.getOrigin())
        encoder.writeOptionalNonNegativeIntegerTlv(
            Tlv.ControlParameters_LocalControlFeature,
            controlParameters.getLocalControlFeature())

        # TODO: Encode Uri.

        encoder.writeOptionalNonNegativeIntegerTlv(
            Tlv.ControlParameters_FaceId, controlParameters.getFaceId())
        if controlParameters.getName().size() > 0:
            self._encodeName(controlParameters.getName(), encoder)

        encoder.writeTypeAndLength(Tlv.ControlParameters_ControlParameters,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 35
0
    def encodeForwardingEntry(self, forwardingEntry):
        """
        Encode forwardingEntry and return the encoding.

        :param forwardingEntry: The ForwardingEntry object to encode.
        :type forwardingEntry: ForwardingEntry
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
            Tlv.FreshnessPeriod, forwardingEntry.getFreshnessPeriod())
        encoder.writeNonNegativeIntegerTlv(
            Tlv.ForwardingFlags,
            forwardingEntry.getForwardingFlags().getForwardingEntryFlags())
        encoder.writeOptionalNonNegativeIntegerTlv(Tlv.FaceID,
                                                   forwardingEntry.getFaceId())
        self._encodeName(forwardingEntry.getPrefix(), encoder)
        if (forwardingEntry.getAction() != None
                and len(forwardingEntry.getAction()) > 0):
            # Convert str to a bytearray.
            encoder.writeBlobTlv(
                Tlv.Action, bytearray(forwardingEntry.getAction(), 'ascii'))

        encoder.writeTypeAndLength(Tlv.ForwardingEntry,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 36
0
    def onNewData(self, interest, data):
        """
        !! Again \n in public key??
        Got data:  {
            "ecdh-pub": "Aqxofe3QdsAfgbtS8TMxv31oudNKoSV307ci5gNXm88h\n",
            "salt": "12935684137560555161",
            "request-id": "14275252044236690531",
            "status": "0",
            "challenges": [
                {
                    "challenge-id": "Email"
                }
            ]
        }
        1. Verify data
        2. Derive shared secret
        """
        content = data.getContent()
        print("Got data: ", content)
        if not VerificationHelpers.verifyDataSignature(data, self.anchor):
            print("Cannot verify signature from: {}".format(self.caPrefix))
        else:
            print("Successfully verified data with hard-coded certificate")

        contentJson = json.loads(content.__str__())
        peerKeyBase64 = contentJson['ecdh-pub']
        self.status = contentJson['status']
        self.requestId = contentJson['request-id']
        self.challenges = contentJson['challenges']

        print(peerKeyBase64)

        serverPubKey = ec.EllipticCurvePublicKey.from_encoded_point(
            ec.SECP256R1(), b64decode(peerKeyBase64))

        shared_key = self.ecdh.private_key.exchange(ec.ECDH(), serverPubKey)
        derived_key = HKDF(algorithm=hashes.SHA256(),
                           length=32,
                           salt=contentJson['salt'].encode(),
                           info=b'handshake data',
                           backend=default_backend()).derive(shared_key)

        self.ecdh.derived_key = derived_key
        print(shared_key)
        for t in shared_key:
            print(t)

        challengeInterestName = Name(
            self.caPrefix).append("CA").append("_CHALLENGE").append(
                self.requestId)
        challengeInterest = Interest(challengeInterestName)
        challengeInterest.setMustBeFresh(True)
        challengeInterest.setCanBePrefix(False)

        # Encrypt the interest parameters
        challengeJson = json.dumps(
            {
                "selected-challenge": "Email",
                "email": "*****@*****.**"
            },
            indent=4)
        raw = self.pad(challengeJson, 16)
        print("raw", raw)
        iv = Random.new().read(AES.block_size)
        #cipher = AES.new(self.ecdh.derived_key, AES.MODE_CBC, iv)
        cipher = AES.new(shared_key, AES.MODE_CBC, iv)
        print(iv)
        xx = cipher.encrypt(raw)

        print(cipher.decrypt(xx))

        print("Printing iv:")
        for t in iv:
            print(t)

        encoder = TlvEncoder(256)
        saveLength = len(encoder)
        encoder.writeBlobTlv(632, iv)
        encoder.writeBlobTlv(630, cipher.encrypt(raw))
        #encoder.writeTypeAndLength(36, len(encoder) - saveLength)

        challengeInterest.setApplicationParameters(Blob(encoder.getOutput()))
        challengeInterest.appendParametersDigestToName()

        self.keyChain.sign(challengeInterest, SigningInfo(self.key))

        with open('foobar.tlv', 'wb') as f:
            f.write(challengeInterest.wireEncode().buf())
        self.face.expressInterest(challengeInterest, self.onChallengeData,
                                  self.onTimeout)
Esempio n. 37
0
    def encodeInterest(self, interest):
        """
        Encode interest in NDN-TLV and return the encoding.

        :param Interest interest: The Interest object to encode.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
          Tlv.InterestLifetime, interest.getInterestLifetimeMilliseconds())
        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.Scope, interest.getScope())

        # Encode the Nonce as 4 bytes.
        if interest.getNonce().size() == 0:
            # This is the most common case. Generate a nonce.
            nonce = bytearray(4)
            for i in range(4):
                nonce[i] = _systemRandom.randint(0, 0xff)
            encoder.writeBlobTlv(Tlv.Nonce, nonce)
        elif interest.getNonce().size() < 4:
            nonce = bytearray(4)
            # Copy existing nonce bytes.
            nonce[:interest.getNonce().size()] = interest.getNonce().buf()

            # Generate random bytes for remaining bytes in the nonce.
            for i in range(interest.getNonce().size(), 4):
                nonce[i] = _systemRandom.randint(0, 0xff)

            encoder.writeBlobTlv(Tlv.Nonce, nonce)
        elif interest.getNonce().size() == 4:
            # Use the nonce as-is.
            encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf())
        else:
            # Truncate.
            encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf()[:4])

        self._encodeSelectors(interest, encoder)
        self._encodeName(interest.getName(), encoder)

        encoder.writeTypeAndLength(Tlv.Interest, len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 38
0
    def encodeInterest(self, interest):
        """
        Encode interest in NDN-TLV and return the encoding.

        :param Interest interest: The Interest object to encode.
        :return: A Tuple of (encoding, signedPortionBeginOffset,
          signedPortionEndOffset) where encoding is a Blob containing the
          encoding, signedPortionBeginOffset is the offset in the encoding of
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion. The
          signed portion starts from the first name component and ends just
          before the final name component (which is assumed to be a signature
          for a signed interest).
        :rtype: (Blob, int, int)
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
          Tlv.InterestLifetime, interest.getInterestLifetimeMilliseconds())
        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.Scope, interest.getScope())

        # Encode the Nonce as 4 bytes.
        if interest.getNonce().size() == 0:
            # This is the most common case. Generate a nonce.
            nonce = bytearray(4)
            for i in range(4):
                nonce[i] = _systemRandom.randint(0, 0xff)
            encoder.writeBlobTlv(Tlv.Nonce, nonce)
        elif interest.getNonce().size() < 4:
            nonce = bytearray(4)
            # Copy existing nonce bytes.
            nonce[:interest.getNonce().size()] = interest.getNonce().buf()

            # Generate random bytes for remaining bytes in the nonce.
            for i in range(interest.getNonce().size(), 4):
                nonce[i] = _systemRandom.randint(0, 0xff)

            encoder.writeBlobTlv(Tlv.Nonce, nonce)
        elif interest.getNonce().size() == 4:
            # Use the nonce as-is.
            encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf())
        else:
            # Truncate.
            encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf()[:4])

        self._encodeSelectors(interest, encoder)

        (tempSignedPortionBeginOffset, tempSignedPortionEndOffset) = \
          self._encodeName(interest.getName(), encoder)
        signedPortionBeginOffsetFromBack = (len(encoder) -
                                            tempSignedPortionBeginOffset)
        signedPortionEndOffsetFromBack = (len(encoder) -
                                          tempSignedPortionEndOffset)

        encoder.writeTypeAndLength(Tlv.Interest, len(encoder) - saveLength)
        signedPortionBeginOffset = (len(encoder) -
                                    signedPortionBeginOffsetFromBack)
        signedPortionEndOffset = len(encoder) - signedPortionEndOffsetFromBack

        return (Blob(encoder.getOutput(), False), signedPortionBeginOffset,
                signedPortionEndOffset)
Esempio n. 39
0
    def encodeControlParameters(self, controlParameters):
        """
        Encode controlParameters and return the encoding.

        :param controlParameters: The ControlParameters object to encode.
        :type controlParameters: ControlParameters
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
          Tlv.ControlParameters_ExpirationPeriod,
          controlParameters.getExpirationPeriod())

        # TODO: Encode Strategy.

        flags = controlParameters.getForwardingFlags().getNfdForwardingFlags()
        if (flags != ForwardingFlags().getNfdForwardingFlags()):
            # The flags are not the default value.
            encoder.writeNonNegativeIntegerTlv(
              Tlv.ControlParameters_Flags, flags)

        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.ControlParameters_Cost, controlParameters.getCost())
        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.ControlParameters_Origin, controlParameters.getOrigin())
        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.ControlParameters_LocalControlFeature,
          controlParameters.getLocalControlFeature())

        # TODO: Encode Uri.

        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.ControlParameters_FaceId, controlParameters.getFaceId())
        if controlParameters.getName().size() > 0:
          self._encodeName(controlParameters.getName(), encoder)

        encoder.writeTypeAndLength(Tlv.ControlParameters_ControlParameters,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 40
0
    def encodeForwardingEntry(self, forwardingEntry):
        """
        Encode forwardingEntry and return the encoding.

        :param forwardingEntry: The ForwardingEntry object to encode.
        :type forwardingEntry: ForwardingEntry
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
          Tlv.FreshnessPeriod, forwardingEntry.getFreshnessPeriod())
        encoder.writeNonNegativeIntegerTlv(
          Tlv.ForwardingFlags,
          forwardingEntry.getForwardingFlags().getForwardingEntryFlags())
        encoder.writeOptionalNonNegativeIntegerTlv(
          Tlv.FaceID, forwardingEntry.getFaceId())
        self._encodeName(forwardingEntry.getPrefix(), encoder)
        if (forwardingEntry.getAction() != None and
             len(forwardingEntry.getAction()) > 0):
            # Convert str to a bytearray.
            encoder.writeBlobTlv(
              Tlv.Action, bytearray(forwardingEntry.getAction(), 'ascii'))

        encoder.writeTypeAndLength(Tlv.ForwardingEntry,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 41
0
    def encodeInterest(self, interest):
        """
        Encode interest in NDN-TLV and return the encoding.

        :param Interest interest: The Interest object to encode.
        :return: A Tuple of (encoding, signedPortionBeginOffset,
          signedPortionEndOffset) where encoding is a Blob containing the
          encoding, signedPortionBeginOffset is the offset in the encoding of
          the beginning of the signed portion, and signedPortionEndOffset is
          the offset in the encoding of the end of the signed portion. The
          signed portion starts from the first name component and ends just
          before the final name component (which is assumed to be a signature
          for a signed interest).
        :rtype: (Blob, int, int)
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        encoder.writeOptionalNonNegativeIntegerTlvFromFloat(
            Tlv.InterestLifetime, interest.getInterestLifetimeMilliseconds())
        encoder.writeOptionalNonNegativeIntegerTlv(Tlv.Scope,
                                                   interest.getScope())

        # Encode the Nonce as 4 bytes.
        if interest.getNonce().size() == 0:
            # This is the most common case. Generate a nonce.
            nonce = bytearray(4)
            for i in range(4):
                nonce[i] = _systemRandom.randint(0, 0xff)
            encoder.writeBlobTlv(Tlv.Nonce, nonce)
        elif interest.getNonce().size() < 4:
            nonce = bytearray(4)
            # Copy existing nonce bytes.
            nonce[:interest.getNonce().size()] = interest.getNonce().buf()

            # Generate random bytes for remaining bytes in the nonce.
            for i in range(interest.getNonce().size(), 4):
                nonce[i] = _systemRandom.randint(0, 0xff)

            encoder.writeBlobTlv(Tlv.Nonce, nonce)
        elif interest.getNonce().size() == 4:
            # Use the nonce as-is.
            encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf())
        else:
            # Truncate.
            encoder.writeBlobTlv(Tlv.Nonce, interest.getNonce().buf()[:4])

        self._encodeSelectors(interest, encoder)

        (tempSignedPortionBeginOffset, tempSignedPortionEndOffset) = \
          self._encodeName(interest.getName(), encoder)
        signedPortionBeginOffsetFromBack = (len(encoder) -
                                            tempSignedPortionBeginOffset)
        signedPortionEndOffsetFromBack = (len(encoder) -
                                          tempSignedPortionEndOffset)

        encoder.writeTypeAndLength(Tlv.Interest, len(encoder) - saveLength)
        signedPortionBeginOffset = (len(encoder) -
                                    signedPortionBeginOffsetFromBack)
        signedPortionEndOffset = len(encoder) - signedPortionEndOffsetFromBack

        return (Blob(encoder.getOutput(),
                     False), signedPortionBeginOffset, signedPortionEndOffset)
Esempio n. 42
0
    def _encodeLpNack(interest, networkNack):
        """
        Encode the interest into an NDN-TLV LpPacket as a NACK with the reason
        code in the networkNack object.
        TODO: Generalize this and move to WireFormat.encodeLpPacket.
        
        :param Interest interest: The Interest to put in the LpPacket fragment.
        :param NetworkNack networkNack: The NetworkNack with the reason code.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        # Encode the fragment with the Interest.
        encoder.writeBlobTlv(Tlv.LpPacket_Fragment,
                             interest.wireEncode(TlvWireFormat.get()).buf())

        # Encode the reason.
        if (networkNack.getReason() == NetworkNack.Reason.NONE
                or networkNack.getReason() == NetworkNack.Reason.CONGESTION
                or networkNack.getReason() == NetworkNack.Reason.DUPLICATE
                or networkNack.getReason() == NetworkNack.Reason.NO_ROUTE):
            # The Reason enum is set up with the correct integer for each NDN-TLV Reason.
            reason = networkNack.getReason()
        elif networkNack.getReason() == NetworkNack.Reason.OTHER_CODE:
            reason = networkNack.getOtherReasonCode()
        else:
            # We don't expect this to happen.
            raise RuntimeError("unrecognized NetworkNack.getReason() value")

        nackSaveLength = len(encoder)
        encoder.writeNonNegativeIntegerTlv(Tlv.LpPacket_NackReason, reason)
        encoder.writeTypeAndLength(Tlv.LpPacket_Nack,
                                   len(encoder) - nackSaveLength)

        encoder.writeTypeAndLength(Tlv.LpPacket_LpPacket,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 43
0
    def encodeStateVector(stateVector, stateVectorKeys):
        """
        Encode the stateVector as TLV.

        :param dict<str,int> stateVector: The state vector dictionary where
          the key is the member ID string and the value is the sequence number.
        :param list<str> stateVectorKeys: The key strings of stateVector,
          sorted in the order to be encoded.
        :return: A Blob containing the encoding.
        :rtype: Blob
        """
        encoder = TlvEncoder(256)
        saveLength = len(encoder)

        # Encode backwards.
        for i in range(len(stateVectorKeys) - 1, -1, -1):
            saveLengthForEntry = len(encoder)

            encoder.writeNonNegativeIntegerTlv(
                StateVectorSync2018.TLV_StateVector_SequenceNumber,
                stateVector[stateVectorKeys[i]])
            encoder.writeBlobTlv(StateVectorSync2018.TLV_StateVector_MemberId,
                                 Blob(stateVectorKeys[i]).buf())
            encoder.writeTypeAndLength(
                StateVectorSync2018.TLV_StateVectorEntry,
                len(encoder) - saveLengthForEntry)

        encoder.writeTypeAndLength(StateVectorSync2018.TLV_StateVector,
                                   len(encoder) - saveLength)

        return Blob(encoder.getOutput(), False)
Esempio n. 44
0
    def makeCommandInterest(self, name, params=None, wireFormat=None):
        """
        Append the timestamp and nonce name components to the supplied name,
        create an Interest object and signs it with the KeyChain given to the
        constructor. This ensures that the timestamp is greater than the
        timestamp used in the previous call.

        :param Name name: The Name for the Interest, which is copied.
        :param SigningInfo params: (optional) The signing parameters. If omitted,
          use a default SigningInfo().
        :param WireFormat wireFormat: (optional) A WireFormat object used to
          encode the SignatureInfo and to encode interest name for signing. If
          omitted, use WireFormat getDefaultWireFormat().
        :return: The new command Interest object.
        :rtype: Interest
        """
        arg2 = params
        arg3 = wireFormat
        if isinstance(arg2, SigningInfo):
            params = arg2
        else:
            params = None

        if isinstance(arg2, WireFormat):
            wireFormat = arg2
        elif isinstance(arg3, WireFormat):
            wireFormat = arg3
        else:
            wireFormat = None

        if params == None:
            params = SigningInfo()

        if wireFormat == None:
            wireFormat = WireFormat.getDefaultWireFormat()

        # This copies the Name.
        commandInterest = Interest(name)

        # _nowOffsetMilliseconds is only used for testing.
        now = Common.getNowMilliseconds() + self._nowOffsetMilliseconds
        timestamp = round(now)
        while timestamp <= self._lastUsedTimestamp:
            timestamp += 1.0

        # The timestamp is encoded as a TLV nonNegativeInteger.
        encoder = TlvEncoder(8)
        encoder.writeNonNegativeInteger(int(timestamp))
        commandInterest.getName().append(Blob(encoder.getOutput(), False))

        # The random value is a TLV nonNegativeInteger too, but we know it is 8
        # bytes, so we don't need to call the nonNegativeInteger encoder.
        randomBuffer = bytearray(8)
        for i in range(len(randomBuffer)):
            randomBuffer[i] = _systemRandom.randint(0, 0xff)
        commandInterest.getName().append(Blob(randomBuffer, False))

        self._keyChain.sign(commandInterest, params, wireFormat)

        # We successfully signed the interest, so update the timestamp.
        self._lastUsedTimestamp = timestamp

        return commandInterest