コード例 #1
0
ファイル: signing_info.py プロジェクト: nabilschear/PyNDN2
    def __init__(self, arg1=None, arg2=None):
        self._validityPeriod = ValidityPeriod()
        if arg1 is None:
            self.reset(SigningInfo.SignerType.NULL)
            self._digestAlgorithm = DigestAlgorithm.SHA256
        elif isinstance(arg1, SigningInfo):
            # The copy constructor.
            signingInfo = arg1

            self._type = signingInfo._type
            self._name = Name(signingInfo._name)
            self._identity = signingInfo._identity
            self._key = signingInfo._key
            self._digestAlgorithm = signingInfo._digestAlgorithm
            self._validityPeriod = ValidityPeriod(signingInfo._validityPeriod)
        elif type(arg1) is int:
            signerType = arg1

            self.reset(signerType)
            if not (arg2 is None):
                self._name = Name(arg2)
            self._digestAlgorithm = DigestAlgorithm.SHA256
        elif isinstance(arg1, PibIdentity):
            self._digestAlgorithm = DigestAlgorithm.SHA256
            self.setPibIdentity(arg1)
        elif isinstance(arg1, PibKey):
            self._digestAlgorithm = DigestAlgorithm.SHA256
            self.setPibKey(arg1)
        elif type(arg1) is str:
            signingString = arg1

            self.reset(SigningInfo.SignerType.NULL)
            self._digestAlgorithm = DigestAlgorithm.SHA256

            if signingString == "":
                return

            try:
                iColon = signingString.index(':')
            except:
                raise ValueError(
                    "Invalid signing string cannot represent SigningInfo")

            scheme = signingString[0:iColon]
            nameArg = signingString[iColon + 1:]

            if scheme == "id":
                if nameArg == SigningInfo.getDigestSha256Identity().toUri():
                    self.setSha256Signing()
                else:
                    self.setSigningIdentity(Name(nameArg))
            elif scheme == "key":
                self.setSigningKeyName(Name(nameArg))
            elif scheme == "cert":
                self.setSigningCertificateName(Name(nameArg))
            else:
                raise ValueError("Invalid signing string scheme")
        else:
            raise ValueError("SigningInfo: Unrecognized type")
コード例 #2
0
ファイル: certificate_v2.py プロジェクト: named-data/PyNDN2
    def getValidityPeriod(self):
        """
        Get the certificate validity period from the SignatureInfo.

        :return: The ValidityPeriod object.
        :rtype: ValidityPeriod
        :raises ValueError: If the SignatureInfo doesn't have a
          ValidityPeriod.
        """
        if not ValidityPeriod.canGetFromSignature(self.getSignature()):
            raise ValueError(
              "The SignatureInfo does not have a ValidityPeriod")

        return ValidityPeriod.getFromSignature(self.getSignature())
コード例 #3
0
    def getValidityPeriod(self):
        """
        Get the certificate validity period from the SignatureInfo.

        :return: The ValidityPeriod object.
        :rtype: ValidityPeriod
        :raises ValueError: If the SignatureInfo doesn't have a
          ValidityPeriod.
        """
        if not ValidityPeriod.canGetFromSignature(self.getSignature()):
            raise ValueError(
                "The SignatureInfo does not have a ValidityPeriod")

        return ValidityPeriod.getFromSignature(self.getSignature())
コード例 #4
0
ファイル: safe_bag.py プロジェクト: named-data/PyNDN2
    def _makeSelfSignedCertificate(
      keyName, privateKeyBag, publicKeyEncoding, password, digestAlgorithm,
      wireFormat):
        certificate = CertificateV2()

        # Set the name.
        now = Common.getNowMilliseconds()
        certificateName = Name(keyName)
        certificateName.append("self").appendVersion(int(now))
        certificate.setName(certificateName)

        # Set the MetaInfo.
        certificate.getMetaInfo().setType(ContentType.KEY)
        # Set a one-hour freshness period.
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

        # Set the content.
        publicKey = PublicKey(publicKeyEncoding)
        certificate.setContent(publicKey.getKeyDer())

        # Create a temporary in-memory Tpm and import the private key.
        tpm = Tpm("", "", TpmBackEndMemory())
        tpm._importPrivateKey(keyName, privateKeyBag.toBytes(), password)

        # Set the signature info.
        if publicKey.getKeyType() == KeyType.RSA:
            certificate.setSignature(Sha256WithRsaSignature())
        elif publicKey.getKeyType() == KeyType.EC:
            certificate.setSignature(Sha256WithEcdsaSignature())
        else:
            raise ValueError("Unsupported key type")
        signatureInfo = certificate.getSignature()
        KeyLocator.getFromSignature(signatureInfo).setType(KeyLocatorType.KEYNAME)
        KeyLocator.getFromSignature(signatureInfo).setKeyName(keyName)

        # Set a 20-year validity period.
        ValidityPeriod.getFromSignature(signatureInfo).setPeriod(
          now, now + 20 * 365 * 24 * 3600 * 1000.0)

        # Encode once to get the signed portion.
        encoding = certificate.wireEncode(wireFormat)
        signatureBytes = tpm.sign(encoding.toSignedBytes(), keyName,
          digestAlgorithm)
        signatureInfo.setSignature(signatureBytes)

        # Encode again to include the signature.
        certificate.wireEncode(wireFormat)

        return certificate
コード例 #5
0
    def _makeSelfSignedCertificate(keyName, privateKeyBag, publicKeyEncoding,
                                   password, digestAlgorithm, wireFormat):
        certificate = CertificateV2()

        # Set the name.
        now = Common.getNowMilliseconds()
        certificateName = Name(keyName)
        certificateName.append("self").appendVersion(int(now))
        certificate.setName(certificateName)

        # Set the MetaInfo.
        certificate.getMetaInfo().setType(ContentType.KEY)
        # Set a one-hour freshness period.
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

        # Set the content.
        publicKey = PublicKey(publicKeyEncoding)
        certificate.setContent(publicKey.getKeyDer())

        # Create a temporary in-memory Tpm and import the private key.
        tpm = Tpm("", "", TpmBackEndMemory())
        tpm._importPrivateKey(keyName, privateKeyBag.toBytes(), password)

        # Set the signature info.
        if publicKey.getKeyType() == KeyType.RSA:
            certificate.setSignature(Sha256WithRsaSignature())
        elif publicKey.getKeyType() == KeyType.EC:
            certificate.setSignature(Sha256WithEcdsaSignature())
        else:
            raise ValueError("Unsupported key type")
        signatureInfo = certificate.getSignature()
        KeyLocator.getFromSignature(signatureInfo).setType(
            KeyLocatorType.KEYNAME)
        KeyLocator.getFromSignature(signatureInfo).setKeyName(keyName)

        # Set a 20-year validity period.
        ValidityPeriod.getFromSignature(signatureInfo).setPeriod(
            now, now + 20 * 365 * 24 * 3600 * 1000.0)

        # Encode once to get the signed portion.
        encoding = certificate.wireEncode(wireFormat)
        signatureBytes = tpm.sign(encoding.toSignedBytes(), keyName,
                                  digestAlgorithm)
        signatureInfo.setSignature(signatureBytes)

        # Encode again to include the signature.
        certificate.wireEncode(wireFormat)

        return certificate
コード例 #6
0
    def __init__(self, value = None):
        if value == None:
            self._keyLocator = ChangeCounter(KeyLocator())
            self._validityPeriod = ChangeCounter(ValidityPeriod())
            self._signature = Blob()
        elif isinstance(value, Sha256WithRsaSignature):
            # Copy its values.
            self._keyLocator = ChangeCounter(KeyLocator(value.getKeyLocator()))
            self._validityPeriod = ChangeCounter(ValidityPeriod(value.getValidityPeriod()))
            self._signature = value._signature
        else:
            raise RuntimeError(
              "Unrecognized type for Sha256WithRsaSignature constructor: " +
              str(type(value)))

        self._changeCount = 0
コード例 #7
0
    def addCertificate(self, key, issuerId):
        """
        Add a self-signed certificate made from the key and issuer ID.

        :param PibKey key: The key for the certificate.
        :param str issuerId: The issuer ID name component for the certificate
          name.
        :return: The new certificate.
        :rtype: CertificateV2
        """
        certificateName = key.getName()
        certificateName.append(issuerId).appendVersion(3)
        certificate = CertificateV2()
        certificate.setName(certificateName)

        # Set the MetaInfo.
        certificate.getMetaInfo().setType(ContentType.KEY)
        # One hour.
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

        # Set the content.
        certificate.setContent(key.getPublicKey())

        params = SigningInfo(key)
        # Validity period of 10 days.
        now = Common.getNowMilliseconds()
        params.setValidityPeriod(
          ValidityPeriod(now, now + 10 * 24 * 3600 * 1000.0))

        self._keyChain.sign(certificate, params)
        return certificate
コード例 #8
0
    def setValidityPeriod(self, validityPeriod):
        """
        Set the validity period to a copy of the given ValidityPeriod.

        :param ValidityPeriod validityPeriod: The ValidityPeriod which is copied.
        """
        self._validityPeriod.set(ValidityPeriod(validityPeriod))
        self._changeCount += 1
コード例 #9
0
    def generateKeyAndSendNewInterest(self, probeTokenData):
        """
        """
        pib = self.keyChain.getPib()
        try:
            identity = pib.getIdentity(self.identityName)
            self.key = self.keyChain.createKey(identity)
        except Exception as e:
            identity = self.keyChain.createIdentityV2(self.identityName)
            self.key = identity.getDefaultKey()

        cert = CertificateV2()
        cert.setName(
            Name(self.key.getName()).append("cert-request").appendVersion(
                int(time.time())))
        cert.getMetaInfo().setType(ContentType.KEY)
        cert.getMetaInfo().setFreshnessPeriod(24 * 3600)
        cert.setContent(self.key.getPublicKey())

        signingInfo = SigningInfo(self.key)
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(
            ValidityPeriod(now, now + 24 * 3600 * 1000.0))
        self.keyChain.sign(cert, signingInfo)
        #cert = self.keyChain.selfSign(self.key) # Does not work because validity period is greater than certserver default

        interestName = Name(self.caPrefix).append("CA").append("_NEW")
        newInterest = Interest(interestName)
        newInterest.setMustBeFresh(True)
        newInterest.setCanBePrefix(False)

        ecdhPub = "{}\n".format(self.ecdh.getBase64PubKey())
        ecdhCertReq = "{}\n".format(
            b64encode(cert.wireEncode().toBytes()).decode('utf-8'))
        probeToken = "{}\n".format(
            b64encode(probeTokenData.wireEncode().toBytes()).decode('utf-8'))

        jsonDump = json.dumps(
            {
                "ecdh-pub": ecdhPub,
                "cert-request": ecdhCertReq,
                "probe-token": probeToken
            },
            indent=4)
        print(jsonDump)
        newInterest.setApplicationParameters(jsonDump)
        newInterest.appendParametersDigestToName()

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

        print(newInterest.getName())

        self.face.expressInterest(newInterest, self.onNewData, self.onTimeout)
コード例 #10
0
ファイル: signing_info.py プロジェクト: nabilschear/PyNDN2
    def setValidityPeriod(self, validityPeriod):
        """
        Set the validity period for the signature info.
        Note that the equivalent ndn-cxx method uses a semi-prepared
        SignatureInfo, but this method only uses the ValidityPeriod from the
        SignatureInfo.

        :param ValidityPeriod validityPeriod: The validity period, which is
          copied.
        :return: This SigningInfo.
        :rtype: SigningInfo
        """
        self._validityPeriod = ValidityPeriod(validityPeriod)
        return self
コード例 #11
0
ファイル: signing_info.py プロジェクト: nabilschear/PyNDN2
    def reset(self, signerType):
        """
        Check and set the signerType, and set others to default values. This
        does NOT reset the digest algorithm.

        :param signerType: The type of signer.
        :type signerType: int from the SigningInfo.SignerType enum
        """
        if (not (signerType == SigningInfo.SignerType.NULL
                 or signerType == SigningInfo.SignerType.ID
                 or signerType == SigningInfo.SignerType.KEY
                 or signerType == SigningInfo.SignerType.CERT
                 or signerType == SigningInfo.SignerType.SHA256)):
            raise ValueError("SigningInfo: The signerType is not valid")

        self._type = signerType
        self._name = Name()
        self._identity = None
        self._key = None
        self._validityPeriod = ValidityPeriod()