本文整理汇总了Python中pyndn.security.identity.MemoryIdentityStorage类的典型用法代码示例。如果您正苦于以下问题:Python MemoryIdentityStorage类的具体用法?Python MemoryIdentityStorage怎么用?Python MemoryIdentityStorage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MemoryIdentityStorage类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: benchmarkDecodeDataSeconds
def benchmarkDecodeDataSeconds(nIterations, useCrypto, encoding):
"""
Loop to decode a data packet nIterations times.
:param int nIterations: The number of iterations.
:param bool useCrypto: If true, verify the signature. If false, don't
verify.
:param Blob encoding: The wire encoding to decode.
"""
# 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))
start = getNowSeconds()
for i in range(nIterations):
data = Data()
data.wireDecode(encoding)
if useCrypto:
keyChain.verifyData(data, onVerified, onVerifyFailed)
finish = getNowSeconds()
return finish - start
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:30,代码来源:test_encode_decode_benchmark.py
示例2: test_prepare_unsigned_certificate
def test_prepare_unsigned_certificate(self):
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
identityManager = IdentityManager(identityStorage, privateKeyStorage)
keyName = Name("/test/ksk-1457560485494")
identityStorage.addKey(keyName, KeyType.RSA, Blob(PUBLIC_KEY))
subjectDescriptions = []
subjectDescriptions.append(CertificateSubjectDescription(
TEST_OID, "TEST NAME"))
newCertificate = identityManager.prepareUnsignedIdentityCertificate(
keyName,
keyName.getPrefix(1), self.toyCertNotBefore,
self.toyCertNotAfter, subjectDescriptions)
# Update the generated certificate version to equal the one in toyCert.
newCertificate.setName(
Name(newCertificate.getName().getPrefix(-1).append
(self.toyCert.getName().get(-1))))
# Make a copy to test encoding.
certificateCopy = IdentityCertificate(newCertificate)
self.assertEqual(
str(self.toyCert), str(certificateCopy),
"Prepared unsigned certificate dump does not have the expected format")
开发者ID:,项目名称:,代码行数:25,代码来源:
示例3: main
def main():
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage), None)
keyChain.setFace(face)
# 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)
echo = Echo(keyChain, certificateName)
prefix = Name("/testecho")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while echo._responseCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
开发者ID:bboalimoe,项目名称:PyNDN2,代码行数:29,代码来源:test_publish_async_ndnx.py
示例4: __init__
class CredentialStorage:
def __init__(self):
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage),
SelfVerifyPolicyManager(self.identityStorage))
keyName = Name("/testname/DSK-123")
self.defaultCertName = keyName[:-1].append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
ecdsaKeyName = Name("/testEcdsa/DSK-123")
self.ecdsaCertName = ecdsaKeyName[:-1].append(
"KEY").append(ecdsaKeyName[-1]).append("ID-CERT").append("0")
self.identityStorage.addKey(
keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
self.identityStorage.addKey(
ecdsaKeyName, KeyType.ECDSA, Blob(DEFAULT_EC_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
ecdsaKeyName, KeyType.ECDSA, DEFAULT_EC_PUBLIC_KEY_DER, DEFAULT_EC_PRIVATE_KEY_DER)
def signData(self, data, certificateName = None):
if certificateName is None:
certificateName = self.defaultCertName
self.keyChain.sign(data, certificateName)
def signDataWithSha256(self, data):
self.keyChain.signWithSha256(data)
def verifyData(self, data, verifiedCallback, failedCallback):
self.keyChain.verifyData(data, verifiedCallback, failedCallback)
开发者ID:,项目名称:,代码行数:34,代码来源:
示例5: wrap_content
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()
开发者ID:remap,项目名称:BMS-REPO,代码行数:31,代码来源:repo.py
示例6: benchmarkDecodeDataSeconds
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
"""
Loop to decode a data packet nIterations times.
:param int nIterations: The number of iterations.
:param bool useCrypto: If true, verify the signature. If false, don't
verify.
:param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
:param Blob encoding: The wire encoding to decode.
:return: The number of seconds for all iterations.
:rtype: float
"""
# Initialize the private key storage in case useCrypto is true.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
keyName = Name("/testname/DSK-123")
identityStorage.addKey(
keyName, keyType, Blob(
DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER))
start = getNowSeconds()
for i in range(nIterations):
data = Data()
data.wireDecode(encoding)
if useCrypto:
keyChain.verifyData(data, onVerified, onValidationFailed)
finish = getNowSeconds()
return finish - start
开发者ID:,项目名称:,代码行数:33,代码来源:
示例7: main
def main():
face = Face("localhost")
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage), None)
keyChain.setFace(face)
# Initialize the storage.
keyName = Name("/testname/DSK-reposerver")
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)
echo = RepoServer(keyChain, certificateName)
prefix = Name("/ndn/ucla.edu/bms")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while True:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
开发者ID:remap,项目名称:BMS-REPO,代码行数:28,代码来源:server.py
示例8: main
def main():
interest = Interest()
interest.wireDecode(TlvInterest)
dump("Interest:")
dumpInterest(interest)
# Set the name again to clear the cached encoding so we encode again.
interest.setName(interest.getName())
encoding = interest.wireEncode()
dump("")
dump("Re-encoded interest", encoding.toHex())
reDecodedInterest = Interest()
reDecodedInterest.wireDecode(encoding)
dump("Re-decoded Interest:")
dumpInterest(reDecodedInterest)
freshInterest = Interest(Name("/ndn/abc"))
freshInterest.setMustBeFresh(False)
dump(freshInterest.toUri())
freshInterest.setMinSuffixComponents(4)
freshInterest.setMaxSuffixComponents(6)
freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
freshInterest.getKeyLocator().setKeyData(bytearray(
[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
freshInterest.setInterestLifetimeMilliseconds(30000)
freshInterest.setChildSelector(1)
freshInterest.setMustBeFresh(True);
freshInterest.setScope(2)
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)
# Make a Face just so that we can sign the interest.
face = Face("localhost")
face.setCommandSigningInfo(keyChain, certificateName)
face.makeCommandInterest(freshInterest)
reDecodedFreshInterest = Interest()
reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
dump("")
dump("Re-decoded fresh Interest:")
dumpInterest(reDecodedFreshInterest)
keyChain.verifyInterest(
reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"),
makeOnVerifyFailed("Freshly-signed Interest"))
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:59,代码来源:test_encode_decode_interest.py
示例9: setUp
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
self.groupName = Name("/Prefix/READ")
self.contentName = Name("/Prefix/SAMPLE/Content")
self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
self.eKeyName = Name("/Prefix/READ/E-KEY/1/2")
self.dKeyName = Name("/Prefix/READ/D-KEY/1/2")
self.uKeyName = Name("/U/Key")
self.uName = Name("/U")
# Generate the E-KEY and D-KEY.
params = RsaKeyParams()
self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
self.fixtureDKeyBlob).getKeyBits()
# Generate the user key.
self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey(
self.fixtureUDKeyBlob).getKeyBits()
# Load the C-KEY.
self.fixtureCKeyBlob = Blob(AES_KEY, False)
# Set up the keyChain.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
# Initialize the storage.
keyName = Name("/testname/DSK-123")
self.certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName.get(-1)).append("ID-CERT").append("0")
identityStorage.addKey(
keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
DEFAULT_RSA_PRIVATE_KEY_DER)
开发者ID:,项目名称:,代码行数:50,代码来源:
示例10: createVerifyKeyChain
def createVerifyKeyChain():
"""
Create an in-memory KeyChain with a default public key for verifying.
:return: A new KeyChain.
:rtype: KeyChain
"""
identityStorage = MemoryIdentityStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, MemoryPrivateKeyStorage()),
SelfVerifyPolicyManager(identityStorage))
# Initialize the storage.
keyName = Name("/testname/DSK-123")
identityStorage.addKey(
keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
return keyChain
开发者ID:named-data,项目名称:PyCNL,代码行数:18,代码来源:test_nac_consumer.py
示例11: main
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"))
开发者ID:mjycom,项目名称:PyNDN2,代码行数:43,代码来源:test_encode_decode_data.py
示例12: __init__
def __init__(self):
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage),
SelfVerifyPolicyManager(self.identityStorage))
keyName = Name("/testname/DSK-123")
self.defaultCertName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
开发者ID:sanchitgupta05,项目名称:PyNDN2,代码行数:12,代码来源:test_utils.py
示例13: createKeyChain
def createKeyChain():
"""
Create an in-memory KeyChain with default keys.
:return: A tuple with the new KeyChain and certificate name.
:rtype: (KeyChain,Name)
"""
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
# Initialize the storage.
keyName = Name("/testname/DSK-123")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName.get(-1)).append("ID-CERT").append("0")
identityStorage.addKey(
keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
DEFAULT_RSA_PRIVATE_KEY_DER)
return keyChain, certificateName
开发者ID:named-data,项目名称:PyCNL,代码行数:24,代码来源:test_nac_producer.py
示例14: 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()
开发者ID:wentaoshang,项目名称:ndn-sensor,代码行数:17,代码来源:publish_modbus.py
示例15: setUp
def setUp(self):
# set up the keychain so we can sign data
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
self.privateKeyStorage = MemoryPrivateKeyStorage()
# not using keychain for verification so we don't need to set the
# policy manager
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
self.identityName = Name('/SecurityTestSecRule/Basic/Longer')
keyName = Name(self.identityName).append('ksk-2439872')
self.defaultCertName = self._certNameFromKeyName(keyName)
self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
keyName = Name('/SecurityTestSecRule/Basic/ksk-0923489')
self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
self.shortCertName = self._certNameFromKeyName(keyName, -2)
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:22,代码来源:test_verification_rules.py
示例16: __init__
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)
开发者ID:wentaoshang,项目名称:ndn-sensor,代码行数:72,代码来源:publish_modbus.py
示例17: BACnetAggregator
class BACnetAggregator(BIPSimpleApplication, Logging):
def __init__(self, config):
if _debug: BACnetAggregator._debug("__init__ %r", config)
# get local address from the config file
laddr = config.get('BACpypes', 'address')
# make a local device object
local_device = \
LocalDeviceObject( objectName=config.get('BACpypes','objectName')
, objectIdentifier=config.getint('BACpypes','objectIdentifier')
, maxApduLengthAccepted=config.getint('BACpypes','maxApduLengthAccepted')
, segmentationSupported=config.get('BACpypes','segmentationSupported')
, vendorIdentifier=config.getint('BACpypes','vendorIdentifier')
)
# build a bit string that knows about the bit names
pss = ServicesSupported()
pss['whoIs'] = 1
pss['iAm'] = 1
pss['readProperty'] = 1
pss['writeProperty'] = 1
# set the property value to be just the bits
local_device.protocolServicesSupported = pss.value
# make a simple application
BIPSimpleApplication.__init__(self, local_device, laddr)
# create logger
self.logger = BACnetDataLogger(self, config)
self.loadKey()
# keep track of requests to line up responses
self._request = None
# connect to local repo
self.publisher = RepoSocketPublisher(12345)
self.interval = 5 # in seconds
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, name_str, payload, timestamp):
data = Data(Name(name_str).append(bytearray(timestamp)))
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC, iv)
data.setContent(bytearray(time_s + iv + encryptor.encrypt(pad(json.dumps(payload)))))
data.getMetaInfo().setFreshnessPeriod(10000)
self.keychain.sign(data, self.cert_name)
self.publisher.put(data)
#print payload
#print 'Publish ' + data.getName().toUri()
def request(self, apdu):
if _debug: BACnetAggregator._debug("request %r", apdu)
# save a copy of the request
self._request = apdu
# forward it along
BIPSimpleApplication.request(self, apdu)
def confirmation(self, apdu):
#print thread.get_ident()
global kds_count, key, time_s, point_count
if _debug: BACnetAggregator._debug("confirmation %r", apdu)
if isinstance(apdu, Error):
sys.stdout.write("error: %s\n" % (apdu.errorCode,))
sys.stdout.flush()
elif isinstance(apdu, AbortPDU):
apdu.debug_contents()
elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
# find the datatype
datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
BACnetAggregator._debug(" - datatype: %r", datatype)
if not datatype:
raise TypeError, "unknown datatype"
# special case for array parts, others are managed by cast_out
#.........这里部分代码省略.........
开发者ID:wentaoshang,项目名称:ndn-sensor,代码行数:101,代码来源:publish_bacnet.py
示例18: main
def main():
# Uncomment these lines to print ChronoSync debug messages.
# logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
# logging.getLogger('').setLevel(logging.INFO)
screenName = promptAndInput("Enter your chat username: ")
defaultHubPrefix = "ndn/edu/ucla/remap"
hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
if hubPrefix == "":
hubPrefix = defaultHubPrefix
defaultChatRoom = "ndnchat"
chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ")
if chatRoom == "":
chatRoom = defaultChatRoom
host = "localhost"
print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: " +
screenName)
print("")
# Set up the key chain.
face = Face(host)
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
keyChain.setFace(face)
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)
face.setCommandSigningInfo(keyChain, certificateName)
chat = Chat(
screenName, chatRoom, Name(hubPrefix), face, keyChain, certificateName)
# The main loop to process Chat while checking stdin to send a message.
print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
while True:
# Set timeout to 0 for an immediate check.
isReady, _, _ = select.select([sys.stdin], [], [], 0)
if len(isReady) != 0:
input = promptAndInput("")
if input == "leave" or input == "exit":
# We will send the leave message below.
break
chat.sendMessage(input)
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
# The user entered the command to leave.
chat.leave()
# Wait a little bit to allow other applications to fetch the leave message.
startTime = Chat.getNowMilliseconds()
while True:
if Chat.getNowMilliseconds() - startTime >= 1000.0:
break
face.processEvents()
time.sleep(0.01)
开发者ID:,项目名称:,代码行数:68,代码来源:
示例19: TestRegexMatching
class TestRegexMatching(ut.TestCase):
def _certNameFromKeyName(self, keyName, keyIdx=-1):
return keyName[:keyIdx].append("KEY").append(keyName[keyIdx:]).\
append("ID-CERT").append("0")
def setUp(self):
# set up the keychain so we can sign data
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
self.privateKeyStorage = MemoryPrivateKeyStorage()
# not using keychain for verification so we don't need to set the
# policy manager
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
self.identityName = Name('/SecurityTestSecRule/Basic/Longer')
keyName = Name(self.identityName).append('ksk-2439872')
self.defaultCertName = self._certNameFromKeyName(keyName)
self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
keyName = Name('/SecurityTestSecRule/Basic/ksk-0923489')
self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
self.shortCertName = self._certNameFromKeyName(keyName, -2)
def test_name_relation(self):
policyManagerPrefix = ConfigPolicyManager("policy_config/relation_ruleset_prefix.conf")
policyManagerStrict = ConfigPolicyManager("policy_config/relation_ruleset_strict.conf")
policyManagerEqual = ConfigPolicyManager("policy_config/relation_ruleset_equal.conf")
dataName = Name('/TestRule1')
self.assertIsNotNone(
policyManagerPrefix._findMatchingRule(dataName, 'data'),
"Prefix relation should match prefix name")
self.assertIsNotNone(
policyManagerEqual._findMatchingRule(dataName, 'data'),
"Equal relation should match prefix name")
self.assertIsNone(
policyManagerStrict._findMatchingRule(dataName, 'data'),
"Strict-prefix relation should not match prefix name")
dataName = Name('/TestRule1/hi')
self.assertIsNotNone(
policyManagerPrefix._findMatchingRule(dataName, 'data'),
"Prefix relation should match longer name")
self.assertIsNone(
policyManagerEqual._findMatchingRule(dataName, 'data'),
"Equal relation should not match longer name")
self.assertIsNotNone(
policyManagerStrict._findMatchingRule(dataName, 'data'),
"Strict-prefix relation should match longer name")
dataName = Name('/Bad/TestRule1/')
self.assertIsNone(
policyManagerPrefix._findMatchingRule(dataName, 'data'),
"Prefix relation should not match inner components")
self.assertIsNone(
policyManagerEqual._findMatchingRule(dataName, 'data'),
"Equal relation should not match inner components")
self.assertIsNone(
policyManagerStrict._findMatchingRule(dataName, 'data'),
"Strict-prefix relation should not match inner components")
def test_simple_regex(self):
policyManager = ConfigPolicyManager("policy_config/regex_ruleset.conf")
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)
#.........这里部分代码省略.........
开发者ID:WeiqiJust,项目名称:NDN-total,代码行数:101,代码来源:test_verification_rules.py
示例20: Data
cipher = PKCS1_v1_5.new(self.usr_key)
ciphertext = cipher.encrypt(self.symkey)
symkey_name = self.prefix.append(bytearray(self.timestamp)).append(bytearray(keyid))
symkey_data = Data(symkey_name)
symkey_data.setContent(bytearray(ciphertext))
self.keychain.sign(symkey_data, self.cert_name)
self.publisher.put(symkey_data)
print symkey_data.getName().toUri()
print 'Simple KDS stop'
# Only for testing
if __name__ == "__main__":
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage))
key_file = "../keychain/keys/melnitz_root.pem"
f = open(key_file, "r")
key = RSA.importKey(f.read())
keyid = hashlib.sha256(key.publickey().exportKey("DER")).digest()
bld_root = Name("/nd
|
请发表评论