本文整理汇总了Python中pyndn.security.certificate.IdentityCertificate类的典型用法代码示例。如果您正苦于以下问题:Python IdentityCertificate类的具体用法?Python IdentityCertificate怎么用?Python IdentityCertificate使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IdentityCertificate类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getCertificate
def getCertificate(self, certificateName, allowAny = False):
"""
Get a certificate from the identity storage.
:param Name certificateName: The name of the requested certificate.
:param bool allowAny: (optional) If False, only a valid certificate will
be returned, otherwise validity is disregarded. If omitted,
allowAny is False.
:return: The requested certificate. If not found, return None.
:rtype: Data
"""
chosenCert = None
certificateUri = certificateName.toUri()
cursor = self._database.cursor()
#if not allowAny:
# validityClause = " AND valid_flag=1"
#else:
validityClause = ""
# use LIKE because key locators chop off timestamps
# need to escape any percent signs in the certificate uri for sql's
# sake, but still append % for LIKE
escapedUri = certificateUri.replace('%', '\\%')
full_statement = "SELECT certificate_data FROM Certificate WHERE cert_name LIKE ?"+validityClause+" ESCAPE '\\' ORDER BY cert_name DESC"
#full_statement = "SELECT certificate_data FROM Certificate WHERE cert_name=?"+validityClause
cursor.execute(full_statement, (escapedUri+'%', ))
try:
(certData, ) = cursor.fetchone()
except TypeError:
pass
else:
chosenCert = IdentityCertificate()
chosenCert.wireDecode(bytearray(certData))
return chosenCert
示例2: _processValidCertificate
def _processValidCertificate(self, data):
# unpack the cert from the HMAC signed packet and verify
try:
newCert = IdentityCertificate()
newCert.wireDecode(data.getContent())
self.log.info("Received certificate from controller")
self.log.debug(str(newCert))
# NOTE: we download and install the root certificate without verifying it (!)
# otherwise our policy manager will reject it.
# we may need a static method on KeyChain to allow verifying before adding
rootCertName = newCert.getSignature().getKeyLocator().getKeyName()
# update trust rules so we trust the controller
self._policyManager.setDeviceIdentity(self._configureIdentity)
self._policyManager.updateTrustRules()
def onRootCertificateDownload(interest, data):
try:
self._identityStorage.addCertificate(data)
except SecurityException:
# already exists
pass
self._keyChain.verifyData(newCert, self._finalizeCertificateDownload, self._certificateValidationFailed)
def onRootCertificateTimeout(interest):
# TODO: limit number of tries, then revert trust root + network prefix
# reset salt, create new Hmac key
self.face.expressInterest(rootCertName, onRootCertificateDownload, onRootCertificateTimeout)
self.face.expressInterest(rootCertName, onRootCertificateDownload, onRootCertificateTimeout)
except Exception as e:
self.log.exception("Could not import new certificate", exc_info=True)
示例3: _processValidCertificate
def _processValidCertificate(self, data):
# unpack the cert from the HMAC signed packet and verify
try:
newCert = IdentityCertificate()
newCert.wireDecode(data.getContent())
self.log.info("Received certificate from controller")
# NOTE: we download and install the root certificate without verifying it (!)
# otherwise our policy manager will reject it.
# we may need a static method on KeyChain to allow verifying before adding
rootCertName = newCert.getSignature().getKeyLocator().getKeyName()
# update trust rules so we trust the controller
self._policyManager.setDeviceIdentity(self._configureIdentity)
self._policyManager.updateTrustRules()
def onRootCertificateDownload(interest, data):
try:
# zhehao: the root cert is downloaded and installed without verifying; should the root cert be preconfigured?
# Insert root certificate so that we can verify newCert
self._policyManager._certificateCache.insertCertificate(data)
# Set the root cert as default for root identity
try:
self._identityManager.addCertificateAsIdentityDefault(IdentityCertificate(data))
except SecurityException as e:
print("Error when addCertificateAsIdentityDefault for root: " + data.getName().toUri())
print(str(e))
self._rootCertificate = data
try:
# use the default configuration where possible
# TODO: use environment variable for this, fall back to default
fileName = os.path.expanduser('~/.ndn/.iot.root.cert')
rootCertFile = open(fileName, "w")
rootCertFile.write(Blob(b64encode(self._rootCertificate.wireEncode().toBytes()), False).toRawStr())
rootCertFile.close()
except IOError as e:
self.log.error("Cannot write to root certificate file: " + rootCertFile)
print "Cannot write to root certificate file: " + rootCertFile
except SecurityException as e:
print(str(e))
# already exists, or got certificate in wrong format
pass
self._keyChain.verifyData(newCert, self._finalizeCertificateDownload, self._certificateValidationFailed)
def onRootCertificateTimeout(interest):
# TODO: limit number of tries, then revert trust root + network prefix
# reset salt, create new Hmac key
self.face.expressInterest(rootCertName, onRootCertificateDownload, onRootCertificateTimeout)
self.face.expressInterest(rootCertName, onRootCertificateDownload, onRootCertificateTimeout)
except Exception as e:
self.log.exception("Could not import new certificate", exc_info=True)
示例4: test_refresh_10s
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)
# 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
with open(self.testCertFile, 'w') as certFile:
cert = IdentityCertificate()
certData = b64decode(CERT_DUMP)
cert.wireDecode(Blob(certData, False))
self.keyChain.signByIdentity(cert, self.identityName)
encodedCert = b64encode(cert.wireEncode().toBuffer())
certFile.write(Blob(encodedCert, False).toRawStr())
# still too early for refresh to pick it up
vr = doVerify(self.policyManager, data)
self.assertTrue(vr.hasFurtherSteps,
"ConfigPolicyManager refresh occured sooner than specified")
self.assertEqual(vr.successCount, 0,
"ConfigPolicyManager called success callback with pending ValidationRequest")
self.assertEqual(vr.failureCount, 0,
"ConfigPolicyManager called failure callback with pending ValidationRequest")
time.sleep(6)
# now we should find it
vr = doVerify(self.policyManager, data)
self.assertFalse(vr.hasFurtherSteps,
"ConfigPolicyManager did not refresh certificate store")
self.assertEqual(vr.successCount, 1,
"Verification success called {} times instead of 1".format(
vr.successCount))
self.assertEqual(vr.failureCount, 0,
"ConfigPolicyManager did not verify valid signed data")
示例5: setDefaultCertificateNameForKey
def setDefaultCertificateNameForKey(self, keyName, certificateName):
"""
Set the default certificate name for the corresponding key
:param Name keyName: not used
:param Name certificateName: The certificate name.
"""
if not self.doesCertificateExist(certificateName):
raise SecurityException("Certificate does not exist")
keyName = IdentityCertificate.certificateNameToPublicKeyName(certificateName)
identityUri = keyName.getPrefix(-1).toUri()
keyId = keyName.get(-1).toEscapedString()
try:
cursor = None
currentDefault = self.getDefaultCertificateNameForKey(keyName)
except SecurityException:
pass
else:
cursor = self._database.cursor()
cursor.execute("UPDATE Certificate SET default_cert=0 WHERE cert_name=? AND identity_name=? AND key_identifier=?",
(currentDefault.toUri(), identityUri, keyId))
if cursor is None:
cursor = self._database.cursor()
cursor.execute("UPDATE Certificate SET default_cert=1 WHERE cert_name=? AND identity_name=? AND key_identifier=?",
(certificateName.toUri(), identityUri, keyId))
self._database.commit()
cursor.close()
示例6: test_create_d_key_data
def test_create_d_key_data(self):
# Create the group manager.
manager = GroupManager(
Name("Alice"), Name("data_type"),
Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1,
self.keyChain)
newCertificateBlob = self.certificate.wireEncode()
newCertificate = IdentityCertificate()
newCertificate.wireDecode(newCertificateBlob)
# Encrypt the D-KEY.
data = manager._createDKeyData(
"20150825T000000", "20150827T000000", Name("/ndn/memberA/KEY"),
self.decryptKeyBlob, newCertificate.getPublicKeyInfo().getKeyDer())
# Verify the encrypted D-KEY.
dataContent = data.getContent()
# Get the nonce key.
# dataContent is a sequence of the two EncryptedContent.
encryptedNonce = EncryptedContent()
encryptedNonce.wireDecode(dataContent)
self.assertEqual(0, encryptedNonce.getInitialVector().size())
self.assertEqual(EncryptAlgorithmType.RsaOaep, encryptedNonce.getAlgorithmType())
blobNonce = encryptedNonce.getPayload()
decryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
nonce = RsaAlgorithm.decrypt(self.decryptKeyBlob, blobNonce, decryptParams)
# Get the D-KEY.
# Use the size of encryptedNonce to find the start of encryptedPayload.
payloadContent = dataContent.buf()[encryptedNonce.wireEncode().size():]
encryptedPayload = EncryptedContent()
encryptedPayload.wireDecode(payloadContent)
self.assertEqual(16, encryptedPayload.getInitialVector().size())
self.assertEqual(EncryptAlgorithmType.AesCbc, encryptedPayload.getAlgorithmType())
decryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
decryptParams.setInitialVector(encryptedPayload.getInitialVector())
blobPayload = encryptedPayload.getPayload()
largePayload = AesAlgorithm.decrypt(nonce, blobPayload, decryptParams)
self.assertTrue(largePayload.equals(self.decryptKeyBlob))
示例7: getCertificate
def getCertificate(self, certificateName, allowAny = False):
"""
Get a certificate from the identity storage.
:param Name certificateName: The name of the requested certificate.
:param bool allowAny: (optional) If False, only a valid certificate will
be returned, otherwise validity is disregarded. If omitted,
allowAny is False.
:return: The requested certificate. If not found, return None.
:rtype: IdentityCertificate
"""
certificateNameUri = certificateName.toUri()
if not (certificateNameUri in self._certificateStore):
# Not found. Silently return None.
return None
certificate = IdentityCertificate()
certificate.wireDecode(self._certificateStore[certificateNameUri])
return certificate
示例8: __init__
def __init__(self, face):
# Set up face
self.face = face
self.databaseFilePath = "policy_config/test_consumer.db"
try:
os.remove(self.databaseFilePath)
except OSError:
# no such file
pass
self.groupName = Name("/org/openmhealth/zhehao")
# Set up the keyChain.
identityStorage = BasicIdentityStorage()
privateKeyStorage = FilePrivateKeyStorage()
self.keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
# Authorized identity
identityName = Name("/org/openmhealth/dvu-python-3")
# Unauthorized identity
#identityName = Name("/org/openmhealth/dvu-python-1")
self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
self.face.setCommandSigningInfo(self.keyChain, self.certificateName)
consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName)
consumerCertificate = identityStorage.getCertificate(self.certificateName)
self.consumer = Consumer(
face, self.keyChain, self.groupName, identityName,
Sqlite3ConsumerDb(self.databaseFilePath))
# TODO: Read the private key to decrypt d-key...this may or may not be ideal
base64Content = None
with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile:
print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")
base64Content = keyFile.read()
#print base64Content
der = Blob(base64.b64decode(base64Content), False)
self.consumer.addDecryptionKey(consumerKeyName, der)
self.memoryContentCache = MemoryContentCache(self.face)
self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
self.memoryContentCache.add(consumerCertificate)
accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time())))
self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout)
print "Access request interest name: " + accessRequestInterest.getName().toUri()
self.consumeCatalog = True
return
示例9: _updateDeviceCapabilities
def _updateDeviceCapabilities(self, interest):
"""
Take the received capabilities update interest and update our directory listings.
"""
# we assume the sender is the one who signed the interest...
signature = self._policyManager._extractSignature(interest)
certificateName = signature.getKeyLocator().getKeyName()
senderIdentity = IdentityCertificate.certificateNameToPublicKeyName(certificateName).getPrefix(-1)
self.log.info('Updating capabilities for {}'.format(senderIdentity.toUri()))
# get the params from the interest name
messageComponent = interest.getName().get(self.prefix.size()+1)
message = UpdateCapabilitiesCommandMessage()
ProtobufTlv.decode(message, messageComponent.getValue())
# we remove all the old capabilities for the sender
tempDirectory = defaultdict(list)
for keyword in self._directory:
tempDirectory[keyword] = [cap for cap in self._directory[keyword]
if not senderIdentity.match(Name(cap['name']))]
# then we add the ones from the message
for capability in message.capabilities:
capabilityPrefix = Name()
for component in capability.commandPrefix.components:
capabilityPrefix.append(component)
commandUri = capabilityPrefix.toUri()
if not senderIdentity.match(capabilityPrefix):
self.log.error("Node {} tried to register another prefix: {} - ignoring update".format(
senderIdentity.toUri(),commandUri))
else:
for keyword in capability.keywords:
allUris = [info['name'] for info in tempDirectory[keyword]]
if capabilityPrefix not in allUris:
listing = {'signed':capability.needsSignature,
'name':commandUri}
tempDirectory[keyword].append(listing)
self._directory= tempDirectory
示例10: addCertificate
def addCertificate(self, certificate):
"""
Add a certificate to the identity storage.
:param IdentityCertificate certificate: The certificate to be added.
This makes a copy of the certificate.
"""
#TODO: actually check validity of certificate timestamp
certificateName = certificate.getName()
if self.doesCertificateExist(certificateName):
raise SecurityException("Certificate has already been installed!")
certCopy = IdentityCertificate(certificate)
makeDefault = 0
keyName = certCopy.getPublicKeyName()
keyInfo = certCopy.getPublicKeyInfo()
if not self.doesKeyExist(keyName):
self.addKey(keyName, keyInfo.getKeyType(), keyInfo.getKeyDer())
makeDefault = 1
else:
# see if the key we already have matches this certificate
keyBlob = self.getKey(keyName)
if (keyBlob.isNull() or keyBlob.toBuffer() !=
keyInfo.getKeyDer().toBuffer()):
raise SecurityException("Certificate does not match public key")
keyId = keyName.get(-1).toEscapedString()
identityUri = keyName.getPrefix(-1).toUri()
certIssuer = certCopy.getSignature().getKeyLocator().getKeyName().toUri()
encodedCert = buffer(bytearray(certCopy.wireEncode().buf()))
notBefore = certCopy.getNotBefore()
notAfter = certCopy.getNotAfter()
cursor = self._database.cursor()
cursor.execute("INSERT INTO Certificate VALUES(?,?,?,?,?,?,?,?,?)",
(certificateName.toUri(), certIssuer, identityUri, keyId,
notBefore, notAfter, encodedCert, 1, makeDefault))
self._database.commit()
cursor.close()
示例11: __init__
def __init__(self, face, encryptResult, defaultPrefix, link = None):
# Set up face
self.face = face
self._encryptResult = encryptResult
self._link = link
self.databaseFilePath = "policy_config/test_consumer_dpu.db"
try:
os.remove(self.databaseFilePath)
except OSError:
# no such file
pass
self.groupName = Name(defaultPrefix)
# Set up the keyChain.
identityStorage = BasicIdentityStorage()
privateKeyStorage = FilePrivateKeyStorage()
self.keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
# Authorized identity
identityName = Name("/ndn/edu/basel/dpu")
# Function name: the function that this DPU provides
self._functionName = "bounding_box"
self._identityName = identityName
self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
# TODO: if using BasicIdentityStorage and FilePrivateKeyStorage
# For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error
#self.keyChain.installIdentityCertificate()
self.memoryContentCache = MemoryContentCache(self.face)
try:
commandSigningKeyChain = KeyChain()
print "Default certificate name is: " + self.keyChain.getDefaultCertificateName().toUri()
self.face.setCommandSigningInfo(commandSigningKeyChain, commandSigningKeyChain.getDefaultCertificateName())
self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
except SecurityException as e:
print str(e)
print "Cannot use default certificate, use created certificate in FilePrivateKeyStorage"
self.face.setCommandSigningInfo(self.keyChain, self.certificateName)
self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName)
consumerCertificate = identityStorage.getCertificate(self.certificateName)
self.consumer = Consumer(
face, self.keyChain, self.groupName, identityName,
Sqlite3ConsumerDb(self.databaseFilePath))
# TODO: Read the private key to decrypt d-key...this may or may not be ideal
base64Content = None
with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile:
print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")
base64Content = keyFile.read()
#print base64Content
der = Blob(base64.b64decode(base64Content), False)
self.consumer.addDecryptionKey(consumerKeyName, der)
self.memoryContentCache.add(consumerCertificate)
accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time())))
self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout)
print "Access request interest name: " + accessRequestInterest.getName().toUri()
self._tasks = dict()
return
示例12: 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
示例13: TestGroupManager
class TestGroupManager(ut.TestCase):
def setUp(self):
# Reuse the policy_config subdirectory for the temporary SQLite files.
self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db"
try:
os.remove(self.dKeyDatabaseFilePath)
except OSError:
# no such file
pass
self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db"
try:
os.remove(self.eKeyDatabaseFilePath)
except OSError:
# no such file
pass
self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db"
try:
os.remove(self.intervalDatabaseFilePath)
except OSError:
# no such file
pass
self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db"
try:
os.remove(self.groupKeyDatabaseFilePath)
except OSError:
# no such file
pass
params = RsaKeyParams()
memberDecryptKey = RsaAlgorithm.generateKey(params)
self.decryptKeyBlob = memberDecryptKey.getKeyBits()
memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob)
self.encryptKeyBlob = memberEncryptKey.getKeyBits()
# Generate the certificate.
self.certificate = IdentityCertificate()
self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
contentPublicKey = PublicKey(self.encryptKeyBlob)
self.certificate.setPublicKeyInfo(contentPublicKey)
self.certificate.setNotBefore(0)
self.certificate.setNotAfter(0)
self.certificate.encode()
signatureInfoBlob = Blob(SIG_INFO, False)
signatureValueBlob = Blob(SIG_VALUE, False)
signature = TlvWireFormat.get().decodeSignatureInfoAndValue(
signatureInfoBlob.buf(), signatureValueBlob.buf())
self.certificate.setSignature(signature)
self.certificate.wireEncode()
# Set up the keyChain.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
identityName = Name("TestGroupManager")
self.keyChain.createIdentityAndCertificate(identityName)
self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
def tearDown(self):
try:
os.remove(self.dKeyDatabaseFilePath)
except OSError:
pass
try:
os.remove(self.eKeyDatabaseFilePath)
except OSError:
pass
try:
os.remove(self.intervalDatabaseFilePath)
except OSError:
pass
try:
os.remove(self.groupKeyDatabaseFilePath)
except OSError:
pass
def setManager(self, manager):
# Set up the first schedule.
schedule1 = Schedule()
interval11 = RepetitiveInterval(
Schedule.fromIsoString("20150825T000000"),
Schedule.fromIsoString("20150827T000000"), 5, 10, 2,
RepetitiveInterval.RepeatUnit.DAY)
interval12 = RepetitiveInterval(
Schedule.fromIsoString("20150825T000000"),
Schedule.fromIsoString("20150827T000000"), 6, 8, 1,
RepetitiveInterval.RepeatUnit.DAY)
interval13 = RepetitiveInterval(
Schedule.fromIsoString("20150827T000000"),
Schedule.fromIsoString("20150827T000000"), 7, 8)
schedule1.addWhiteInterval(interval11)
schedule1.addWhiteInterval(interval12)
schedule1.addBlackInterval(interval13)
#.........这里部分代码省略.........
示例14: setUp
def setUp(self):
# Reuse the policy_config subdirectory for the temporary SQLite files.
self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db"
try:
os.remove(self.dKeyDatabaseFilePath)
except OSError:
# no such file
pass
self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db"
try:
os.remove(self.eKeyDatabaseFilePath)
except OSError:
# no such file
pass
self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db"
try:
os.remove(self.intervalDatabaseFilePath)
except OSError:
# no such file
pass
self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db"
try:
os.remove(self.groupKeyDatabaseFilePath)
except OSError:
# no such file
pass
params = RsaKeyParams()
memberDecryptKey = RsaAlgorithm.generateKey(params)
self.decryptKeyBlob = memberDecryptKey.getKeyBits()
memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob)
self.encryptKeyBlob = memberEncryptKey.getKeyBits()
# Generate the certificate.
self.certificate = IdentityCertificate()
self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
contentPublicKey = PublicKey(self.encryptKeyBlob)
self.certificate.setPublicKeyInfo(contentPublicKey)
self.certificate.setNotBefore(0)
self.certificate.setNotAfter(0)
self.certificate.encode()
signatureInfoBlob = Blob(SIG_INFO, False)
signatureValueBlob = Blob(SIG_VALUE, False)
signature = TlvWireFormat.get().decodeSignatureInfoAndValue(
signatureInfoBlob.buf(), signatureValueBlob.buf())
self.certificate.setSignature(signature)
self.certificate.wireEncode()
# Set up the keyChain.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
identityName = Name("TestGroupManager")
self.keyChain.createIdentityAndCertificate(identityName)
self.keyChain.getIdentityManager().setDefaultIdentity(identityName)