本文整理汇总了Python中pyndn.util.common.Common类的典型用法代码示例。如果您正苦于以下问题:Python Common类的具体用法?Python Common怎么用?Python Common使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Common类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __str__
def __str__(self):
s = "Certificate name:\n"
s += " "+self.getName().toUri()+"\n"
s += "Validity:\n"
dateFormat = "%Y%m%dT%H%M%S"
notBeforeStr = Common.datetimeFromTimestamp(self.getNotBefore()).strftime(dateFormat)
notAfterStr = Common.datetimeFromTimestamp(self.getNotAfter()).strftime(dateFormat)
s += " NotBefore: " + notBeforeStr+"\n"
s += " NotAfter: " + notAfterStr + "\n"
for sd in self._subjectDescriptionList:
s += "Subject Description:\n"
s += " " + str(sd.getOid()) + ": " + sd.getValue().toRawStr() + "\n"
s += "Public key bits:\n"
s += Common.base64Encode(self.getPublicKeyDer().toBytes(), True)
if len(self._extensionList) > 0:
s += "Extensions:\n"
for ext in self._extensionList:
s += " OID: "+ext.getOid()+"\n"
s += " Is critical: " + ('Y' if ext.isCritical() else 'N') + "\n"
s += " Value: " + str(ext.getValue()).encode('hex') + "\n"
return s
示例2: processEvents
def processEvents(self):
"""
Process any packets to receive and call callbacks such as onData,
onInterest or onTimeout. This returns immediately if there is no data to
receive. This blocks while calling the callbacks. You should repeatedly
call this from an event loop, with calls to sleep as needed so that the
loop doesn't use 100% of the CPU. Since processEvents modifies the pending
interest table, your application should make sure that it calls
processEvents in the same thread as expressInterest (which also modifies
the pending interest table).
:raises: This may raise an exception for reading data or in the callback
for processing the data. If you call this from an main event loop,
you may want to catch and log/disregard all exceptions.
"""
self._transport.processEvents()
# Check for PIT entry timeouts. Go backwards through the list so we can
# erase entries.
nowMilliseconds = Common.getNowMilliseconds()
i = len(self._pendingInterestTable) - 1
while i >= 0:
if self._pendingInterestTable[i].isTimedOut(nowMilliseconds):
# Save the PendingInterest and remove it from the PIT. Then
# call the callback.
pendingInterest = self._pendingInterestTable[i]
self._pendingInterestTable.pop(i)
pendingInterest.callTimeout()
# Refresh now since the timeout callback might have delayed.
nowMilliseconds = Common.getNowMilliseconds()
i -= 1
示例3: generateKeyPair
def generateKeyPair(self, keyName, params):
"""
Generate a pair of asymmetric keys.
:param Name keyName: The name of the key pair.
:param KeyParams params: The parameters of the key.
"""
if self.doesKeyExist(keyName, KeyClass.PUBLIC):
raise SecurityException("Public key already exists")
if self.doesKeyExist(keyName, KeyClass.PRIVATE):
raise SecurityException("Private key already exists")
try:
privateKey = TpmPrivateKey.generatePrivateKey(params)
privateKeyDer = privateKey.toPkcs8().toBytes()
publicKeyDer = privateKey.derivePublicKey().toBytes()
except Exception as ex:
raise SecurityException("Error in generatePrivateKey: " + str(ex))
keyUri = keyName.toUri()
keyFilePathNoExtension = self.maintainMapping(keyUri)
publicKeyFilePath = keyFilePathNoExtension + ".pub"
privateKeyFilePath = keyFilePathNoExtension + ".pri"
with open(publicKeyFilePath, 'w') as keyFile:
keyFile.write(Common.base64Encode(publicKeyDer, True))
with open(privateKeyFilePath, 'w') as keyFile:
keyFile.write(Common.base64Encode(privateKeyDer, True))
os.chmod(publicKeyFilePath, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
os.chmod(privateKeyFilePath, stat.S_IRUSR)
示例4: test_self_signed_cert_validity
def test_self_signed_cert_validity(self):
certificate = (self._fixture.addIdentity
(Name("/Security/V2/TestKeyChain/SelfSignedCertValidity"))
.getDefaultKey().getDefaultCertificate())
self.assertTrue(certificate.isValid())
# Check 10 years from now.
self.assertTrue(certificate.isValid
(Common.getNowMilliseconds() + 10 * 365 * 24 * 3600 * 1000.0))
# Check that notAfter is later than 10 years from now.
self.assertTrue(certificate.getValidityPeriod().getNotAfter() >
Common.getNowMilliseconds() + 10 * 365 * 24 * 3600 * 1000.0)
示例5: __init__
def __init__(self, arg1 = None, arg2 = None):
if arg1 == None or Common.typeIsString(arg1):
filePath = ""
if arg1 == None and arg2 == None:
# Check if we can connect using UnixSocket.
tryFilePath = "/var/run/nfd.sock"
# Use listdir because isfile doesn't see socket file types.
if (os.path.basename(tryFilePath) in
os.listdir(os.path.dirname(tryFilePath))):
filePath = tryFilePath
else:
tryFilePath = "/tmp/.ndnd.sock"
if (os.path.basename(tryFilePath) in
os.listdir(os.path.dirname(tryFilePath))):
filePath = tryFilePath
if filePath == "":
transport = TcpTransport()
host = arg1 if arg1 != None else "localhost"
connectionInfo = TcpTransport.ConnectionInfo(
host, arg2 if type(arg2) is int else 6363)
else:
transport = UnixTransport()
connectionInfo = UnixTransport.ConnectionInfo(filePath)
else:
transport = arg1
connectionInfo = arg2
self._node = Node(transport, connectionInfo)
self._commandKeyChain = None
self._commandCertificateName = Name()
示例6: __init__
def __init__(self, array = None, copy = True):
self._hash = None
if array == None:
self._array = None
elif isinstance(array, Blob):
# Use the existing _array. Don't need to check for copy.
self._array = array._array
else:
array = Common.stringToUtf8Array(array)
if copy:
# We are copying, so just make another bytearray.
# We always use a memoryview so that slicing is efficient.
if type(array) is _memoryviewWrapper:
# Use the underlying memoryview directly. (When we only
# support Python 3.3 or later, this check is not necessary.)
self._array = memoryview(bytearray(array._view))
else:
self._array = memoryview(bytearray(array))
else:
if type(array) is bytearray:
# We always use a memoryview so that slicing is efficient.
self._array = memoryview(array)
else:
# Can't take a memoryview, so use as-is.
self._array = array
if not _memoryviewUsesInt and type(self._array) is memoryview:
# memoryview elements are not int (Python versions before 3.3)
# so we need a wrapper which will return int elements.
self._array = _memoryviewWrapper(self._array)
示例7: _refresh
def _refresh(self):
"""
Remove all outdated certificate entries.
"""
# _nowOffsetMilliseconds is only used for testing.
now = Common.getNowMilliseconds() + self._nowOffsetMilliseconds
if now < self._nextRefreshTime:
return
# We recompute _nextRefreshTime.
nextRefreshTime = sys.float_info.max
# Go backwards through the list so we can erase entries.
i = len(self._certificatesByNameKeys) - 1
while i >= 0:
entry = self._certificatesByName[self._certificatesByNameKeys[i]]
if entry._removalTime <= now:
del self._certificatesByName[self._certificatesByNameKeys[i]]
self._certificatesByNameKeys.pop(i)
else:
nextRefreshTime = min(nextRefreshTime, entry._removalTime)
i -= 1
self._nextRefreshTime = nextRefreshTime
示例8: addSubCertificate
def addSubCertificate(self, subIdentityName, issuer, params = None):
"""
Issue a certificate for subIdentityName signed by issuer. If the
identity does not exist, it is created. A new key is generated as the
default key for the identity. A default certificate for the key is
signed by the issuer using its default certificate.
"""
if params == None:
params = KeyChain.getDefaultKeyParams()
subIdentity = self.addIdentity(subIdentityName, params)
request = subIdentity.getDefaultKey().getDefaultCertificate()
request.setName(request.getKeyName().append("parent").appendVersion(1))
certificateParams = SigningInfo(issuer)
# Validity period of 20 years.
now = Common.getNowMilliseconds()
certificateParams.setValidityPeriod(
ValidityPeriod(now, now + 20 * 365 * 24 * 3600 * 1000.0))
# Skip the AdditionalDescription.
self._keyChain.sign(request, certificateParams)
self._keyChain.setDefaultCertificate(subIdentity.getDefaultKey(), request)
return subIdentity
示例9: addCertificate
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 = Name(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
示例10: toHex
def toHex(self, result = None):
"""
Return the hex representation of the bytes in array.
:param BytesIO result: (optional) The BytesIO stream to write to. If
omitted, return a str with the result.
:return: The hex string (only if result is omitted).
:rtype: str
"""
if result == None:
if self._array == None:
return ""
result = BytesIO()
self.toHex(result)
return Common.getBytesIOString(result)
if self._array == None:
return
array = self.buf()
hexBuffer = bytearray(2)
for i in range(len(array)):
# Get the hex string and transfer to hexBuffer for writing.
hex = "%02x" % array[i]
hexBuffer[0] = ord(hex[0])
hexBuffer[1] = ord(hex[1])
result.write(hexBuffer)
示例11: _interestTimestampIsFresh
def _interestTimestampIsFresh(self, keyName, timestamp, failureReason):
"""
Determine whether the timestamp from the interest is newer than the last use
of this key, or within the grace interval on first use.
:param Name keyName: The name of the public key used to sign the interest.
:paramt int timestamp: The timestamp extracted from the interest name.
:param Array<str> failureReason: If verification fails, set
failureReason[0] to the failure reason string.
"""
try:
lastTimestamp = self._keyTimestamps[keyName.toUri()]
except KeyError:
now = Common.getNowMilliseconds()
notBefore = now - self._keyGraceInterval
notAfter = now + self._keyGraceInterval
if not (timestamp > notBefore and timestamp < notAfter):
return False
failureReason[0] = (
"The command interest timestamp is not within the first use grace period of " +
str(self._keyGraceInterval) + " milliseconds.")
else:
return True
else:
if timestamp <= lastTimestamp:
failureReason[0] = (
"The command interest timestamp is not newer than the previous timestamp")
return False
else:
return True
示例12: _checkTimestamp
def _checkTimestamp(self, state, keyName, timestamp):
"""
:param ValidationState state: On error, this calls state.fail and
returns False.
:param Name keyName: The key name.
:param float timestamp: The timestamp as milliseconds since Jan 1, 1970 UTC.
:return: On success, return True. On error, call state.fail and return
False.
:rtype: bool
"""
self._cleanUp()
# _nowOffsetMilliseconds is only used for testing.
now = Common.getNowMilliseconds() + self._nowOffsetMilliseconds
if (timestamp < now - self._options._gracePeriod or
timestamp > now + self._options._gracePeriod):
state.fail(ValidationError(ValidationError.POLICY_ERROR,
"Timestamp is outside the grace period for key " + keyName.toUri()))
return False
index = self._findByKeyName(keyName)
if index >= 0:
if timestamp <= self._container[index]._timestamp:
state.fail(ValidationError(ValidationError.POLICY_ERROR,
"Timestamp is reordered for key " + keyName.toUri()))
return False
def successCallback(interest):
self._insertNewRecord(interest, keyName, timestamp)
state.addSuccessCallback(successCallback)
return True
示例13: processEvents
def processEvents(self):
"""
Process any packets to receive and call callbacks such as onData,
onInterest or onTimeout. This returns immediately if there is no data to
receive. This blocks while calling the callbacks. You should repeatedly
call this from an event loop, with calls to sleep as needed so that the
loop doesn't use 100% of the CPU. Since processEvents modifies the pending
interest table, your application should make sure that it calls
processEvents in the same thread as expressInterest (which also modifies
the pending interest table).
:raises: This may raise an exception for reading data or in the callback
for processing the data. If you call this from an main event loop,
you may want to catch and log/disregard all exceptions.
"""
self._transport.processEvents()
# Check for delayed calls. Since callLater does a sorted insert into
# _delayedCallTable, the check for timeouts is quick and does not
# require searching the entire table. If callLater is overridden to use
# a different mechanism, then processEvents is not needed to check for
# delayed calls.
now = Common.getNowMilliseconds()
# _delayedCallTable is sorted on _callTime, so we only need to process
# the timed-out entries at the front, then quit.
while (len(self._delayedCallTable) > 0 and
self._delayedCallTable[0].getCallTime() <= now):
delayedCall = self._delayedCallTable[0]
del self._delayedCallTable[0]
delayedCall.callCallback()
示例14: getNewKeyName
def getNewKeyName(self, identityName, useKsk):
"""
Generate a name for a new key belonging to the identity.
:param Name identityName: The identity name.
:param bool useKsk: If True, generate a KSK name, otherwise a DSK name.
:return: The generated key name.
:rtype: Name
"""
timestamp = math.floor(Common.getNowMilliseconds() / 1000.0)
while timestamp <= self._lastTimestamp:
# Make the timestamp unique.
timestamp += 1
self._lastTimestamp = timestamp
nowString = repr(timestamp).replace(".0", "")
if useKsk:
keyIdStr = "ksk-" + nowString
else:
keyIdStr = "dsk-" + nowString
keyName = Name(identityName).append(keyIdStr)
if self.doesKeyExist(keyName):
raise SecurityException("Key name already exists")
return keyName
示例15: generateCertificateForKey
def generateCertificateForKey(self, keyName):
# let any raised SecurityExceptions bubble up
publicKeyBits = self._identityStorage.getKey(keyName)
publicKeyType = self._identityStorage.getKeyType(keyName)
publicKey = PublicKey(publicKeyType, publicKeyBits)
timestamp = Common.getNowMilliseconds()
# TODO: specify where the 'KEY' component is inserted
# to delegate responsibility for cert delivery
certificateName = keyName.getPrefix(-1).append('KEY').append(keyName.get(-1))
certificateName.append("ID-CERT").append(Name.Component(struct.pack(">Q", timestamp)))
certificate = IdentityCertificate(certificateName)
certificate.setNotBefore(timestamp)
certificate.setNotAfter((timestamp + 30*86400*1000)) # about a month
certificate.setPublicKeyInfo(publicKey)
# ndnsec likes to put the key name in a subject description
sd = CertificateSubjectDescription("2.5.4.41", keyName.toUri())
certificate.addSubjectDescription(sd)
certificate.encode()
return certificate