本文整理汇总了Python中pyndn.security.KeyChain.sign方法的典型用法代码示例。如果您正苦于以下问题:Python KeyChain.sign方法的具体用法?Python KeyChain.sign怎么用?Python KeyChain.sign使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.security.KeyChain
的用法示例。
在下文中一共展示了KeyChain.sign方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrap_content
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
def wrap_content(self, name, content, key=None, key_locator=None):
"""
@param name - name of the data
@param content - data to be wrapped
@param key - key used to sign the data
@return the content object created
wraps the given name and content into a content object
"""
co = Data(Name(name))
co.setContent(content)
co.getMetaInfo().setFreshnessPeriod(5000)
co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
identityManager = IdentityManager(identityStorage, privateKeyStorage)
keyChain = KeyChain(identityManager, None)
# Initialize the storage.
keyName = Name("/ndn/bms/DSK-default")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(keyName, DEFAULT_PUBLIC_KEY_DER,
DEFAULT_PRIVATE_KEY_DER)
keyChain.sign(co, certificateName)
_data = co.wireEncode()
return _data.toRawStr()
示例2: Producer
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class Producer(object):
def __init__(self, delay=None):
self.delay = delay
self.nDataServed = 0
self.isDone = False
def run(self, prefix):
self.keyChain = KeyChain()
self.consoleThread = ConsoleThread()
self.consoleThread.start()
# The default Face will connect using a Unix socket
face = Face()
prefix = Name(prefix)
# Use the system default key chain and certificate name to sign commands.
face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())
# Also use the default certificate name to sign data packets.
face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)
print "Registering prefix", prefix.toUri()
while not self.isDone:
face.processEvents()
time.sleep(0.01)
def onInterest(self, prefix, interest, transport, registeredPrefixId):
global stopServing
if stopServing:
print "refusing to serve " + interest.getName().toUri()
self.consoleThread.join()
print "join'd thread"
return
if self.delay is not None:
time.sleep(self.delay)
interestName = interest.getName()
data = Data(interestName)
data.setContent("Hello " + interestName.toUri())
data.getMetaInfo().setFreshnessPeriod(3600 * 1000)
self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
transport.send(data.wireEncode().toBuffer())
self.nDataServed += 1
print "Replied to: %s (#%d)" % (interestName.toUri(), self.nDataServed)
def onRegisterFailed(self, prefix):
print "Register failed for prefix", prefix.toUri()
示例3: Producer
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class Producer(object):
def __init__(self):
self.keyChain = KeyChain()
self.isDone = False
def run(self, namespace):
# Create a connection to the local forwarder over a Unix socket
face = Face()
prefix = Name(namespace)
# Use the system default key chain and certificate name to sign commands.
face.setCommandSigningInfo(self.keyChain, \
self.keyChain.getDefaultCertificateName())
# Also use the default certificate name to sign Data packets.
face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)
print "Registering prefix", prefix.toUri()
# Run the event loop forever. Use a short sleep to
# prevent the Producer from using 100% of the CPU.
while not self.isDone:
face.processEvents()
time.sleep(0.01)
def onInterest(self, prefix, interest, transport, registeredPrefixId):
interestName = interest.getName()
data = Data(interestName)
data.setContent("Hello, " + interestName.toUri())
hourMilliseconds = 3600 * 1000
data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)
self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
transport.send(data.wireEncode().toBuffer())
print "Replied to: %s" % interestName.toUri()
def onRegisterFailed(self, prefix):
print "Register failed for prefix", prefix.toUri()
self.isDone = True
示例4: main
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [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)
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
# Initialize the storage.
keyName = Name("/testname/DSK-123")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
makeOnVerifyFailed("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, certificateName)
dump("")
dump("Freshly-signed Data:")
dumpData(freshData)
keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
makeOnVerifyFailed("Freshly-signed Data"))
示例5: main
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [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"))
示例6: benchmarkEncodeDataSeconds
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto):
"""
Loop to encode a data packet nIterations times.
:param int nIterations: The number of iterations.
:param bool useComplex: If true, use a large name, large content and all
fields. If false, use a small name, small content and only required
fields.
:param bool useCrypto: If true, sign the data packet. If false, use a blank
signature.
:return: A tuple (duration, encoding) where duration is the number of
seconds for all iterations and encoding is the wire encoding.
:rtype: (float, Blob)
"""
if useComplex:
# Use a large name and content.
name = Name(
"/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00")
contentString = ""
count = 1
contentString += "%d" % count
count += 1
while len(contentString) < 1115:
contentString += " %d" % count
count += 1
content = Name.fromEscapedString(contentString)
else:
# Use a small name and content.
name = Name("/test")
content = Name.fromEscapedString("abc")
finalBlockId = Name("/%00")[0]
# Initialize the private key storage in case useCrypto is true.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
keyName = Name("/testname/DSK-123")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
# Set up signatureBits in case useCrypto is false.
signatureBits = Blob(bytearray(256))
emptyBlob = Blob([])
start = getNowSeconds()
for i in range(nIterations):
data = Data(name)
data.setContent(content)
if useComplex:
data.getMetaInfo().setFreshnessPeriod(1000)
data.getMetaInfo().setFinalBlockId(finalBlockId)
if useCrypto:
# This sets the signature fields.
keyChain.sign(data, certificateName)
else:
# Imitate IdentityManager.signByCertificate to set up the signature
# fields, but don't sign.
sha256Signature = data.getSignature()
keyLocator = sha256Signature.getKeyLocator()
keyLocator.setType(KeyLocatorType.KEYNAME)
keyLocator.setKeyName(certificateName)
sha256Signature.setSignature(signatureBits)
encoding = data.wireEncode()
finish = getNowSeconds()
return (finish - start, encoding)
示例7: TestFaceRegisterMethods
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class TestFaceRegisterMethods(ut.TestCase):
def setUp(self):
self.face_in = Face()
self.face_out = Face()
self.keyChain = KeyChain()
def tearDown(self):
self.face_in.shutdown()
self.face_out.shutdown()
def test_register_prefix_response(self):
prefixName = Name("/test")
self.face_in.setCommandSigningInfo(self.keyChain,
self.keyChain.getDefaultCertificateName())
interestCallbackCount = [0]
def onInterest(prefix, interest, transport, prefixID):
interestCallbackCount[0] += 1
data = Data(interest.getName())
data.setContent("SUCCESS")
self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())
encodedData = data.wireEncode()
transport.send(encodedData.toBuffer())
failedCallback = Mock()
self.face_in.registerPrefix(prefixName, onInterest, failedCallback)
# Give the 'server' time to register the interest.
time.sleep(1)
# express an interest on another face
dataCallback = Mock()
timeoutCallback = Mock()
# now express an interest on this new face, and see if onInterest is called
# Add the timestamp so it is unique and we don't get a cached response.
interestName = prefixName.append("hello" + repr(time.time()))
self.face_out.expressInterest(interestName, dataCallback, timeoutCallback)
# Process events for the in and out faces.
timeout = 10000
startTime = getNowMilliseconds()
while True:
if getNowMilliseconds() - startTime >= timeout:
break
self.face_in.processEvents()
self.face_out.processEvents()
done = True
if interestCallbackCount[0] == 0 and failedCallback.call_count == 0:
# Still processing face_in.
done = False
if dataCallback.call_count == 0 and timeoutCallback.call_count == 0:
# Still processing face_out.
done = False
if done:
break
time.sleep(0.01)
self.assertEqual(failedCallback.call_count, 0, 'Failed to register prefix at all')
self.assertEqual(interestCallbackCount[0], 1, 'Expected 1 onInterest callback, got '+str(interestCallbackCount[0]))
self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))
onDataArgs = dataCallback.call_args[0]
# check the message content
data = onDataArgs[1]
expectedBlob = Blob("SUCCESS")
self.assertTrue(expectedBlob == data.getContent(), 'Data received on face does not match expected format')
示例8: __init__
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class SensorDataLogger:
def __init__(self, data_interval):
# connect to modbus
self.master = modbus_tcp.TcpMaster("172.17.66.246", 502)
# self.master.set_timeout(120) # in seconds
# connect to local repo
self.publisher = RepoSocketPublisher(12345)
self.prefix = "/ndn/ucla.edu/bms/strathmore/data/demand"
self.interval = data_interval # in seconds
self.loadKey()
def loadKey(self):
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keychain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
f = open(key_file, "r")
self.key = RSA.importKey(f.read())
self.key_name = Name(bld_root).append(getKeyID(self.key))
key_pub_der = bytearray(self.key.publickey().exportKey(format="DER"))
key_pri_der = bytearray(self.key.exportKey(format="DER"))
self.identityStorage.addKey(self.key_name, KeyType.RSA, Blob(key_pub_der))
self.privateKeyStorage.setKeyPairForKeyName(self.key_name, key_pub_der, key_pri_der)
self.cert_name = self.key_name.getSubName(0, self.key_name.size() - 1).append(
"KEY").append(self.key_name[-1]).append("ID-CERT").append("0")
print 'KeyName = ' + self.key_name.toUri()
print 'CertName = ' + self.cert_name.toUri()
def publishData(self, key, key_ts, payload, timestamp):
data = Data(Name(self.prefix).append(bytearray(timestamp)))
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC, iv)
data.setContent(bytearray(key_ts + iv + encryptor.encrypt(pad(json.dumps(payload)))))
data.getMetaInfo().setFreshnessPeriod(5000)
self.keychain.sign(data, self.cert_name)
self.publisher.put(data)
#print payload
#print data.getName().toUri()
def run(self):
key_ts = struct.pack('!Q', int(time.time() * 1000))
key = Random.new().read(32)
kds_count = -1
while (True):
# KDS
kds_count = kds_count + 1
if kds_count % 120 == 0:
key_ts = struct.pack("!Q", int(time.time() * 1000))
key = Random.new().read(32)
kds_thread = kds.SimpleKDSPublisher(Name(bld_root), self.keychain, self.cert_name, key, key_ts)
kds_thread.start()
kds_count = 0
# Data
now = int(time.time() * 1000) # in milliseconds
a = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 166, 1)
b = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 167, 1)
vln = (b[0] << 16) + a[0]
c = self.master.execute(1, cst.READ_HOLDING_REGISTERS, 150, 1)
la = c[0]
payload = {'ts': now, 'vlna': vln, 'la': la}
timestamp = struct.pack("!Q", now) # timestamp is in milliseconds
self.publishData(key, key_ts, payload, timestamp)
time.sleep(self.interval)
示例9: LightController
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class LightController():
shouldSign = False
COLORS_PER_LIGHT = 3
STRAND_SIZE = 50
def __init__(self, nStrands=1, myIP="192.168.1.1", lightIP="192.168.1.50", prefix="/testlight"):
self.log = logging.getLogger("LightController")
self.log.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setLevel(logging.WARNING)
self.log.addHandler(sh)
fh = logging.FileHandler("LightController.log")
fh.setLevel(logging.INFO)
self.log.addHandler(fh)
self.payloadBuffer = [[0]*self.STRAND_SIZE*self.COLORS_PER_LIGHT for n in range(nStrands)]
self.kinetsender = KinetSender(myIP, lightIP, nStrands, self.STRAND_SIZE*self.COLORS_PER_LIGHT)
self.registerFailed = False
self.done = False
self.prefix = Name(prefix)
self.keychain = KeyChain()
self.certificateName = self.keychain.getDefaultCertificateName()
# XXX: we should get a thread for this or something!
def start(self):
self.face = Face()
self.face.setCommandSigningInfo(self.keychain, self.certificateName)
self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed)
while self.face is not None:
self.face.processEvents()
if self.registerFailed:
self.stop()
break
#time.sleep(0.001)
def stop(self):
self.kinetsender.stop = True
self.kinetsender.complete.wait()
self.face.shutdown()
self.face = None
def signData(self, data):
if LightController.shouldSign:
self.keychain.sign(data, self.certificateName)
else:
data.setSignature(Sha256WithRsaSignature())
def setPayloadColor(self, strand, color):
# will expand this to allow the repeats, etc
self.payloadBuffer[strand] = [int(color.r)&0xff, int(color.g)&0xff, int(color.b)&0xff]*self.STRAND_SIZE
def onLightingCommand(self, prefix, interest, transport, prefixId):
interestName = Name(interest.getName())
#d = Data(interest.getName().getPrefix(prefix.size()+1))
d = Data(interest.getName())
# get the command parameters from the name
try:
commandComponent = interest.getName().get(prefix.size())
commandParams = interest.getName().get(prefix.size()+1)
lightingCommand = LightCommandMessage()
ProtobufTlv.decode(lightingCommand, commandParams.getValue())
self.log.info("Command: " + commandComponent.toEscapedString())
requestedColor = lightingCommand.command.pattern.colors[0]
colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
self.log.info("Requested color: " + colorStr)
self.setPayloadColor(0, requestedColor)
self.sendLightPayload(1)
d.setContent("Gotcha: " + colorStr+ "\n")
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
d.getMetaInfo().setFinalBlockID(0)
self.signData(d)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
def onRegisterFailed(self, prefix):
self.log.error("Could not register " + prefix.toUri())
print "Register failed!"
self.registerFailed = True
def sendLightPayload(self, port):
self.kinetsender.setPayload(port, self.payloadBuffer[port-1])
示例10: RegisterSongList
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class RegisterSongList(object):
def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):
logging.basicConfig()
self.device = "PC1"
self.deviceComponent = Name.Component(self.device)
self.excludeDevice = None
self.prefix = Name(prefix)
self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
self.keychain = KeyChain()
self.certificateName = self.keychain.getDefaultCertificateName()
self.address = ""
self._isStopped = True
def start(self):
print "reg start"
self.loop = asyncio.get_event_loop()
self.face = ThreadsafeFace(self.loop,self.address)
self.face.setCommandSigningInfo(self.keychain,self.certificateName)
self.face.registerPrefix(self.prefix,self.onInterest,self.onRegisterFailed)
self._isStopped = False
self.face.stopWhen(lambda:self._isStopped)
try:
self.loop.run_forever()
except KeyboardInterrupt:
sys.exit()
finally:
self.stop()
def stop(self):
self.loop.close()
self.face.shutdown()
self.face = None
sys.exit(1)
def signData(self,data):
data.setSignature(Sha256WithRsaSignature())
def onInterest(self, prefix, interest, transport, registeredPrefixId):
print "received interest"
initInterest = Name(interest.getName())
print "interest name:",initInterest.toUri()
d = Data(interest.getName().append(self.deviceComponent))
try:
print "start to set data's content"
currentString = ','.join(currentList)
d.setContent("songList of " +self.device+":"+currentString+ "\n")
self.face.registerPrefix(self.changePrefix,self.onInterest,self.onRegisterFailed)
except KeyboardInterrupt:
print "key interrupt"
sys.exit(1)
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
self.keychain.sign(d,self.certificateName)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
print d.getName().toUri()
print d.getContent()
self.loop.close()
self.face.shutdown()
self.face = None
def onRegisterFailed(self, prefix):
self.log.error("Could not register " + prefix.toUri())
self.stop()
示例11: TestRegexMatching
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
#.........这里部分代码省略.........
dataName1 = Name('/SecurityTestSecRule/Basic')
dataName2 = Name('/SecurityTestSecRule/Basic/More')
dataName3 = Name('/SecurityTestSecRule/')
dataName4 = Name('/SecurityTestSecRule/Other/TestData')
dataName5 = Name('/Basic/Data')
matchedRule1 = policyManager._findMatchingRule(dataName1, 'data')
matchedRule2 = policyManager._findMatchingRule(dataName2, 'data')
matchedRule3 = policyManager._findMatchingRule(dataName3, 'data')
matchedRule4 = policyManager._findMatchingRule(dataName4, 'data')
matchedRule5 = policyManager._findMatchingRule(dataName5, 'data')
self.assertIsNotNone(matchedRule1)
self.assertIsNone(matchedRule2)
self.assertIsNotNone(matchedRule3)
self.assertNotEqual(matchedRule3, matchedRule1,
"Rule regex matched extra components")
self.assertIsNotNone(matchedRule4)
self.assertNotEqual(matchedRule4, matchedRule1,
"Rule regex matched with missing component")
self.assertIsNone(matchedRule5)
def test_checker_hierarchical(self):
policyManager = ConfigPolicyManager("policy_config/hierarchical_ruleset.conf")
dataName1 = Name('/SecurityTestSecRule/Basic/Data1')
dataName2 = Name('/SecurityTestSecRule/Basic/Longer/Data2')
data1 = Data(dataName1)
data2 = Data(dataName2)
matchedRule = policyManager._findMatchingRule(dataName1, 'data')
self.assertEqual(matchedRule,
policyManager._findMatchingRule(dataName2, 'data'))
self.keyChain.sign(data1, self.defaultCertName)
self.keyChain.sign(data2, self.defaultCertName)
signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
signatureName2 = data2.getSignature().getKeyLocator().getKeyName()
self.assertFalse(policyManager._checkSignatureMatch(signatureName1,
dataName1, matchedRule),
"Hierarchical matcher matched short data name to long key name")
self.assertTrue(policyManager._checkSignatureMatch(signatureName2,
dataName2, matchedRule))
self.keyChain.sign(data1, self.shortCertName)
self.keyChain.sign(data2, self.shortCertName)
signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
signatureName2 = data2.getSignature().getKeyLocator().getKeyName()
self.assertTrue(policyManager._checkSignatureMatch(signatureName1,
dataName1, matchedRule))
self.assertTrue(policyManager._checkSignatureMatch(signatureName2,
dataName2, matchedRule))
def test_hyperrelation(self):
policyManager = ConfigPolicyManager("policy_config/hyperrelation_ruleset.conf")
dataName = Name('/SecurityTestSecRule/Basic/Longer/Data2')
data1 = Data(dataName)
data2 = Data(dataName)
matchedRule = policyManager._findMatchingRule(dataName, 'data')
self.keyChain.sign(data1, self.defaultCertName)
self.keyChain.sign(data2, self.shortCertName)
signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
signatureName2 = data2.getSignature().getKeyLocator().getKeyName()
self.assertTrue(policyManager._checkSignatureMatch(signatureName1,
dataName, matchedRule))
self.assertFalse(policyManager._checkSignatureMatch(signatureName2,
dataName, matchedRule))
dataName = Name('/SecurityTestSecRule/Basic/Other/Data1')
data1 = Data(dataName)
data2 = Data(dataName)
matchedRule = policyManager._findMatchingRule(dataName, 'data')
self.keyChain.sign(data1, self.defaultCertName)
self.keyChain.sign(data2, self.shortCertName)
signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
signatureName2 = data2.getSignature().getKeyLocator().getKeyName()
self.assertFalse(policyManager._checkSignatureMatch(signatureName1,
dataName, matchedRule))
self.assertTrue(policyManager._checkSignatureMatch(signatureName2,
dataName, matchedRule))
def test_interest_matching(self):
# make sure we chop off timestamp, nonce, and signature info from
# signed interests
pass
示例12: IdentityManagementFixture
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class IdentityManagementFixture(object):
def __init__(self):
self._keyChain = KeyChain("pib-memory:", "tpm-memory:")
self._identityNames = set()
self._certificateFiles = set()
def saveCertificateToFile(self, data, filePath):
"""
:param Data data: The certificate to save.
:param str filePath: The file path, which should be writable.
:return: True if successful.
:rtype: bool
"""
self._certificateFiles.add(filePath)
try:
encoding = data.wireEncode()
encodedCertificate = Common.base64Encode(encoding.toBytes(), True)
with open(filePath, 'w') as keyFile:
keyFile.write(encodedCertificate)
return True
except Exception:
return False
def addIdentity(self, identityName, params = None):
"""
Add an identity for the identityName.
:param Name identityName: The name of the identity.
:param KeyParams params: (optional) The key parameters if a key needs to
be generated for the identity. If omitted, use
KeyChain.getDefaultKeyParams().
:return: The created PibIdentity instance.
:rtype: PibIdentity
"""
if params == None:
params = KeyChain.getDefaultKeyParams()
identity = self._keyChain.createIdentityV2(identityName, params)
self._identityNames.add(identityName)
return identity
def saveCertificate(identity, filePath):
"""
Save the identity's certificate to a file.
:param PibIdentity identity: The PibIdentity.
:param str filePath: The file path, which should be writable.
:return: True if successful.
:rtype: str
"""
try:
certificate = identity.getDefaultKey().getDefaultCertificate()
return self.saveCertificateToFile(certificate, filePath)
except Pib.Error:
return False
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
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)
#.........这里部分代码省略.........
示例13: TestProducer
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class TestProducer(ut.TestCase):
def setUp(self):
self.decryptionKeys = {} # key: Name, value: Blob
self.encryptionKeys = {} # key: Name, value: Data
# Reuse the policy_config subdirectory for the temporary SQLite files.
self.databaseFilePath = "policy_config/test.db"
try:
os.remove(self.databaseFilePath)
except OSError:
# no such file
pass
# Set up the keyChain.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
identityName = Name("TestProducer")
self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
def tearDown(self):
try:
os.remove(self.databaseFilePath)
except OSError:
pass
def createEncryptionKey(self, eKeyName, timeMarker):
params = RsaKeyParams()
eKeyName = Name(eKeyName)
eKeyName.append(timeMarker)
dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits()
self.decryptionKeys[eKeyName] = dKeyBlob
keyData = Data(eKeyName)
keyData.setContent(eKeyBlob)
self.keyChain.sign(keyData, self.certificateName)
self.encryptionKeys[eKeyName] = keyData
def test_content_key_request(self):
prefix = Name("/prefix")
suffix = Name("/a/b/c")
expectedInterest = Name(prefix)
expectedInterest.append(Encryptor.NAME_COMPONENT_READ)
expectedInterest.append(suffix)
expectedInterest.append(Encryptor.NAME_COMPONENT_E_KEY)
cKeyName = Name(prefix)
cKeyName.append(Encryptor.NAME_COMPONENT_SAMPLE)
cKeyName.append(suffix)
cKeyName.append(Encryptor.NAME_COMPONENT_C_KEY)
timeMarker = Name("20150101T100000/20150101T120000")
testTime1 = Schedule.fromIsoString("20150101T100001")
testTime2 = Schedule.fromIsoString("20150101T110001")
testTimeRounded1 = Name.Component("20150101T100000")
testTimeRounded2 = Name.Component("20150101T110000")
# Create content keys required for this test case:
for i in range(suffix.size()):
self.createEncryptionKey(expectedInterest, timeMarker)
expectedInterest = expectedInterest.getPrefix(-2).append(
Encryptor.NAME_COMPONENT_E_KEY)
expressInterestCallCount = [0]
# Prepare a TestFace to instantly answer calls to expressInterest.
class TestFace(object):
def __init__(self, handleExpressInterest):
self.handleExpressInterest = handleExpressInterest
def expressInterest(self, interest, onData, onTimeout):
return self.handleExpressInterest(interest, onData, onTimeout)
def handleExpressInterest(interest, onData, onTimeout):
expressInterestCallCount[0] += 1
interestName = Name(interest.getName())
interestName.append(timeMarker)
self.assertTrue(interestName in self.encryptionKeys)
onData(interest, self.encryptionKeys[interestName])
return 0
face = TestFace(handleExpressInterest)
# Verify that the content key is correctly encrypted for each domain, and
# the produce method encrypts the provided data with the same content key.
testDb = Sqlite3ProducerDb(self.databaseFilePath)
producer = Producer(prefix, suffix, face, self.keyChain, testDb)
contentKey = [None] # Blob
def checkEncryptionKeys(
result, testTime, roundedTime, expectedExpressInterestCallCount):
self.assertEqual(expectedExpressInterestCallCount,
expressInterestCallCount[0])
self.assertEqual(True, testDb.hasContentKey(testTime))
#.........这里部分代码省略.........
示例14: BaseNode
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
#.........这里部分代码省略.........
def start(self):
"""
Begins the event loop. After this, the node's Face is set up and it can
send/receive interests+data
"""
self.log.info("Starting up")
self.loop = asyncio.get_event_loop()
if (self.faceTransport == None or self.faceTransport == ''):
self.face = ThreadsafeFace(self.loop)
else:
self.face = ThreadsafeFace(self.loop, self.faceTransport, self.faceConn)
self.face.setCommandSigningInfo(self._keyChain, self.getDefaultCertificateName())
self._keyChain.setFace(self.face)
self._isStopped = False
self.beforeLoopStart()
try:
self.loop.run_forever()
except Exception as e:
self.log.exception(exc_info=True)
finally:
self.stop()
def stop(self):
"""
Stops the node, taking it off the network
"""
self.log.info("Shutting down")
self._isStopped = True
self.loop.stop()
###
# Data handling
###
def signData(self, data):
"""
Sign the data with our network certificate
:param pyndn.Data data: The data to sign
"""
self._keyChain.sign(data, self.getDefaultCertificateName())
def sendData(self, data, sign=True):
"""
Reply to an interest with a data packet, optionally signing it.
:param pyndn.Data data: The response data packet
:param boolean sign: (optional, default=True) Whether the response must be signed.
"""
if sign:
self.signData(data)
self.face.putData(data)
###
#
#
##
def onRegisterFailed(self, prefix):
"""
Called when the node cannot register its name with the forwarder
:param pyndn.Name prefix: The network name that failed registration
"""
if self.faceTransport != None and self.faceConn != None:
self.log.warn("Explicit face transport and connectionInfo: Could not register {}; expect a manual or autoreg on the other side.".format(prefix.toUri()))
elif self._registrationFailures < 5:
self._registrationFailures += 1
self.log.warn("Could not register {}, retry: {}/{}".format(prefix.toUri(), self._registrationFailures, 5))
self.face.registerPrefix(self.prefix, self._onCommandReceived, self.onRegisterFailed)
else:
self.log.info("Prefix registration failed")
self.stop()
def verificationFailed(self, dataOrInterest):
"""
Called when verification of a data packet or command interest fails.
:param pyndn.Data or pyndn.Interest: The packet that could not be verified
"""
self.log.info("Received invalid" + dataOrInterest.getName().toUri())
@staticmethod
def getSerial():
"""
Find and return the serial number of the Raspberry Pi. Provided in case
you wish to distinguish data from nodes with the same name by serial.
:return: The serial number extracted from device information in /proc/cpuinfo
:rtype: str
"""
try:
if PLATFORM == "raspberry pi":
with open('/proc/cpuinfo') as f:
for line in f:
if line.startswith('Serial'):
return line.split(':')[1].strip()
else:
return "todo"
except NameError:
return "todo"
示例15: __init__
# 需要导入模块: from pyndn.security import KeyChain [as 别名]
# 或者: from pyndn.security.KeyChain import sign [as 别名]
class PutFile:
def __init__(self, repoDataPrefix, repoCommandPrefix, face, loop):
self._repoCommandPrefix = repoCommandPrefix
self._dataName = Name(repoDataPrefix)
self._nDataToPrepare = 10
self._interestLifetime = 4000
self._mData = []
self._face = face
self._loop = loop
self._keyChain = KeyChain()
self._certificateName = self._keyChain.getDefaultCertificateName()
self._currentSegmentNo = 0
self._isFinished = False
self.insertStream = None
self.fileSize = 0
self._segmentSize = 1000
self._endBlockId = 0
self._count = 0
def start(self):
self._face.registerPrefix(self._dataName,self.onInterest,self.onRegisterFailed)
self.startInsertCommand();
# Just for appending segment number 0, making it encoded as %00%00, instead of %00 in PyNDN.
# Potential bug/loss of interoperability?
@staticmethod
def componentFromSingleDigitNumberWithMarkerCXX(number, marker):
value = []
value.append(number & 0xFF)
number >>= 8
value.reverse()
value.insert(0, marker)
return Name.Component(Blob(value, False))
def prepareNextData(self,referenceSegmentNo):
if (self._isFinished):
return
if self._mData:
maxSegmentNo = len(self._mData)
if(maxSegmentNo - referenceSegmentNo >= self._nDataToPrepare):
return
self._nDataToPrepare -= (maxSegmentNo - referenceSegmentNo)
# Prepare _nDataToPrepare number of data segments, and insert them into _mData
for i in range(0,self._nDataToPrepare):
buffer = self.insertStream.read(self._segmentSize)
if not buffer:
self._isFinished = True
# For now, repo-ng cannot handle FinalBlockID:
# ERROR: Invalid length for nonNegativeInteger (only 1, 2, 4, and 8 are allowed)
#d.getMetaInfo().setFinalBlockID(self._currentSegmentNo)
# using EndBlockId in repo protocol spec instead
break
if self._currentSegmentNo == 0:
dataName = Name(self._dataName).append(PutFile.componentFromSingleDigitNumberWithMarkerCXX(0, 0x00))
else:
dataName = Name(self._dataName).appendSegment(self._currentSegmentNo)
d = Data(dataName)
# Biggest mistake: wrong data name. Still finding out why, though
# Original one:
#d = Data(Name(self._dataName).append(self._currentSegmentNo))
print "Given data name", d.getName().toUri(), " Segment no", self._currentSegmentNo
d.setContent(buffer)
self._keyChain.sign(d, self._certificateName)
self._mData.append(d)
self._currentSegmentNo += 1
def startInsertCommand(self):
parameters = RepoCommandParameter()
parameters.setName(self._dataName)
parameters.setStartBlockId(0)
# Adding endBlockID so that repo does not crash on putfile
# should be replaced by FinalBlockID in data.metainfo, once that's fixed
parameters.setEndBlockId(math.trunc(self.fileSize/self._segmentSize))
#print (math.trunc(self.fileSize / self._segmentSize))
self._endBlockId = math.trunc(self.fileSize / self._segmentSize)
commandInterest = self.generateCommandInterest(self._repoCommandPrefix, "insert", parameters)
self._face.makeCommandInterest(commandInterest)
#print commandInterest.getName().toUri()
self._face.expressInterest(commandInterest,self.onInsertCommandResponse, self.onInsertCommandTimeout)
def onInsertCommandResponse(self,interest,data):
#.........这里部分代码省略.........