def test_save_load(self): for dataSet in self.keyTestData: # Load the key in PKCS #1 format. pkcs1 = base64.b64decode(dataSet.privateKeyPkcs1) key1 = TpmPrivateKey() key1.loadPkcs1(pkcs1) # Save the key in PKCS #1 format. savedPkcs1Key = key1.toPkcs1() self.assertTrue(savedPkcs1Key.equals(Blob(pkcs1))) # Load the key in unencrypted PKCS #8 format. pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted) key8 = TpmPrivateKey() key8.loadPkcs8(pkcs8) # Save the key in unencrypted PKCS #8 format. savedPkcs8Key = key8.toPkcs8() self.assertTrue(savedPkcs8Key.equals(Blob(pkcs8))) password = Blob("password").toBytes() # Load the key in encrypted PKCS #8 format. encryptedPkcs8 = base64.b64decode(dataSet.privateKeyPkcs8) encryptedKey8 = TpmPrivateKey() encryptedKey8.loadEncryptedPkcs8(encryptedPkcs8, password) # Save the key in encrypted PKCS #8 format and resave as unencrypted. savedEncryptedPkcs8Key = encryptedKey8.toEncryptedPkcs8(password) key8 = TpmPrivateKey() key8.loadEncryptedPkcs8(savedEncryptedPkcs8Key, password) resavedPkcs8Key = key8.toPkcs8() self.assertTrue(resavedPkcs8Key.equals(Blob(pkcs8)))
def test_append(self): # could possibly split this into different tests uri = "/localhost/user/folders/files/%00%0F" name = Name(uri) name2 = Name("/localhost").append(Name("/user/folders/")) self.assertEqual( len(name2), 3, 'Name constructed by appending names has ' + str(len(name2)) + ' components instead of 3') self.assertTrue(name2[2].getValue() == Blob("folders"), 'Name constructed with append has wrong suffix') name2 = name2.append("files") self.assertEqual( len(name2), 4, 'Name constructed by appending string has ' + str(len(name2)) + ' components instead of 4') name2 = name2.appendSegment(15) self.assertTrue( name2[4].getValue() == Blob(bytearray([0x00, 0x0F])), 'Name constructed by appending segment has wrong segment value') self.assertTrue( name2 == name, 'Name constructed with append is not equal to URI constructed name' ) self.assertEqual(name2.toUri(), name.toUri(), 'Name constructed with append has wrong URI')
def decodeData(self, data, input): """ Decode input as an NDN-TLV data packet, set the fields in the data object, and return the signed offsets. :param Data data: The Data object whose fields are updated. :param input: The array with the bytes to decode. :type input: An array type with int elements :return: A Tuple of (signedPortionBeginOffset, signedPortionEndOffset) where signedPortionBeginOffset is the offset in the encoding of the beginning of the signed portion, and signedPortionEndOffset is the offset in the encoding of the end of the signed portion. :rtype: (int, int) """ decoder = TlvDecoder(input) endOffset = decoder.readNestedTlvsStart(Tlv.Data) signedPortionBeginOffset = decoder.getOffset() self._decodeName(data.getName(), decoder) self._decodeMetaInfo(data.getMetaInfo(), decoder) data.setContent(Blob(decoder.readBlobTlv(Tlv.Content))) self._decodeSignatureInfo(data, decoder) signedPortionEndOffset = decoder.getOffset() data.getSignature().setSignature( Blob(decoder.readBlobTlv(Tlv.SignatureValue))) decoder.finishNestedTlvs(endOffset) return (signedPortionBeginOffset, signedPortionEndOffset)
def fromEscapedString(escapedString, beginOffset = 0, endOffset = None): """ Make a Blob value by decoding the escapedString between beginOffset and endOffset according to the NDN URI Scheme. (If offsets are omitted, then decode the whole string.) If the escaped string is "", "." or ".." then return a Blob with a null pointer, which means the component should be skipped in a URI name. :param str escapedString: The escaped string. :return: The unescaped Blob value. If the escapedString is not a valid escaped component, then the Blob isNull(). """ if endOffset == None: endOffset = len(escapedString) value = Name._unescape(escapedString[beginOffset:endOffset].strip()) gotNonDot = False for i in range(len(value)): if value[i] != ord('.'): gotNonDot = True break if not gotNonDot: # Special case for component of only periods. if len(value) <= 2: # Zero, one or two periods is illegal. Ignore this component. return Blob() else: # Remove 3 periods. return Blob(value[3:]) else: return Blob(value)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) # The default Face will connect using a Unix socket, or to "localhost". face = Face() memberName = Name("/first/user") memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6")) memberKeyChain = KeyChain("pib-memory:", "tpm-memory:") memberKeyChain.importSafeBag(SafeBag (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False), Blob(MEMBER_PUBLIC_KEY, False))) # TODO: Use a real Validator. decryptor = DecryptorV2( memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(), ValidatorNull(), memberKeyChain, face) contentPrefix = Name("/testname/content") contentNamespace = Namespace(contentPrefix) contentNamespace.setFace(face) contentNamespace.setDecryptor(decryptor) enabled = [True] def onSegmentedObject(objectNamespace): dump("Got segmented content", objectNamespace.obj.toRawStr()) enabled[0] = False SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded() while enabled[0]: face.processEvents() # We need to sleep for a few milliseconds so we don't use 100% of the CPU. time.sleep(0.01)
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) if sys.version_info[0] <= 2: userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ") else: userPrefixUri = input("Enter your user prefix (e.g. /a): ") if userPrefixUri == "": dump("You must enter a user prefix") return syncPrefixUri = "/sync" nUserPrefixes = 2 maxPublishedSequenceNo = 3 # The default Face will connect using a Unix socket, or to "localhost". face = Face() # 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))) face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) producer = Producer(face, keyChain, Name(syncPrefixUri), userPrefixUri, nUserPrefixes, maxPublishedSequenceNo) # The main event loop. 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)
def test_constructor(self): certificate = CertificateV2() certificate.wireDecode(Blob(CERT, False)) self.assertEqual( Name("/ndn/site1/KEY/ksk-1416425377094/0123/%FD%00%00%01I%C9%8B"), certificate.getName()) self.assertEqual(Name("/ndn/site1/KEY/ksk-1416425377094"), certificate.getKeyName()) self.assertEqual(Name("/ndn/site1"), certificate.getIdentity()) self.assertEqual(Name.Component("0123"), certificate.getIssuerId()) self.assertEqual(Name.Component("ksk-1416425377094"), certificate.getKeyId()) self.assertEqual(Name("/ndn/site1/KEY/ksk-2516425377094"), KeyLocator.getFromSignature(certificate.getSignature()).getKeyName()) self.assertEqual(fromIsoString("20150814T223739"), certificate.getValidityPeriod().getNotBefore(), 0) self.assertEqual(fromIsoString("20150818T223738"), certificate.getValidityPeriod().getNotAfter(), 0) try: certificate.getPublicKey() except: self.fail("Error in getPublicKey"); data = Data() data.wireDecode(Blob(CERT, False)) certificate2 = CertificateV2(data) self.assertEqual(certificate.getName(), certificate2.getName()) self.assertTrue(certificate.getPublicKey().equals(certificate2.getPublicKey()))
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 test_full_name(self): data = Data() data.wireDecode(codedData) # Check the full name format. self.assertEqual(data.getFullName().size(), data.getName().size() + 1) self.assertEqual(data.getName(), data.getFullName().getPrefix(-1)) self.assertEqual(data.getFullName().get(-1).getValue().size(), 32) # Check the independent digest calculation. sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend()) sha256.update(Blob(codedData).toBytes()) newDigest = Blob(bytearray(sha256.finalize()), False) self.assertTrue(newDigest.equals( data.getFullName().get(-1).getValue())) # Check the expected URI. self.assertEqual( data.getFullName().toUri(), "/ndn/abc/sha256digest=" + "96556d685dcb1af04be4ae57f0e7223457d4055ea9b3d07c0d337bef4a8b3ee9") # Changing the Data packet should change the full name. saveFullName = Name(data.getFullName()) data.setContent(Blob()) self.assertNotEqual(data.getFullName().get(-1), saveFullName.get(-1))
def test_setter_getter(self): content = EncryptedContent() self.assertEqual(content.getAlgorithmType(), None) self.assertTrue(content.getPayload().isNull()) self.assertTrue(content.getInitialVector().isNull()) self.assertEqual(content.getKeyLocator().getType(), None) content.setAlgorithmType(EncryptAlgorithmType.RsaOaep) self.assertEqual(content.getAlgorithmType(), EncryptAlgorithmType.RsaOaep) self.assertTrue(content.getPayload().isNull()) self.assertTrue(content.getInitialVector().isNull()) self.assertEqual(content.getKeyLocator().getType(), None) keyLocator = KeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.getKeyName().set("/test/key/locator") content.setKeyLocator(keyLocator) self.assertTrue(content.getKeyLocator().getType() != None) self.assertTrue(content.getKeyLocator().getKeyName().equals( Name("/test/key/locator"))) self.assertTrue(content.getPayload().isNull()) self.assertTrue(content.getInitialVector().isNull()) content.setPayload(Blob(message, False)) self.assertTrue(content.getPayload().equals(Blob(message, False))) content.setInitialVector(Blob(iv, False)) self.assertTrue(content.getInitialVector().equals(Blob(iv, False))) encoded = content.wireEncode() contentBlob = Blob(encrypted, False) self.assertTrue(contentBlob.equals(encoded))
class TestDataAesEcb(object): testName = "TestDataAesEcb" keyName = Name("/test") encryptParams = EncryptParams(EncryptAlgorithmType.AesEcb) plainText = Blob(bytearray([ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73 ]), False) key = Blob(bytearray([ 0xdd, 0x60, 0x77, 0xec, 0xa9, 0x6b, 0x23, 0x1b, 0x40, 0x6b, 0x5a, 0xf8, 0x7d, 0x3d, 0x55, 0x32 ]), False) encryptedContent = Blob(bytearray([ 0x82, 0x2f, 0x1c, 0x08, 0x07, 0x06, 0x08, 0x04, 0x74, 0x65, 0x73, 0x74, 0x83, 0x01, 0x00, 0x84, 0x20, 0x13, 0x80, 0x1a, 0xc0, 0x4c, 0x75, 0xa7, 0x7f, 0x43, 0x5e, 0xd7, 0xa6, 0x3f, 0xd3, 0x68, 0x94, 0xe2, 0xcf, 0x54, 0xb1, 0xc2, 0xce, 0xad, 0x9b, 0x56, 0x6e, 0x1c, 0xe6, 0x55, 0x1d, 0x79, 0x04 ]), False)
def sign(self, data, keyName, digestAlgorithm = DigestAlgorithm.SHA256): """ Fetch the private key for keyName and sign the data, returning a signature Blob. :param data: The input byte buffer to sign. :type data: an array which implements the buffer protocol :param Name keyName: The name of the signing key. :param digestAlgorithm: (optional) the digest algorithm. If omitted, use DigestAlgorithm.SHA256. :type digestAlgorithm: int from DigestAlgorithm :return: The signature, or an isNull() Blob pointer if signing fails. :rtype: Blob :raises SecurityException: if can't find the private key with keyName. """ if digestAlgorithm != DigestAlgorithm.SHA256: return Blob() # Find the private key. keyUri = keyName.toUri() if not keyUri in self._privateKeyStore: raise SecurityException( "MemoryPrivateKeyStorage: Cannot find private key " + keyUri) privateKey = self._privateKeyStore[keyUri] # Sign the hash of the data. if sys.version_info[0] == 2: # In Python 2.x, we need a str. Use Blob to convert data. data = Blob(data, False).toRawStr() signature = PKCS1_v1_5.new(privateKey.getPrivateKey()).sign(SHA256.new(data)) # Convert the string to a Blob. return Blob(bytearray(signature), False)
class TestDataAesCbc(object): testName = "TestDataAesCbc" keyName = Name("/test") encryptParams = EncryptParams(EncryptAlgorithmType.AesCbc).setInitialVector( Blob(bytearray([ 0x73, 0x6f, 0x6d, 0x65, 0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x76, 0x65, 0x63, 0x74, 0x6f, 0x72 ]), False)) plainText = Blob(bytearray([ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73 ]), False) key = Blob(bytearray([ 0xdd, 0x60, 0x77, 0xec, 0xa9, 0x6b, 0x23, 0x1b, 0x40, 0x6b, 0x5a, 0xf8, 0x7d, 0x3d, 0x55, 0x32 ]), False) encryptedContent = Blob(bytearray([ 0x82, 0x41, # EncryptedContent 0x1c, 0x08, # KeyLocator /test 0x07, 0x06, 0x08, 0x04, 0x74, 0x65, 0x73, 0x74, 0x83, 0x01, # EncryptedAlgorithm 0x01, # AlgorithmAesCbc 0x85, 0x10, 0x73, 0x6f, 0x6d, 0x65, 0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x76, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x84, 0x20, # EncryptedPayLoad 0x6a, 0x6b, 0x58, 0x9c, 0x30, 0x3b, 0xd9, 0xa6, 0xed, 0xd2, 0x12, 0xef, 0x29, 0xad, 0xc3, 0x60, 0x1f, 0x1b, 0x6b, 0xc7, 0x03, 0xff, 0x53, 0x52, 0x82, 0x6d, 0x82, 0x73, 0x05, 0xf9, 0x03, 0xdc ]), False)
def sign(self, data, keyName, digestAlgorithm=DigestAlgorithm.SHA256): """ Fetch the private key for keyName and sign the data, returning a signature Blob. :param data: Pointer the input byte buffer to sign. :type data: An array type with int elements :param Name keyName: The name of the signing key. :param digestAlgorithm: (optional) the digest algorithm. If omitted, use DigestAlgorithm.SHA256. :type digestAlgorithm: int from DigestAlgorithm :return: The signature, or an isNull() Blob pointer if signing fails. :rtype: Blob """ if digestAlgorithm != DigestAlgorithm.SHA256: raise SecurityException( "FilePrivateKeyStorage.sign: Unsupported digest algorithm") der = self.getPrivateKey(keyName) privateKey = RSA.importKey(der.toRawStr()) # Sign the hash of the data. if sys.version_info[0] == 2: # In Python 2.x, we need a str. Use Blob to convert data. data = Blob(data, False).toRawStr() signature = PKCS1_v1_5.new(privateKey).sign(SHA256.new(data)) # Convert the string to a Blob. return Blob(bytearray(signature), False)
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 clear(self): """ Set all the fields to their default unspecified values. """ self._contentType = "" self._timestamp = None self._hasSegments = False self._other = Blob()
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) # This test is 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. cert = CertificateV2() certData = b64decode(CERT_DUMP) cert.wireDecode(Blob(certData, False)) signingInfo = SigningInfo() signingInfo.setSigningIdentity(self.identityName) # Make sure the validity period is current for two years. now = Common.getNowMilliseconds() signingInfo.setValidityPeriod(ValidityPeriod (now, now + 2 * 365 * 24 * 3600 * 1000.0)) self.keyChain.sign(cert, signingInfo) encodedCert = b64encode(cert.wireEncode().toBytes()) with open(self.testCertFile, 'w') as certFile: 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")
def main(): # Silence the warning from Interest wire encode. Interest.setDefaultCanBePrefix(True) 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")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) 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.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # 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())) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) validator.validate(reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"), makeFailureCallback("Freshly-signed Interest"))
def __init__(self, value = None): if type(value) is Name.Component: # Use the existing Blob in the other Component. self._value = value._value elif value == None: self._value = Blob([]) else: # Blob will make a copy. self._value = value if isinstance(value, Blob) else Blob(value)
def createEncryptedContent(self): contentData = Data(self.contentName) encryptParams = EncryptParams(EncryptAlgorithmType.AesCbc) encryptParams.setInitialVector(Blob(INITIAL_VECTOR, False)) Encryptor.encryptData( contentData, Blob(DATA_CONTENT, False), self.cKeyName, self.fixtureCKeyBlob, encryptParams) self.keyChain.sign(contentData, self.certificateName) return contentData
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")).setMustBeFresh(False).setMinSuffixComponents( 4).setMaxSuffixComponents(6).setInterestLifetimeMilliseconds( 30000).setChildSelector(1).setMustBeFresh(True)) 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.getForwardingHint().add(1, Name("/A")) dump(freshInterest.toUri()) # Set up the KeyChain. pibImpl = PibMemory() keyChain = KeyChain(pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl)) # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager. keyChain.importSafeBag( SafeBag(Name("/testname/KEY/123"), Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False), Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))) # Make a Face just so that we can sign the interest. face = Face("localhost") face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName()) face.makeCommandInterest(freshInterest) reDecodedFreshInterest = Interest() reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()) dump("") dump("Re-decoded fresh Interest:") dumpInterest(reDecodedFreshInterest) keyChain.verifyInterest(reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"), makeOnValidationFailed("Freshly-signed Interest"))
def test_extension(self): #now add an extension name = "/hello/kitty" trustClass = 0 trustLevel = 300 extValueRoot = DerSequence() extValueName = DerOctetString(Blob(name).buf()) extValueTrustClass = DerInteger(trustClass) extValueTrustLevel = DerInteger(trustLevel) extValueRoot.addChild(extValueName) extValueRoot.addChild(extValueTrustClass) extValueRoot.addChild(extValueTrustLevel) extValueData = extValueRoot.encode() oidString = "1.3.6.1.5.32.1" isCritical = True certExtension = CertificateExtension(oidString, isCritical, extValueData) self.toyCert.encode() cert = Certificate(self.toyCert) cert.addExtension(certExtension) cert.encode() certData = cert.getContent() plainData = Data() plainData.setContent(certData) # The constructor Certificate(Data) calls decode(). decodedCert = Certificate(plainData) self.assertEqual(1, len(decodedCert.getExtensionList()), "Wrong number of certificate extensions after decoding") decodedExtension = decodedCert.getExtensionList()[0] self.assertEqual(oidString, str(decodedExtension.getOid()), "Certificate extension has the wrong OID after decoding") self.assertEqual(isCritical, decodedExtension.getIsCritical(), "Certificate extension has the wrong isCritical value after decoding") # Decode and check the extension value. parsedExtValue = DerNode.parse(decodedExtension.getValue().buf()) decodedExtValueRoot = parsedExtValue.getChildren() self.assertEqual(3, len(decodedExtValueRoot), "Wrong number of certificate extension value items after decoding") decodedName = decodedExtValueRoot[0] decodedTrustClass = decodedExtValueRoot[1] decodedTrustLevel = decodedExtValueRoot[2] # Use Blob to get a string. self.assertEqual(name, Blob(decodedName.toVal()).toRawStr(), "Wrong extension value name after decoding") self.assertEqual(trustClass, decodedTrustClass.toVal(), "Wrong extension value trust class after decoding") self.assertEqual(trustLevel, decodedTrustLevel.toVal(), "Wrong extension value trust level after decoding")
def ibcKeySize(): group = PairingGroup('SS512') g1 = group.random(G1) g2 = group.random(G2) gt = group.random(GT) logging.info("G1:" + str(g1) + ", length: " + str(len(Blob(objectToBytes(g1, group)))) + " bytes.") logging.info("G2:" + str(g2) + ", length: " + str(len(Blob(objectToBytes(g2, group)))) + " bytes.") logging.info("GT:" + str(gt) + ", length: " + str(len(Blob(objectToBytes(gt, group)))) + " bytes.")
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)
def __init__(self, contentPrefix, userKeyName, keyChain, certificateName): self._enabled = True self._responseCount = 0 # Imitate test_consumer from the PyNDN integration tests. contentName0 = Name(contentPrefix).append("Content").appendSegment(0) contentName1 = Name(contentPrefix).append("Content").appendSegment(1) cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1") dKeyName = Name("/Prefix/READ/D-KEY/1/2") # Generate the E-KEY and D-KEY. params = RsaKeyParams() fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits() fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey( fixtureDKeyBlob).getKeyBits() # The user key. fixtureUserEKeyBlob = Blob(FIXTURE_USER_E_KEY) # Load the C-KEY. fixtureCKeyBlob = Blob(AES_KEY, False) # Imitate createEncryptedContent. Make two segments. encryptParams = EncryptParams(EncryptAlgorithmType.AesCbc) encryptParams.setInitialVector(Blob(INITIAL_VECTOR, False)) self._contentData0 = Data(contentName0) Encryptor.encryptData(self._contentData0, Blob(DATA0_CONTENT, False), cKeyName, fixtureCKeyBlob, encryptParams) self._contentData0.getMetaInfo().setFinalBlockId( Name().appendSegment(1)[0]) keyChain.sign(self._contentData0, certificateName) self._contentData1 = Data(contentName1) Encryptor.encryptData(self._contentData1, Blob(DATA1_CONTENT, False), cKeyName, fixtureCKeyBlob, encryptParams) self._contentData1.getMetaInfo().setFinalBlockId( Name().appendSegment(1)[0]) keyChain.sign(self._contentData1, certificateName) # Imitate createEncryptedCKey. self._cKeyData = Data(cKeyName) encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep) Encryptor.encryptData(self._cKeyData, fixtureCKeyBlob, dKeyName, fixtureEKeyBlob, encryptParams) keyChain.sign(self._cKeyData, certificateName) # Imitate createEncryptedDKey. self._dKeyData = Data(dKeyName) encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep) Encryptor.encryptData(self._dKeyData, fixtureDKeyBlob, userKeyName, fixtureUserEKeyBlob, encryptParams) keyChain.sign(self._dKeyData, certificateName)
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().toBytes()) 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")
def test_generic_signature(self): # Test correct encoding. signature = GenericSignature() signature.setSignatureInfoEncoding( Blob(experimentalSignatureInfo, False), None) signatureValue = Blob([1, 2, 3, 4], False) signature.setSignature(signatureValue) self.freshData.setSignature(signature) encoding = self.freshData.wireEncode() decodedData = Data() decodedData.wireDecode(encoding) decodedSignature = decodedData.getSignature() self.assertEqual(decodedSignature.getTypeCode(), experimentalSignatureType) self.assertTrue(Blob(experimentalSignatureInfo, False).equals (decodedSignature.getSignatureInfoEncoding())) self.assertTrue(signatureValue.equals(decodedSignature.getSignature())) # Test bad encoding. signature = GenericSignature() signature.setSignatureInfoEncoding( Blob(experimentalSignatureInfoNoSignatureType, False), None) signature.setSignature(signatureValue) self.freshData.setSignature(signature) gotError = True try: self.freshData.wireEncode() gotError = False except: pass if not gotError: self.fail("Expected encoding error for experimentalSignatureInfoNoSignatureType") signature = GenericSignature() signature.setSignatureInfoEncoding( Blob(experimentalSignatureInfoBadTlv, False), None) signature.setSignature(signatureValue) self.freshData.setSignature(signature) gotError = True try: self.freshData.wireEncode() gotError = False except: pass if not gotError: self.fail("Expected encoding error for experimentalSignatureInfoBadTlv")
def testNameAppendAndExtract(self): size = 10 iblt = InvertibleBloomLookupTable(size) prefix = Name("/test/memphis").appendNumber(1).toUri() newHash = Common.murmurHash3Blob(11, prefix) iblt.insert(newHash) expectedEncoding = [ 0x78, 0xda, 0x63, 0x64, 0x60, 0x60, 0xd8, 0x55, 0xb5, 0xfc, 0x5b, 0xb2, 0xef, 0xe2, 0x6c, 0x06, 0x0a, 0x00, 0x23, 0x1d, 0xcd, 0x01, 0x00, 0x65, 0x29, 0x0d, 0xb1 ] ibltName = Name("sync") encodedIblt = iblt.encode() self.assertTrue(encodedIblt.equals(Blob(expectedEncoding))) ibltName.append(encodedIblt) received = InvertibleBloomLookupTable(size) received.initialize(ibltName.get(-1).getValue()) self.assertTrue(iblt.equals(received)) receivedDifferentSize = InvertibleBloomLookupTable(20) try: receivedDifferentSize.initialize(ibltName.get(-1).getValue()) self.fail("Did not throw the expected exception") except RuntimeError: pass else: self.fail("Did not throw the expected exception")
def encodeData(self, data): """ Encode data in NDN-TLV and return the encoding and signed offsets. :param Data data: The Data object to encode. :return: A Tuple of (encoding, signedPortionBeginOffset, signedPortionEndOffset) where encoding is a Blob containing the encoding, signedPortionBeginOffset is the offset in the encoding of the beginning of the signed portion, and signedPortionEndOffset is the offset in the encoding of the end of the signed portion. :rtype: (Blob, int, int) """ encoder = TlvEncoder(1500) saveLength = len(encoder) # Encode backwards. encoder.writeBlobTlv(Tlv.SignatureValue, data.getSignature().getSignature().buf()) signedPortionEndOffsetFromBack = len(encoder) self._encodeSignatureInfo(data.getSignature(), encoder) encoder.writeBlobTlv(Tlv.Content, data.getContent().buf()) self._encodeMetaInfo(data.getMetaInfo(), encoder) self._encodeName(data.getName(), encoder) signedPortionBeginOffsetFromBack = len(encoder) encoder.writeTypeAndLength(Tlv.Data, len(encoder) - saveLength) signedPortionBeginOffset = (len(encoder) - signedPortionBeginOffsetFromBack) signedPortionEndOffset = len(encoder) - signedPortionEndOffsetFromBack return (Blob(encoder.getOutput(), False), signedPortionBeginOffset, signedPortionEndOffset)
def encodeForwardingEntry(self, forwardingEntry): """ Encode forwardingEntry and return the encoding. :param forwardingEntry: The ForwardingEntry object to encode. :type forwardingEntry: ForwardingEntry :return: A Blob containing the encoding. :rtype: Blob """ encoder = TlvEncoder(256) saveLength = len(encoder) # Encode backwards. encoder.writeOptionalNonNegativeIntegerTlvFromFloat( Tlv.FreshnessPeriod, forwardingEntry.getFreshnessPeriod()) encoder.writeNonNegativeIntegerTlv( Tlv.ForwardingFlags, forwardingEntry.getForwardingFlags().getForwardingEntryFlags()) encoder.writeOptionalNonNegativeIntegerTlv(Tlv.FaceID, forwardingEntry.getFaceId()) self._encodeName(forwardingEntry.getPrefix(), encoder) if (forwardingEntry.getAction() != None and len(forwardingEntry.getAction()) > 0): # Convert str to a bytearray. encoder.writeBlobTlv( Tlv.Action, bytearray(forwardingEntry.getAction(), 'ascii')) encoder.writeTypeAndLength(Tlv.ForwardingEntry, len(encoder) - saveLength) return Blob(encoder.getOutput(), False)
def decodeSignatureInfoAndValue(self, signatureInfo, signatureValue): """ Decode signatureInfo as a signature info and signatureValue as the related SignatureValue, and return a new object which is a subclass of Signature. :param signatureInfo: The array with the signature info input buffer to decode. :type signatureInfo: An array type with int elements :param signatureValue: The array with the signature value input buffer to decode. :type signatureValue: An array type with int elements :return: A new object which is a subclass of Signature. :rtype: a subclass of Signature """ # Use a SignatureHolder to imitate a Data object for _decodeSignatureInfo. signatureHolder = self.SignatureHolder() decoder = TlvDecoder(signatureInfo) self._decodeSignatureInfo(signatureHolder, decoder) decoder = TlvDecoder(signatureValue) signatureHolder.getSignature().setSignature( Blob(decoder.readBlobTlv(Tlv.SignatureValue))) return signatureHolder.getSignature()
def test_rsa_decryption(self): dataSet = self.rsaKeyTestData pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted) key = TpmPrivateKey() key.loadPkcs8(pkcs8) plainText = Blob([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]) cipherTextBase64 = ( "i2XNpZ2JbLa4JmBTdDrGmsd4/0C+p+BSCpW3MuPBNe5uChQ0eRO1dvjTnEqwSECY\n" + "38en9JZwcyb0It/TSFNXHlq+Z1ZpffnjIJxQR9HcgwvwQJh6WRH0vu38tvGkGuNv\n" + "60Rdn85hqSy1CikmXCeWXL9yCqeqcP21R94G/T3FuA+c1FtFko8KOzCwvrTXMO6n\n" + "5PNsqlLXabSGr+jz4EwOsSCgPkiDf9U6tXoSPRA2/YvqFQdaiUXIVlomESvaqqZ8\n" + "FxPs2BON0lobM8gT+xdzbRKofp+rNjNK+5uWyeOnXJwzCszh17cdJl2BH1dZwaVD\n" + "PmTiSdeDQXZ94U5boDQ4Aw==\n") cipherText = base64.b64decode(cipherTextBase64) decryptedText = key.decrypt(cipherText) self.assertTrue(decryptedText.equals(plainText))
def clear(self): """ Clear the fields and set the type to None. """ self._type = None self._keyName.get().clear() self._keyData = Blob() self._changeCount += 1
def test_generate_key(self): for dataSet in self.keyTestData: key = TpmPrivateKey.generatePrivateKey(dataSet.keyParams) publicKeyBits = key.derivePublicKey() publicKey = PublicKey(publicKeyBits) data = Blob([0x01, 0x02, 0x03, 0x04]) # Sign and verify. signature = key.sign(data.toBytes(), DigestAlgorithm.SHA256) result = VerificationHelpers.verifySignature( data, signature, publicKey) self.assertTrue(result) # Check that another generated private key is different. key2 = TpmPrivateKey.generatePrivateKey(dataSet.keyParams) self.assertTrue(not key.toPkcs8().equals(key2.toPkcs8()))
def test_rsa_signing(self): for tpm in self.backEndList: # Create an RSA key. identityName = Name("/Test/KeyName") key = tpm.createKey(identityName, RsaKeyParams()) keyName = key.getKeyName() content = Blob([0x01, 0x02, 0x03, 0x04]) signature = key.sign(DigestAlgorithm.SHA256, content.toBytes()) publicKey = key.derivePublicKey() result = VerificationHelpers.verifySignature( content, signature, publicKey) self.assertEqual(True, result) tpm.deleteKey(keyName) self.assertEqual(False, tpm.hasKey(keyName))
def test_encryption_decryption(self): encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep, 0) privateKeyBlob = Blob(b64decode(PRIVATE_KEY)) publicKeyBlob = Blob(b64decode(PUBLIC_KEY)) decryptKey = DecryptKey(privateKeyBlob) encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits()) encodedPublic = publicKeyBlob derivedPublicKey = encryptKey.getKeyBits() self.assertTrue(encodedPublic.equals(derivedPublicKey)) plainBlob = Blob(PLAINTEXT, False) encryptBlob = RsaAlgorithm.encrypt( encryptKey.getKeyBits(), plainBlob, encryptParams) receivedBlob = RsaAlgorithm.decrypt( decryptKey.getKeyBits(), encryptBlob, encryptParams) self.assertTrue(plainBlob.equals(receivedBlob)) cipherBlob = Blob(CIPHERTEXT_OAEP, False) decryptedBlob = RsaAlgorithm.decrypt( decryptKey.getKeyBits(), cipherBlob, encryptParams) self.assertTrue(plainBlob.equals(decryptedBlob)) # Now test RsaPkcs. encryptParams = EncryptParams(EncryptAlgorithmType.RsaPkcs, 0) encryptBlob = RsaAlgorithm.encrypt( encryptKey.getKeyBits(), plainBlob, encryptParams) receivedBlob = RsaAlgorithm.decrypt( decryptKey.getKeyBits(), encryptBlob, encryptParams) self.assertTrue(plainBlob.equals(receivedBlob)) cipherBlob = Blob(CIPHERTEXT_PKCS, False) decryptedBlob = RsaAlgorithm.decrypt( decryptKey.getKeyBits(), cipherBlob, encryptParams) self.assertTrue(plainBlob.equals(decryptedBlob))
def test_content_asymmetric_encrypt_small(self): for input in encryptorRsaTestInputs: rawContent = Blob(bytearray([ 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73 ]), False) data = Data() rsaParams = RsaKeyParams(1024) keyName = Name("test") decryptKey = RsaAlgorithm.generateKey(rsaParams) encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits()) eKey = encryptKey.getKeyBits() dKey = decryptKey.getKeyBits() encryptParams = EncryptParams(input.type) Encryptor.encryptData(data, rawContent, keyName, eKey, encryptParams) self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)), input.testName) extractContent = EncryptedContent() extractContent.wireDecode(data.getContent()) self.assertTrue( keyName.equals(extractContent.getKeyLocator().getKeyName()), input.testName) self.assertEqual( extractContent.getInitialVector().size(), 0, input.testName) self.assertEqual( extractContent.getAlgorithmType(), input.type, input.testName) recovered = extractContent.getPayload() decrypted = RsaAlgorithm.decrypt(dKey, recovered, encryptParams) self.assertTrue(rawContent.equals(decrypted), input.testName)
def test_full_name(self): data = Data() data.wireDecode(codedData) # Check the full name format. self.assertEqual(data.getFullName().size(), data.getName().size() + 1) self.assertEqual(data.getName(), data.getFullName().getPrefix(-1)) self.assertEqual(data.getFullName().get(-1).getValue().size(), 32) # Check the independent digest calculation. sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend()) sha256.update(Blob(codedData).toBytes()) newDigest = Blob(bytearray(sha256.finalize()), False) self.assertTrue(newDigest.equals(data.getFullName().get(-1).getValue())) # Check the expected URI. self.assertEqual( data.getFullName().toUri(), "/ndn/abc/sha256digest=" + "96556d685dcb1af04be4ae57f0e7223457d4055ea9b3d07c0d337bef4a8b3ee9") # Changing the Data packet should change the full name. saveFullName = Name(data.getFullName()) data.setContent(Blob()) self.assertNotEqual(data.getFullName().get(-1), saveFullName.get(-1))
def __init__(self, value = None): if value == None: self._type = None self._keyName = ChangeCounter(Name()) self._keyData = Blob() elif type(value) is KeyLocator: # Copy its values. self._type = value._type self._keyName = ChangeCounter(Name(value.getKeyName())) self._keyData = value._keyData else: raise RuntimeError( "Unrecognized type for KeyLocator constructor: " + repr(type(value))) self._changeCount = 0
def extract_co_from_db(self, leaf_node, wired=True): try: # by design, there is AT MOST one C2S relation for each node query = 'START s=node(%s)\n' % leaf_node._id + \ 'MATCH (s)-[r:%s]->(c)\n' % RELATION_C2S + \ 'RETURN c' records = neo4j.CypherQuery(self.db_handler, query).execute() nodes = [record.values[0] for record in records.data] segment_node = nodes[0] properties = segment_node.get_properties() wrapped = eval(properties[PROPERTY_WRAPPED]) _data = properties[PROPERTY_DATA] data = base64.b64decode(_data) # decode wired co to ContentObject instance # if not wired: co = Data() co.wireDecode(Blob.fromRawStr(data)) return co # else: # return data except StopIteration as ex: return None
class Component(object): """ Create a new Name.Component. :param value: (optional) If value is already a Blob or Name.Component, then take another pointer to the value. Otherwise, create a new Blob with a copy of the value. If omitted, create an empty component. :type value: Blob or Name.Component or value for Blob constructor """ def __init__(self, value = None): if type(value) is Name.Component: # Use the existing Blob in the other Component. self._value = value._value elif value == None: self._value = Blob([]) else: # Blob will make a copy. self._value = value if isinstance(value, Blob) else Blob(value) def getValue(self): """ Get the value of the component. :return: The component value. :rtype: Blob """ return self._value def toEscapedString(self, result = None): """ Convert this component to a string, escaping characters according to the NDN URI Scheme. This also adds "..." to a value with zero or more ".". :param BytesIO result: (optional) The BytesIO stream to write to. If omitted, return a str with the result. :return: The result as a string (only if result is omitted). :rtype: str """ if result == None: return Name.toEscapedString(self._value.buf()) else: Name.toEscapedString(self._value.buf(), result) def toNumber(self): """ Interpret this name component as a network-ordered number and return an integer. :return: The integer number. :rtype: int """ result = 0 for i in range(self._value.size()): result *= 256 result += self._value.buf()[i] return result def toNumberWithMarker(self, marker): """ Interpret this name component as a network-ordered number with a marker and return an integer. :param int marker: The required first byte of the component. :return: The integer number. :rtype: int :raises RuntimeError: If the first byte of the component does not equal the marker. """ if self._value.size() <= 0 or self._value.buf()[0] != marker: raise RuntimeError( "Name component does not begin with the expected marker") result = 0 for i in range(1, self._value.size()): result *= 256 result += self._value.buf()[i] return result def toSegment(self): """ Interpret this name component as a segment number according to NDN name conventions (a network-ordered number where the first byte is the marker 0x00). :return: The integer segment number. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0x00) def toVersion(self): """ Interpret this name component as a version number according to NDN name conventions (a network-ordered number where the first byte is the marker 0xFD). Note that this returns the exact number from the component without converting it to a time representation. :return: The integer version number. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0xFD) def equals(self, other): """ Check if this is the same component as other. :param Name.Component other: The other Component to compare with. :return: True if the components are equal, otherwise False. :rtype: bool """ return self._value.equals(other._value) def compare(self, other): """ Compare this to the other Component using NDN canonical ordering. :param Name.Component other: The other Component to compare with. :return: 0 If they compare equal, -1 if self comes before other in the canonical ordering, or 1 if self comes after other in the canonical ordering. :rtype: int :see: http://named-data.net/doc/0.2/technical/CanonicalOrder.html """ if self._value.size() < other._value.size(): return -1 if self._value.size() > other._value.size(): return 1 # The components are equal length. Just do a byte compare. return self._value.compare(other._value) @staticmethod def fromNumber(number): """ Create a component whose value is the network-ordered encoding of the number. Note: if the number is zero, the result is empty. :param int number: The number to be encoded. :return: The component value. :rtype: Name.Component """ value = [] # First encode in little endian. while number != 0: value.append(number & 0xff) number >>= 8 # Make it big endian. value.reverse() return Name.Component(Blob(value, False)) @staticmethod def fromNumberWithMarker(number, marker): """ Create a component whose value is the marker appended with the network-ordered encoding of the number. Note: if the number is zero, no bytes are used for the number - the result will have only the marker. :param int number: The number to be encoded. :param int marker: The marker to use as the first byte of the component. :return: The component value. :rtype: Name.Component """ value = [] # First encode in little endian. while number != 0: value.append(number & 0xff) number >>= 8 # Make it big endian. value.reverse() # Prepend the leading marker. value.insert(0, marker) return Name.Component(Blob(value, False)) # Python operators def __eq__(self, other): return type(other) is Name.Component and self.equals(other) def __ne__(self, other): return not self == other def __le__(self, other): return self.compare(other) <= 0 def __lt__(self, other): return self.compare(other) < 0 def __ge__(self, other): return self.compare(other) >= 0 def __gt__(self, other): return self.compare(other) > 0
def test_content_asymmetric_encrypt_large(self): for input in encryptorRsaTestInputs: largeContent = Blob(bytearray([ 0x73, 0x5a, 0xbd, 0x47, 0x0c, 0xfe, 0xf8, 0x7d, 0x2e, 0x17, 0xaa, 0x11, 0x6f, 0x23, 0xc5, 0x10, 0x23, 0x36, 0x88, 0xc4, 0x2a, 0x0f, 0x9a, 0x72, 0x54, 0x31, 0xa8, 0xb3, 0x51, 0x18, 0x9f, 0x0e, 0x1b, 0x93, 0x62, 0xd9, 0xc4, 0xf5, 0xf4, 0x3d, 0x61, 0x9a, 0xca, 0x05, 0x65, 0x6b, 0xc6, 0x41, 0xf9, 0xd5, 0x1c, 0x67, 0xc1, 0xd0, 0xd5, 0x6f, 0x7b, 0x70, 0xb8, 0x8f, 0xdb, 0x19, 0x68, 0x7c, 0xe0, 0x2d, 0x04, 0x49, 0xa9, 0xa2, 0x77, 0x4e, 0xfc, 0x60, 0x0d, 0x7c, 0x1b, 0x93, 0x6c, 0xd2, 0x61, 0xc4, 0x6b, 0x01, 0xe9, 0x12, 0x28, 0x6d, 0xf5, 0x78, 0xe9, 0x99, 0x0b, 0x9c, 0x4f, 0x90, 0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f, 0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48, 0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5, 0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde, 0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9, 0x22, 0xf1, 0x67, 0x76, 0x71, 0x0c, 0xff, 0x99, 0x7b, 0x94, 0x9b, 0x24, 0x20, 0x80, 0xe3, 0xcc, 0x06, 0x4a, 0xed, 0xdf, 0xec, 0x50, 0xd5, 0x87, 0x3d, 0xa0, 0x7d, 0x9c, 0xe5, 0x13, 0x10, 0x98, 0x14, 0xc3, 0x90, 0x10, 0xd9, 0x25, 0x9a, 0x59, 0xe9, 0x37, 0x26, 0xfd, 0x87, 0xd7, 0xf4, 0xf9, 0x11, 0x91, 0xad, 0x5c, 0x00, 0x95, 0xf5, 0x2b, 0x37, 0xf7, 0x4e, 0xb4, 0x4b, 0x42, 0x7c, 0xb3, 0xad, 0xd6, 0x33, 0x5f, 0x0b, 0x84, 0x57, 0x7f, 0xa7, 0x07, 0x73, 0x37, 0x4b, 0xab, 0x2e, 0xfb, 0xfe, 0x1e, 0xcb, 0xb6, 0x4a, 0xc1, 0x21, 0x5f, 0xec, 0x92, 0xb7, 0xac, 0x97, 0x75, 0x20, 0xc9, 0xd8, 0x9e, 0x93, 0xd5, 0x12, 0x7a, 0x64, 0xb9, 0x4c, 0xed, 0x49, 0x87, 0x44, 0x5b, 0x4f, 0x90, 0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f, 0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48, 0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5, 0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde, 0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9 ]), False) data = Data() rsaParams = RsaKeyParams(1024) keyName = Name("test") decryptKey = RsaAlgorithm.generateKey(rsaParams) encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits()) eKey = encryptKey.getKeyBits() dKey = decryptKey.getKeyBits() encryptParams = EncryptParams(input.type) Encryptor.encryptData(data, largeContent, keyName, eKey, encryptParams) self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)), input.testName) largeDataContent = data.getContent() # largeDataContent is a sequence of the two EncryptedContent. encryptedNonce = EncryptedContent() encryptedNonce.wireDecode(largeDataContent) self.assertTrue(keyName.equals(encryptedNonce.getKeyLocator().getKeyName()), input.testName) self.assertEqual(encryptedNonce.getInitialVector().size(), 0, input.testName) self.assertEqual(encryptedNonce.getAlgorithmType(), input.type, input.testName) # Use the size of encryptedNonce to find the start of encryptedPayload. payloadContent = largeDataContent.buf()[encryptedNonce.wireEncode().size():] encryptedPayload = EncryptedContent() encryptedPayload.wireDecode(payloadContent) nonceKeyName = Name(keyName) nonceKeyName.append("nonce") self.assertTrue(nonceKeyName.equals(encryptedPayload.getKeyLocator().getKeyName()), input.testName) self.assertEqual(encryptedPayload.getInitialVector().size(), 16, input.testName) self.assertEqual(encryptedPayload.getAlgorithmType(), EncryptAlgorithmType.AesCbc, input.testName) self.assertEqual( largeDataContent.size(), encryptedNonce.wireEncode().size() + encryptedPayload.wireEncode().size(), input.testName) blobNonce = encryptedNonce.getPayload() nonce = RsaAlgorithm.decrypt(dKey, blobNonce, encryptParams) encryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc) encryptParams.setInitialVector(encryptedPayload.getInitialVector()) bufferPayload = encryptedPayload.getPayload() largePayload = AesAlgorithm.decrypt(nonce, bufferPayload, encryptParams) self.assertTrue(largeContent.equals(largePayload), input.testName)
class Component(object): """ Create a new Name.Component. :param value: (optional) If value is already a Blob or Name.Component, then take another pointer to the value. Otherwise, create a new Blob with a copy of the value. If omitted, create an empty component. :type value: Blob or Name.Component or value for Blob constructor """ def __init__(self, value = None): if type(value) is Name.Component: # Use the existing Blob in the other Component. self._value = value._value elif value == None: self._value = Blob([]) else: # Blob will make a copy. self._value = value if isinstance(value, Blob) else Blob(value) def getValue(self): """ Get the value of the component. :return: The component value. :rtype: Blob """ return self._value def toEscapedString(self, result = None): """ Convert this component to a string, escaping characters according to the NDN URI Scheme. This also adds "..." to a value with zero or more ".". :param BytesIO result: (optional) The BytesIO stream to write to. If omitted, return a str with the result. :return: The result as a string (only if result is omitted). :rtype: str """ if result == None: return Name.toEscapedString(self._value.buf()) else: Name.toEscapedString(self._value.buf(), result) def toNumber(self): """ Interpret this name component as a network-ordered number and return an integer. :return: The integer number. :rtype: int """ result = 0 for i in range(self._value.size()): result *= 256 result += self._value.buf()[i] return result def toNumberWithMarker(self, marker): """ Interpret this name component as a network-ordered number with a marker and return an integer. :param int marker: The required first byte of the component. :return: The integer number. :rtype: int :raises RuntimeError: If the first byte of the component does not equal the marker. """ if self._value.size() <= 0 or self._value.buf()[0] != marker: raise RuntimeError( "Name component does not begin with the expected marker") result = 0 for i in range(1, self._value.size()): result *= 256 result += self._value.buf()[i] return result def toSegment(self): """ Interpret this name component as a segment number according to NDN naming conventions for "Segment number" (marker 0x00). http://named-data.net/doc/tech-memos/naming-conventions.pdf :return: The integer segment number. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0x00) def toSegmentOffset(self): """ Interpret this name component as a segment byte offset according to NDN naming conventions for segment "Byte offset" (marker 0xFB). http://named-data.net/doc/tech-memos/naming-conventions.pdf :return: The integer segment byte offset. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0xFB) def toVersion(self): """ Interpret this name component as a version number according to NDN naming conventions for "Versioning" (marker 0xFD). Note that this returns the exact number from the component without converting it to a time representation. http://named-data.net/doc/tech-memos/naming-conventions.pdf :return: The integer version number. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0xFD) def toTimestamp(self): """ Interpret this name component as a timestamp according to NDN naming conventions for "Timestamp" (marker 0xFC). http://named-data.net/doc/tech-memos/naming-conventions.pdf :return: The number of microseconds since the UNIX epoch (Thursday, 1 January 1970) not counting leap seconds. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0xFC) def toSequenceNumber(self): """ Interpret this name component as a sequence number according to NDN naming conventions for "Sequencing" (marker 0xFE). http://named-data.net/doc/tech-memos/naming-conventions.pdf :return: The integer sequence number. :rtype: int :raises RuntimeError: If the first byte of the component is not the expected marker. """ return self.toNumberWithMarker(0xFE) def equals(self, other): """ Check if this is the same component as other. :param Name.Component other: The other Component to compare with. :return: True if the components are equal, otherwise False. :rtype: bool """ return self._value.equals(other._value) def compare(self, other): """ Compare this to the other Component using NDN canonical ordering. :param Name.Component other: The other Component to compare with. :return: 0 If they compare equal, -1 if self comes before other in the canonical ordering, or 1 if self comes after other in the canonical ordering. :rtype: int :see: http://named-data.net/doc/0.2/technical/CanonicalOrder.html """ if self._value.size() < other._value.size(): return -1 if self._value.size() > other._value.size(): return 1 # The components are equal length. Just do a byte compare. return self._value.compare(other._value) @staticmethod def fromNumber(number): """ Create a component whose value is the nonNegativeInteger encoding of the number. :param int number: The number to be encoded. :return: The component value. :rtype: Name.Component """ encoder = TlvEncoder(8) encoder.writeNonNegativeInteger(number) return Name.Component(Blob(encoder.getOutput(), False)) @staticmethod def fromNumberWithMarker(number, marker): """ Create a component whose value is the marker appended with the nonNegativeInteger encoding of the number. :param int number: The number to be encoded. :param int marker: The marker to use as the first byte of the component. :return: The component value. :rtype: Name.Component """ encoder = TlvEncoder(9) # Encode backwards. encoder.writeNonNegativeInteger(number) encoder.writeNonNegativeInteger(marker) return Name.Component(Blob(encoder.getOutput(), False)) # Python operators def __eq__(self, other): return type(other) is Name.Component and self.equals(other) def __ne__(self, other): return not self == other def __le__(self, other): return self.compare(other) <= 0 def __lt__(self, other): return self.compare(other) < 0 def __ge__(self, other): return self.compare(other) >= 0 def __gt__(self, other): return self.compare(other) > 0 def __len__(self): return self._value.size()
def test_constructor(self): # Check default settings. content = EncryptedContent() self.assertEqual(content.getAlgorithmType(), None) self.assertTrue(content.getPayload().isNull()) self.assertTrue(content.getInitialVector().isNull()) self.assertEqual(content.getKeyLocator().getType(), None) # Check an encrypted content with IV. keyLocator = KeyLocator() keyLocator.setType(KeyLocatorType.KEYNAME) keyLocator.getKeyName().set("/test/key/locator") rsaOaepContent = EncryptedContent() rsaOaepContent.setAlgorithmType(EncryptAlgorithmType.RsaOaep).setKeyLocator( keyLocator).setPayload(Blob(message, False)).setInitialVector(Blob(iv, False)) self.assertEqual(rsaOaepContent.getAlgorithmType(), EncryptAlgorithmType.RsaOaep) self.assertTrue(rsaOaepContent.getPayload().equals(Blob(message, False))) self.assertTrue(rsaOaepContent.getInitialVector().equals(Blob(iv, False))) self.assertTrue(rsaOaepContent.getKeyLocator().getType() != None) self.assertTrue(rsaOaepContent.getKeyLocator().getKeyName().equals( Name("/test/key/locator"))) # Encoding. encryptedBlob = Blob(encrypted, False) encoded = rsaOaepContent.wireEncode() self.assertTrue(encryptedBlob.equals(encoded)) # Decoding. rsaOaepContent2 = EncryptedContent() rsaOaepContent2.wireDecode(encryptedBlob) self.assertEqual(rsaOaepContent2.getAlgorithmType(), EncryptAlgorithmType.RsaOaep) self.assertTrue(rsaOaepContent2.getPayload().equals(Blob(message, False))) self.assertTrue(rsaOaepContent2.getInitialVector().equals(Blob(iv, False))) self.assertTrue(rsaOaepContent2.getKeyLocator().getType() != None) self.assertTrue(rsaOaepContent2.getKeyLocator().getKeyName().equals( Name("/test/key/locator"))) # Check the no IV case. rsaOaepContentNoIv = EncryptedContent() rsaOaepContentNoIv.setAlgorithmType(EncryptAlgorithmType.RsaOaep).setKeyLocator( keyLocator).setPayload(Blob(message, False)) self.assertEqual(rsaOaepContentNoIv.getAlgorithmType(), EncryptAlgorithmType.RsaOaep) self.assertTrue(rsaOaepContentNoIv.getPayload().equals(Blob(message, False))) self.assertTrue(rsaOaepContentNoIv.getInitialVector().isNull()) self.assertTrue(rsaOaepContentNoIv.getKeyLocator().getType() != None) self.assertTrue(rsaOaepContentNoIv.getKeyLocator().getKeyName().equals( Name("/test/key/locator"))) # Encoding. encryptedBlob2 = Blob(encryptedNoIv, False) encodedNoIv = rsaOaepContentNoIv.wireEncode() self.assertTrue(encryptedBlob2.equals(encodedNoIv)) # Decoding. rsaOaepContentNoIv2 = EncryptedContent() rsaOaepContentNoIv2.wireDecode(encryptedBlob2) self.assertEqual(rsaOaepContentNoIv2.getAlgorithmType(), EncryptAlgorithmType.RsaOaep) self.assertTrue(rsaOaepContentNoIv2.getPayload().equals(Blob(message, False))) self.assertTrue(rsaOaepContentNoIv2.getInitialVector().isNull()) self.assertTrue(rsaOaepContentNoIv2.getKeyLocator().getType() != None) self.assertTrue(rsaOaepContentNoIv2.getKeyLocator().getKeyName().equals( Name("/test/key/locator")))
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 test_errors(self): fixture = self.fixture pibImpl = PibMemory() try: PibKeyImpl(fixture.id1Key1Name, pibImpl) self.fail("Did not throw the expected exception") except Pib.Error: pass else: self.fail("Did not throw the expected exception") key11 = PibKeyImpl(fixture.id1Key1Name, fixture.id1Key1.buf(), pibImpl) try: PibKeyImpl(Name("/wrong"), pibImpl) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") try: PibKeyImpl(Name("/wrong"), fixture.id1Key1.buf(), pibImpl) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") wrongKey = Blob("") try: PibKeyImpl(fixture.id1Key2Name, wrongKey.toBytes(), pibImpl) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") key11.addCertificate(fixture.id1Key1Cert1) try: key11.addCertificate(fixture.id1Key2Cert1) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") try: key11.removeCertificate(fixture.id1Key2Cert1.getName()) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") try: key11.getCertificate(fixture.id1Key2Cert1.getName()) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") try: key11.setDefaultCertificate(fixture.id1Key2Cert1) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception") try: key11.setDefaultCertificate(fixture.id1Key2Cert1.getName()) self.fail("Did not throw the expected exception") except ValueError: pass else: self.fail("Did not throw the expected exception")
def test_import_export(self): privateKeyPkcs1Base64 = ( "MIIEpAIBAAKCAQEAw0WM1/WhAxyLtEqsiAJgWDZWuzkYpeYVdeeZcqRZzzfRgBQT\n" + "sNozS5t4HnwTZhwwXbH7k3QN0kRTV826Xobws3iigohnM9yTK+KKiayPhIAm/+5H\n" + "GT6SgFJhYhqo1/upWdueojil6RP4/AgavHhopxlAVbk6G9VdVnlQcQ5Zv0OcGi73\n" + "c+EnYD/YgURYGSngUi/Ynsh779p2U69/te9gZwIL5PuE9BiO6I39cL9z7EK1SfZh\n" + "OWvDe/qH7YhD/BHwcWit8FjRww1glwRVTJsA9rH58ynaAix0tcR/nBMRLUX+e3rU\n" + "RHg6UbSjJbdb9qmKM1fTGHKUzL/5pMG6uBU0ywIDAQABAoIBADQkckOIl4IZMUTn\n" + "W8LFv6xOdkJwMKC8G6bsPRFbyY+HvC2TLt7epSvfS+f4AcYWaOPcDu2E49vt2sNr\n" + "cASly8hgwiRRAB3dHH9vcsboiTo8bi2RFvMqvjv9w3tK2yMxVDtmZamzrrnaV3YV\n" + "Q+5nyKo2F/PMDjQ4eUAKDOzjhBuKHsZBTFnA1MFNI+UKj5X4Yp64DFmKlxTX/U2b\n" + "wzVywo5hzx2Uhw51jmoLls4YUvMJXD0wW5ZtYRuPogXvXb/of9ef/20/wU11WFKg\n" + "Xb4gfR8zUXaXS1sXcnVm3+24vIs9dApUwykuoyjOqxWqcHRec2QT2FxVGkFEraze\n" + "CPa4rMECgYEA5Y8CywomIcTgerFGFCeMHJr8nQGqY2V/owFb3k9maczPnC9p4a9R\n" + "c5szLxA9FMYFxurQZMBWSEG2JS1HR2mnjigx8UKjYML/A+rvvjZOMe4M6Sy2ggh4\n" + "SkLZKpWTzjTe07ByM/j5v/SjNZhWAG7sw4/LmPGRQkwJv+KZhGojuOkCgYEA2cOF\n" + "T6cJRv6kvzTz9S0COZOVm+euJh/BXp7oAsAmbNfOpckPMzqHXy8/wpdKl6AAcB57\n" + "OuztlNfV1D7qvbz7JuRlYwQ0cEfBgbZPcz1p18HHDXhwn57ZPb8G33Yh9Omg0HNA\n" + "Imb4LsVuSqxA6NwSj7cpRekgTedrhLFPJ+Ydb5MCgYEAsM3Q7OjILcIg0t6uht9e\n" + "vrlwTsz1mtCV2co2I6crzdj9HeI2vqf1KAElDt6G7PUHhglcr/yjd8uEqmWRPKNX\n" + "ddnnfVZB10jYeP/93pac6z/Zmc3iU4yKeUe7U10ZFf0KkiiYDQd59CpLef/2XScS\n" + "HB0oRofnxRQjfjLc4muNT+ECgYEAlcDk06MOOTly+F8lCc1bA1dgAmgwFd2usDBd\n" + "Y07a3e0HGnGLN3Kfl7C5i0tZq64HvxLnMd2vgLVxQlXGPpdQrC1TH+XLXg+qnlZO\n" + "ivSH7i0/gx75bHvj75eH1XK65V8pDVDEoSPottllAIs21CxLw3N1ObOZWJm2EfmR\n" + "cuHICmsCgYAtFJ1idqMoHxES3mlRpf2JxyQudP3SCm2WpGmqVzhRYInqeatY5sUd\n" + "lPLHm/p77RT7EyxQHTlwn8FJPuM/4ZH1rQd/vB+Y8qAtYJCexDMsbvLW+Js+VOvk\n" + "jweEC0nrcL31j9mF0vz5E6tfRu4hhJ6L4yfWs0gSejskeVB/w8QY4g==\n") for tpm in self.backEndList: if tpm is self.backEndOsx: # TODO: Implement TpmBackEndOsx import/export. continue keyName = Name("/Test/KeyName/KEY/1") tpm.deleteKey(keyName) self.assertEqual(False, tpm.hasKey(keyName)) privateKey = TpmPrivateKey() privateKeyPkcs1Encoding = Blob(base64.b64decode(privateKeyPkcs1Base64)) privateKey.loadPkcs1(privateKeyPkcs1Encoding.buf()) password = Blob("password").toBytes() encryptedPkcs8 = privateKey.toEncryptedPkcs8(password) tpm.importKey(keyName, encryptedPkcs8.buf(), password) self.assertEqual(True, tpm.hasKey(keyName)) try: # Can't import the same keyName again. tpm.importKey(keyName, encryptedPkcs8.buf(), password) self.fail("Did not throw the expected exception") except TpmBackEnd.Error: pass else: self.fail("Did not throw the expected exception") exportedKey = tpm.exportKey(keyName, password) self.assertEqual(True, tpm.hasKey(keyName)) privateKey2 = TpmPrivateKey() privateKey2.loadEncryptedPkcs8(exportedKey.buf(), password) privateKey2Pkcs1Encoding = privateKey2.toPkcs1() self.assertTrue(privateKeyPkcs1Encoding.equals(privateKey2Pkcs1Encoding)) tpm.deleteKey(keyName) self.assertEqual(False, tpm.hasKey(keyName)) try: tpm.exportKey(keyName, password) self.fail("Did not throw the expected exception") except TpmBackEnd.Error: pass else: self.fail("Did not throw the expected exception")
class KeyLocator(object): """ Create a new KeyLocator object, possibly copying values from another object. :param KeyLocator value: (optional) If value is a KeyLocator, copy its values. If value is omitted, set the fields to unspecified. """ def __init__(self, value = None): if value == None: self._type = None self._keyName = ChangeCounter(Name()) self._keyData = Blob() elif type(value) is KeyLocator: # Copy its values. self._type = value._type self._keyName = ChangeCounter(Name(value.getKeyName())) self._keyData = value._keyData else: raise RuntimeError( "Unrecognized type for KeyLocator constructor: " + repr(type(value))) self._changeCount = 0 def getType(self): """ Get the key locator type. If KeyLocatorType.KEYNAME, you may also getKeyName(). If KeyLocatorType.KEY_LOCATOR_DIGEST, you may also getKeyData() to get the digest. :return: The key locator type, or None if not specified. :rtype: an int from KeyLocatorType """ return self._type def getKeyName(self): """ Get the key name. This is meaningful if getType() is KeyLocatorType.KEYNAME. :return: The key name. If not specified, the Name is empty. :rtype: Name """ return self._keyName.get() def getKeyData(self): """ Get the key data. This is the digest bytes if getType() is KeyLocatorType.KEY_LOCATOR_DIGEST. :return: The key data as a Blob, which isNull() if unspecified. :rtype: Blob """ return self._keyData def setType(self, type): """ Set the key locator type. If KeyLocatorType.KEYNAME, you must also setKeyName(). If KeyLocatorType.KEY_LOCATOR_DIGEST, you must also setKeyData() to set the digest. :param type: The key locator type. If None, the type is unspecified. :type type: an int from KeyLocatorType """ self._type = None if type == None or type < 0 else type self._changeCount += 1 def setKeyName(self, keyName): """ Set key name to a copy of the given Name. This is the name if getType() is KeyLocatorType.KEYNAME. :param Name keyName: The key name which is copied. """ self._keyName.set(keyName if type(keyName) is Name else Name(keyName)) self._changeCount += 1 def setKeyData(self, keyData): """ Set the key data to the given value. This is the digest bytes if getType() is KeyLocatorType.KEY_LOCATOR_DIGEST. :param keyData: The array with the key data bytes. If keyData is not a Blob, then create a new Blob to copy the bytes (otherwise take another pointer to the same Blob). :type keyData: A Blob or an array type with int elements """ self._keyData = keyData if type(keyData) is Blob else Blob(keyData) self._changeCount += 1 def clear(self): """ Clear the fields and set the type to None. """ self._type = None self._keyName.get().clear() self._keyData = Blob() self._changeCount += 1 def getChangeCount(self): """ Get the change count, which is incremented each time this object (or a child object) is changed. :return: The change count. :rtype: int """ # Make sure each of the checkChanged is called. changed = self._keyName.checkChanged() if changed: # A child object has changed, so update the change count. self._changeCount += 1 return self._changeCount # Create managed properties for read/write properties of the class for more pythonic syntax. type = property(getType, setType) keyName = property(getKeyName, setKeyName) keyData = property(getKeyData, setKeyData) # Support property-based equivalence check # TODO: Desired syntax? def equals(self, other): if self is None and other is None: return True if other is None: return False if self._type != other._type: return False if self._keyName.get() != None and not self._keyName.get().equals(other._keyName.get()): return False if self._keyData != None and not self._keyData.equals(other._keyData): return False return True