当前位置: 首页>>代码示例>>Python>>正文


Python KeyChain.getPib方法代码示例

本文整理汇总了Python中pyndn.security.KeyChain.getPib方法的典型用法代码示例。如果您正苦于以下问题:Python KeyChain.getPib方法的具体用法?Python KeyChain.getPib怎么用?Python KeyChain.getPib使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyndn.security.KeyChain的用法示例。


在下文中一共展示了KeyChain.getPib方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: benchmarkDecodeDataSeconds

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import getPib [as 别名]
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
    """
    Loop to decode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useCrypto: If true, verify the signature.  If false, don't
      verify.
    :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
    :param Blob encoding: The wire encoding to decode.
    :return: The number of seconds for all iterations.
    :rtype: float
    """
    # Initialize the KeyChain in case useCrypto is true.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.EC
            else DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.EC
            else DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data()
        data.wireDecode(encoding)

        if useCrypto:
            validator.validate(data,onVerifySuccess, onVerifyFailed)

    finish = getNowSeconds()

    return finish - start
开发者ID:named-data,项目名称:PyNDN2,代码行数:36,代码来源:test_encode_decode_benchmark.py

示例2: main

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import getPib [as 别名]
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = (Interest(Name("/ndn/abc"))
      .setMustBeFresh(False)
      .setMinSuffixComponents(4)
      .setMaxSuffixComponents(6)
      .setInterestLifetimeMilliseconds(30000)
      .setChildSelector(1)
      .setMustBeFresh(True))
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(bytearray(
      [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
       0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    validator.validate(
      reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"),
      makeFailureCallback("Freshly-signed Interest"))
开发者ID:named-data,项目名称:PyNDN2,代码行数:59,代码来源:test_encode_decode_interest.py

示例3: main

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import getPib [as 别名]
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"),
      makeFailureCallback("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
      makeFailureCallback("Freshly-signed Data"))
开发者ID:named-data,项目名称:PyNDN2,代码行数:40,代码来源:test_encode_decode_data.py

示例4: TestPolicyManagerV2

# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import getPib [as 别名]
class TestPolicyManagerV2(ut.TestCase):
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.pibImpl = PibMemory()
        self.tpmBackEnd = TpmBackEndMemory()
        self.policyManager = ConfigPolicyManager(
          'policy_config/simple_rules.conf', CertificateCacheV2())

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        self.keyName = Name(self.identityName).append("KEY").append("ksk-1416010123")
        self.pibImpl.addKey(self.identityName, self.keyName,
          TEST_RSA_PUBLIC_KEY_DER)
        # Set the password to None since we have an unencrypted PKCS #8 private key.
        self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8,
          None)

        self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd, self.policyManager)

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)

    def tearDown(self):
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName).getDefaultCertificate().getName()
        face = Face("localhost")
        face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager, newInterest)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
          "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
          "Verification success called {} times instead of 1".format(
            vr.successCount))

        vr  = doVerify(self.policyManager, oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
          "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
          "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
          "Failure callback called {} times instead of 1".format(
            vr.failureCount))

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # This test is needed, since the KeyChain will express interests in
        # unknown certificates.
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
          "ConfigPolicyManager did not create ValidationRequest for unknown certificate")
        self.assertEqual(vr.successCount, 0,
          "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
          "ConfigPolicyManager called failure callback with pending ValidationRequest")

        # Now save the cert data to our anchor directory, and wait.
        # We have to sign it with the current identity or the policy manager
        # will create an interest for the signing certificate.

        cert = CertificateV2()
        certData = b64decode(CERT_DUMP)
        cert.wireDecode(Blob(certData, False))
        signingInfo = SigningInfo()
        signingInfo.setSigningIdentity(self.identityName)
        # Make sure the validity period is current for two years.
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(ValidityPeriod
          (now, now + 2 * 365 * 24 * 3600 * 1000.0))

        self.keyChain.sign(cert, signingInfo)
        encodedCert = b64encode(cert.wireEncode().toBytes())
#.........这里部分代码省略.........
开发者ID:named-data,项目名称:PyNDN2,代码行数:103,代码来源:test_policy_manager_v2.py


注:本文中的pyndn.security.KeyChain.getPib方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。