本文整理汇总了Python中pyndn.name.Name类的典型用法代码示例。如果您正苦于以下问题:Python Name类的具体用法?Python Name怎么用?Python Name使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Name类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getKeysOfIdentity
def getKeysOfIdentity(self, identityName):
"""
Get all the key names of the identity with the name identityName. The
returned key names can be used to create a KeyContainer. With a key name
and a backend implementation, one can create a Key front end instance.
:param Name identityName: The name of the identity.
:return: The set of key names. The Name objects are fresh copies. If the
identity does not exist, return an empty set.
:rtype: set of Name
"""
keyNames = set()
try:
cursor = self._database.cursor()
cursor.execute(
"SELECT key_name " +
"FROM keys JOIN identities ON keys.identity_id=identities.id " +
"WHERE identities.identity=?",
(sqlite3.Binary(bytearray(identityName.wireEncode().buf())), ))
rows = cursor.fetchall()
for (encoding, ) in rows:
name = Name()
name.wireDecode(bytearray(encoding))
keyNames.add(name)
cursor.close()
except Exception as ex:
raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex))
return keyNames
示例2: getDefaultIdentity
def getDefaultIdentity(self):
"""
Get the default identity.
:return: The name of the default identity, as a fresh copy.
:rtype: Name
:raises Pib.Error: For no default identity.
"""
encoding = None
try:
cursor = self._database.cursor()
cursor.execute("SELECT identity FROM identities WHERE is_default=1")
row = cursor.fetchone()
if row != None:
(encoding,) = row
cursor.close()
except Exception as ex:
raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex))
if encoding != None:
name = Name()
name.wireDecode(bytearray(encoding))
return name
else:
raise Pib.Error("No default identity")
示例3: produce
def produce(self, data, timeSlot, content, onError=defaultOnError):
"""
Encrypt the given content with the content key that covers timeSlot, and
update the data packet with the encrypted content and an appropriate
data name.
:param Data data: An empty Data object which is updated.
:param float timeSlot: The time slot as milliseconds since Jan 1, 1970 UTC.
:param Blob content: The content to encrypt.
:param onError: (optional) This calls onError(errorCode, message) for an
error, where errorCode is from EncryptError.ErrorCode and message is a
str. If omitted, use a default callback which does nothing.
NOTE: The library will log any exceptions raised by this callback, but
for better error handling the callback should catch and properly
handle any exceptions.
:type onError: function object
"""
# Get a content key.
contentKeyName = self.createContentKey(timeSlot, None, onError)
contentKey = self._database.getContentKey(timeSlot)
# Produce data.
dataName = Name(self._namespace)
dataName.append(Schedule.toIsoString(timeSlot))
data.setName(dataName)
params = EncryptParams(EncryptAlgorithmType.AesCbc, 16)
Encryptor.encryptData(data, content, contentKeyName, contentKey, params)
self._keyChain.sign(data)
示例4: _createDKeyData
def _createDKeyData(self, startTimeStamp, endTimeStamp, keyName,
privateKeyBlob, certificateKey):
"""
Create a D-KEY Data packet with an EncryptedContent for the given
private key, encrypted with the certificate key.
:param str startTimeStamp: The start time stamp string to put in the name.
:param str endTimeStamp: The end time stamp string to put in the name.
:param Name keyName The key name to put in the data packet name and the
EncryptedContent key locator.
:param Blob privateKeyBlob: A Blob of the encoded private key.
:param Blob certificateKey: The certificate key encoding, used to
encrypt the private key.
:return: The Data packet.
:rtype: Data
"""
name = Name(self._namespace)
name.append(Encryptor.NAME_COMPONENT_D_KEY)
name.append(startTimeStamp).append(endTimeStamp)
data = Data(name)
data.getMetaInfo().setFreshnessPeriod(
self._freshnessHours * GroupManager.MILLISECONDS_IN_HOUR)
encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
Encryptor.encryptData(
data, privateKeyBlob, keyName, certificateKey, encryptParams)
self._keyChain.sign(data)
return data
示例5: getCertificatesOfKey
def getCertificatesOfKey(self, keyName):
"""
Get a list of certificate names of the key with id keyName. The returned
certificate names can be used to create a PibCertificateContainer. With a
certificate name and a backend implementation, one can obtain the
certificate.
:param Name keyName: The name of the key.
:return: The set of certificate names. The Name objects are fresh
copies. If the key does not exist, return an empty set.
:rtype: set of Name
"""
certNames = set()
try:
cursor = self._database.cursor()
cursor.execute(
"SELECT certificate_name " +
"FROM certificates JOIN keys ON certificates.key_id=keys.id " +
"WHERE keys.key_name=?",
(sqlite3.Binary(bytearray(keyName.wireEncode().buf())), ))
rows = cursor.fetchall()
for (encoding, ) in rows:
name = Name()
name.wireDecode(bytearray(encoding))
certNames.add(name)
cursor.close()
except Exception as ex:
raise PibImpl.Error("PibSqlite3: SQLite error: " + str(ex))
return certNames
示例6: getScheduleMembers
def getScheduleMembers(self, name):
"""
For each member using the given schedule, get the name and public key
DER of the member's key.
:param str name: The name of the schedule.
:return: a new dictionary where the dictionary's key is the Name of the
public key and the value is the Blob of the public key DER. Note that
the member's identity name is keyName.getPrefix(-1). If the schedule
name is not found, the dictionary is empty.
:rtype: dictionary<Name, Blob>
:raises GroupManagerDb.Error: For a database error.
"""
dictionary = {}
try:
cursor = self._database.cursor()
cursor.execute(
"SELECT key_name, pubkey "
+ "FROM members JOIN schedules ON members.schedule_id=schedules.schedule_id "
+ "WHERE schedule_name=?",
(name,),
)
results = cursor.fetchall()
for (keyNameEncoding, keyEncoding) in results:
keyName = Name()
keyName.wireDecode(bytearray(keyNameEncoding), TlvWireFormat.get())
dictionary[keyName] = Blob(bytearray(keyEncoding), False)
cursor.close()
return dictionary
except Exception as ex:
raise GroupManagerDb.Error("Sqlite3GroupManagerDb.getScheduleMembers: SQLite error: " + str(ex))
示例7: _initialTimeOut
def _initialTimeOut(self, interest):
"""
Initial sync interest timeout, which means there are no other publishers
yet.
"""
if not self._enabled:
# Ignore callbacks after the application calls shutdown().
return
logging.getLogger(__name__).info("initial sync timeout")
logging.getLogger(__name__).info("no other people")
self._sequenceNo += 1
if self._sequenceNo != 0:
# Since there were no other users, we expect sequence no 0.
raise RuntimeError(
"ChronoSync: sequenceNo_ is not the expected value of 0 for first use.")
tempContent = sync_state_pb2.SyncStateMsg()
content = getattr(tempContent, "ss").add()
content.name = self._applicationDataPrefixUri
content.type = SyncState_UPDATE
content.seqno.seq = self._sequenceNo
content.seqno.session = self._sessionNo
self._update(getattr(tempContent, "ss"))
self._onInitialized()
name = Name(self._applicationBroadcastPrefix)
name.append(self._digestTree.getRoot())
retryInterest = Interest(name)
retryInterest.setInterestLifetimeMilliseconds(self._syncLifetime)
self._face.expressInterest(retryInterest, self._onData, self._syncTimeout)
logging.getLogger(__name__).info("Syncinterest expressed:")
logging.getLogger(__name__).info("%s", name.toUri())
示例8: _onData
def _onData(self, interest, data):
"""
Process Sync Data.
"""
if not self._enabled:
# Ignore callbacks after the application calls shutdown().
return
logging.getLogger(__name__).info(
"Sync ContentObject received in callback")
logging.getLogger(__name__).info(
"name: %s", data.getName().toUri())
# TODO: Check if this works in Python 3.
tempContent = SyncStateMsg()
#pylint: disable=E1103
tempContent.ParseFromString(data.getContent().toBytes())
#pylint: enable=E1103
content = getattr(tempContent, "ss")
if self._digestTree.getRoot() == "00":
isRecovery = True
#processing initial sync data
self._initialOndata(content)
else:
self._update(content)
if (interest.getName().size() ==
self._applicationBroadcastPrefix.size() + 2):
# Assume this is a recovery interest.
isRecovery = True
else:
isRecovery = False
# Send the interests to fetch the application data.
syncStates = []
for i in range(len(content)):
syncState = content[i]
# Only report UPDATE sync states.
if syncState.type == SyncState_UPDATE:
if len(syncState.application_info) > 0:
applicationInfo = Blob(syncState.application_info, True)
else:
applicationInfo = Blob()
syncStates.append(self.SyncState(
syncState.name, syncState.seqno.session,
syncState.seqno.seq, applicationInfo))
try:
self._onReceivedSyncState(syncStates, isRecovery)
except:
logging.exception("Error in onReceivedSyncState")
name = Name(self._applicationBroadcastPrefix)
name.append(self._digestTree.getRoot())
syncInterest = Interest(name)
syncInterest.setInterestLifetimeMilliseconds(self._syncLifetime)
self._face.expressInterest(syncInterest, self._onData, self._syncTimeout)
logging.getLogger(__name__).info("Syncinterest expressed:")
logging.getLogger(__name__).info("%s", name.toUri())
示例9: signByIdentity
def signByIdentity(self, target, identityName = None, wireFormat = None):
"""
Sign the target. If it is a Data object, set its signature.
If it is an array, return a signature object.
:param target: If this is a Data object, wire encode for signing,
update its signature and key locator field and wireEncoding. If it is
an array, sign it and return a Signature object.
:type target: Data or an array which implements the buffer protocol
:param Name identityName: (optional) The identity name for the key to
use for signing. If omitted, infer the signing identity from the data
packet name.
:param wireFormat: (optional) A WireFormat object used to encode the
input. If omitted, use WireFormat.getDefaultWireFormat().
:type wireFormat: A subclass of WireFormat
:return: The Signature object (only if the target is an array).
:rtype: An object of a subclass of Signature
"""
if identityName == None:
identityName = Name()
if isinstance(target, Data):
if identityName.size() == 0:
inferredIdentity = self._policyManager.inferSigningIdentity(
target.getName())
if inferredIdentity.size() == 0:
signingCertificateName = self._identityManager.getDefaultCertificateName()
else:
signingCertificateName = \
self._identityManager.getDefaultCertificateNameForIdentity(inferredIdentity)
else:
signingCertificateName = \
self._identityManager.getDefaultCertificateNameForIdentity(identityName)
if signingCertificateName.size() == 0:
raise SecurityException("No qualified certificate name found!")
if not self._policyManager.checkSigningPolicy(
target.getName(), signingCertificateName):
raise SecurityException(
"Signing Cert name does not comply with signing policy")
self._identityManager.signByCertificate(
target, signingCertificateName, wireFormat)
else:
signingCertificateName = \
self._identityManager.getDefaultCertificateNameForIdentity(identityName)
if signingCertificateName.size() == 0:
raise SecurityException("No qualified certificate name found!")
return self._identityManager.signByCertificate(
target, signingCertificateName)
示例10: _sendRecovery
def _sendRecovery(self, syncDigest):
"""
Send Recovery Interest.
"""
logging.getLogger(__name__).info("unknown digest: ")
name = Name(self._applicationBroadcastPrefix)
name.append("recovery").append(syncDigest)
interest = Interest(name)
interest.setInterestLifetimeMilliseconds(self._syncLifetime)
self._face.expressInterest(interest, self._onData, self._syncTimeout)
logging.getLogger(__name__).info("Recovery Syncinterest expressed:")
logging.getLogger(__name__).info("%s", name.toUri())
示例11: constructKeyName
def constructKeyName(identityName, keyId):
"""
Construct a key name based on the appropriate naming conventions.
:param Name identityName: The name of the identity.
:param Name.Component keyId: The key ID name component.
:return: The constructed name as a new Name.
:rtype: Name
"""
keyName = Name(identityName)
keyName.append(CertificateV2.KEY_COMPONENT).append(keyId)
return keyName
示例12: __init__
def __init__(self, prefix, regexFilter = None):
if type(prefix) is InterestFilter:
interestFilter = prefix
# The copy constructor.
self._prefix = Name(interestFilter._prefix)
self._regexFilter = interestFilter._regexFilter
self._regexFilterPattern = interestFilter._regexFilterPattern
else:
self._prefix = Name(prefix)
self._regexFilter = regexFilter
if regexFilter != None:
self._regexFilterPattern = self.makePattern(regexFilter)
else:
self._regexFilterPattern = None
示例13: _makeSelfSignedCertificate
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
示例14: __init__
def __init__(self, onReceivedSyncState, onInitialized,
applicationDataPrefix, applicationBroadcastPrefix, sessionNo, face,
keyChain, certificateName, syncLifetime, onRegisterFailed):
self._onReceivedSyncState = onReceivedSyncState
self._onInitialized = onInitialized
self._applicationDataPrefixUri = applicationDataPrefix.toUri()
self._applicationBroadcastPrefix = Name(applicationBroadcastPrefix)
self._sessionNo = sessionNo
self._face = face
self._keyChain = keyChain
self._certificateName = Name(certificateName)
self._syncLifetime = syncLifetime
self._contentCache = MemoryContentCache(face)
self._digestLog = [] # of _DigestLogEntry
self._digestTree = DigestTree()
self._sequenceNo = -1
self._enabled = True
emptyContent = SyncStateMsg()
# Use getattr to avoid pylint errors.
self._digestLog.append(self._DigestLogEntry("00", getattr(emptyContent, "ss")))
# Register the prefix with the contentCache_ and use our own onInterest
# as the onDataNotFound fallback.
self._contentCache.registerPrefix(
self._applicationBroadcastPrefix, onRegisterFailed, self._onInterest)
interest = Interest(self._applicationBroadcastPrefix)
interest.getName().append("00")
interest.setInterestLifetimeMilliseconds(1000)
interest.setMustBeFresh(True)
face.expressInterest(interest, self._onData, self._initialTimeOut)
logging.getLogger(__name__).info("initial sync expressed")
logging.getLogger(__name__).info("%s", interest.getName().toUri())
示例15: __init__
def __init__(self, expectedNEntries, face, syncPrefix, onNamesUpdate,
keyChain, syncInterestLifetime = DEFAULT_SYNC_INTEREST_LIFETIME,
syncReplyFreshnessPeriod = DEFAULT_SYNC_REPLY_FRESHNESS_PERIOD,
signingInfo = SigningInfo(), canAddToSyncData = None,
canAddReceivedName = None):
super(FullPSync2017, self).__init__(
expectedNEntries, syncPrefix, syncReplyFreshnessPeriod)
self._face = face
self._keyChain = keyChain
self._syncInterestLifetime = syncInterestLifetime
self._signingInfo = SigningInfo(signingInfo)
self._onNamesUpdate = onNamesUpdate
self._canAddToSyncData = canAddToSyncData
self._canAddReceivedName = canAddReceivedName
self._segmentPublisher = PSyncSegmentPublisher(self._face, self._keyChain)
# The key is the Name. The values is a _PendingEntryInfoFull.
self._pendingEntries = {}
self._outstandingInterestName = Name()
self._registeredPrefix = self._face.registerPrefix(
self._syncPrefix, self._onSyncInterest,
PSyncProducerBase.onRegisterFailed)
# TODO: Should we do this after the registerPrefix onSuccess callback?
self._sendSyncInterest()