public void testAppend() { // could possibly split this into different tests String uri = "/localhost/user/folders/files/%00%0F"; Name name = new Name(uri); Name name2 = new Name("/localhost").append(new Name("/user/folders/")); Assert.AssertEquals("Name constructed by appending names has " + name2.size() + " components instead of 3", 3, name2.size()); Assert.AssertTrue("Name constructed with append has wrong suffix", name2 .get(2).getValue().equals(new Blob("folders"))); name2 = name2.append("files"); Assert.AssertEquals("Name constructed by appending string has " + name2.size() + " components instead of 4", 4, name2.size()); name2 = name2.appendSegment(15); Assert.AssertTrue( "Name constructed by appending segment has wrong segment value", name2.get(4).getValue() .equals(new Blob(new int[] { 0x00, 0x0F }))); Assert.AssertTrue( "Name constructed with append is not equal to URI constructed name", name2.equals(name)); Assert.AssertEquals("Name constructed with append has wrong URI", name.toUri(), name2.toUri()); }
public void testSegment() { Name expected = new Name("/%00%27%10"); Assert.AssertTrue(expected.get(0).isSegment()); long number = 10000; Assert.AssertEquals("appendSegment did not create the expected component", expected, new Name().appendSegment(number)); try { Assert.AssertEquals("toSegment did not return the expected value", number, expected.get(0).toSegment()); } catch (EncodingException ex) { Assert.Fail("Error while parsing a nonNegativeInteger: " + ex.Message); } }
public void testNumberWithMarker() { Name expected = new Name("/%AA%03%E8"); long number = 1000; int marker = 0xAA; Assert.AssertEquals( "fromNumberWithMarker did not create the expected component", expected, new Name().append(net.named_data.jndn.Name.Component .fromNumberWithMarker(number, marker))); try { Assert.AssertEquals( "toNumberWithMarker did not return the expected value", number, expected.get(0).toNumberWithMarker(marker)); } catch (EncodingException ex) { Assert.Fail("Error while parsing a nonNegativeInteger: " + ex.Message); } }
/// <summary> /// Get the public key name from the full certificate name. /// </summary> /// /// <param name="certificateName">The full certificate name.</param> /// <returns>The related public key name.</returns> public static Name certificateNameToPublicKeyName(Name certificateName) { String idString = "ID-CERT"; bool foundIdString = false; int idCertComponentIndex = certificateName.size() - 1; for (; idCertComponentIndex + 1 > 0; --idCertComponentIndex) { if (certificateName.get(idCertComponentIndex).toEscapedString() .equals(idString)) { foundIdString = true; break; } } if (!foundIdString) throw new Exception("Incorrect identity certificate name " + certificateName.toUri()); Name tempName = certificateName.getSubName(0, idCertComponentIndex); String keyString = "KEY"; bool foundKeyString = false; int keyComponentIndex = 0; for (; keyComponentIndex < tempName.size(); keyComponentIndex++) { if (tempName.get(keyComponentIndex).toEscapedString() .equals(keyString)) { foundKeyString = true; break; } } if (!foundKeyString) throw new Exception("Incorrect identity certificate name " + certificateName.toUri()); return tempName.getSubName(0, keyComponentIndex).append( tempName.getSubName(keyComponentIndex + 1, tempName.size() - keyComponentIndex - 1)); }
/// <summary> /// Set a key as the default key of an identity. The identity name is inferred /// from keyName. /// </summary> /// /// <param name="keyName">The name of the key.</param> /// <param name="identityNameCheck"></param> public override sealed void setDefaultKeyNameForIdentity(Name keyName, Name identityNameCheck) { checkSetDefaultKeyNameForIdentity(keyName, identityNameCheck); String keyId = keyName.get(-1).toEscapedString(); Name identityName = keyName.getPrefix(-1); try { // Reset the previous default Key. PreparedStatement statement = database_ .prepareStatement("UPDATE Key SET default_key=0 WHERE " + net.named_data.jndn.security.identity.Sqlite3IdentityStorageBase.WHERE_setDefaultKeyNameForIdentity_reset); statement.setString(1, identityName.toUri()); try { statement.executeUpdate(); } finally { statement.close(); } // Set the current default Key. statement = database_ .prepareStatement("UPDATE Key SET default_key=1 WHERE " + net.named_data.jndn.security.identity.Sqlite3IdentityStorageBase.WHERE_setDefaultKeyNameForIdentity_set); statement.setString(1, identityName.toUri()); statement.setString(2, keyId); try { statement.executeUpdate(); } finally { statement.close(); } } catch (SQLException exception) { throw new SecurityException("BasicIdentityStorage: SQLite error: " + exception); } }
/// <summary> /// Check if the N components of this name are the same as the first N /// components of the given name. /// </summary> /// /// <param name="name">The Name to check.</param> /// <returns>true if this matches the given name, otherwise false. This always /// returns true if this name is empty.</returns> public bool match(Name name) { // This name is longer than the name we are checking it against. if (components_.Count > name.components_.Count) return false; // Check if at least one of given components doesn't match. Check from last // to first since the last components are more likely to differ. for (int i = components_.Count - 1; i >= 0; --i) { if (!get(i).getValue().equals(name.get(i).getValue())) return false; } return true; }
public Name append(Name name) { if (name == this) // Copying from this name, so need to make a copy first. return append(new Name(name)); for (int i = 0; i < name.components_.Count; ++i) append(name.get(i)); return this; }
public CredentialStorage() { this.identityStorage_ = new MemoryIdentityStorage(); this.privateKeyStorage_ = new MemoryPrivateKeyStorage(); this.keyChain_ = new KeyChain(new IdentityManager( identityStorage_, privateKeyStorage_), new SelfVerifyPolicyManager( identityStorage_)); Name keyName = new Name("/testname/DSK-123"); defaultCertName_ = keyName.getSubName(0, keyName.size() - 1) .append("KEY").append(keyName.get(-1)).append("ID-CERT") .append("0"); Name ecdsaKeyName = new Name("/testEcdsa/DSK-123"); ecdsaCertName_ = ecdsaKeyName.getSubName(0, ecdsaKeyName.size() - 1) .append("KEY").append(ecdsaKeyName.get(-1)).append("ID-CERT") .append("0"); try { identityStorage_.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob( DEFAULT_RSA_PUBLIC_KEY_DER, false)); privateKeyStorage_.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER); #if false // Skip ECDSA for now. identityStorage_.addKey(ecdsaKeyName, net.named_data.jndn.security.KeyType.ECDSA, new Blob( DEFAULT_EC_PUBLIC_KEY_DER, false)); privateKeyStorage_.setKeyPairForKeyName(ecdsaKeyName, net.named_data.jndn.security.KeyType.ECDSA, DEFAULT_EC_PUBLIC_KEY_DER, DEFAULT_EC_PRIVATE_KEY_DER); #endif } catch (SecurityException ex) { // Don't expect this to happen; System.Console.Out.WriteLine("Exception setting test keys: " + ex); identityStorage_ = null; privateKeyStorage_ = null; } }
public void testImplicitSha256Digest() { Name name = new Name(); ByteBuffer digest = toBuffer(new int[] { 0x28, 0xba, 0xd4, 0xb5, 0x27, 0x5b, 0xd3, 0x92, 0xdb, 0xb6, 0x70, 0xc7, 0x5c, 0xf0, 0xb6, 0x6f, 0x13, 0xf7, 0x94, 0x2b, 0x21, 0xe8, 0x0f, 0x55, 0xc0, 0xe8, 0x6b, 0x37, 0x47, 0x53, 0xa5, 0x48, 0x00, 0x00 }); digest.limit(32); name.appendImplicitSha256Digest(new Blob(digest, true)); name.appendImplicitSha256Digest(new Blob(digest, true) .getImmutableArray()); Assert.AssertEquals(name.get(0), name.get(1)); digest.limit(34); bool gotError = true; try { name.appendImplicitSha256Digest(new Blob(digest, true)); gotError = false; } catch (Exception ex) { } if (!gotError) Assert.Fail("Expected error in appendImplicitSha256Digest"); digest.limit(30); gotError = true; try { name.appendImplicitSha256Digest(new Blob(digest, true)); gotError = false; } catch (Exception ex_0) { } if (!gotError) Assert.Fail("Expected error in appendImplicitSha256Digest"); // Add name.get(2) as a generic component. digest.limit(32); name.append(new Blob(digest, true)); Assert.AssertTrue(name.get(0).compare(name.get(2)) < 0); Assert.AssertTrue(name.get(0).getValue().equals(name.get(2).getValue())); // Add name.get(3) as a generic component whose first byte is greater. digest.position(1); digest.limit(33); name.append(new Blob(digest, true)); Assert.AssertTrue(name.get(0).compare(name.get(3)) < 0); Assert.AssertEquals( "sha256digest=" + "28bad4b5275bd392dbb670c75cf0b66f13f7942b21e80f55c0e86b374753a548", name.get(0).toEscapedString()); Assert.AssertEquals(true, name.get(0).isImplicitSha256Digest()); Assert.AssertEquals(false, name.get(2).isImplicitSha256Digest()); gotError = true; try { new Name("/hello/sha256digest=hmm"); gotError = false; } catch (Exception ex_1) { } if (!gotError) Assert.Fail("Expected error in new Name from URI"); // Check canonical URI encoding (lower case). Name name2 = new Name( "/hello/sha256digest=" + "28bad4b5275bd392dbb670c75cf0b66f13f7942b21e80f55c0e86b374753a548"); Assert.AssertEquals(name.get(0), name2.get(1)); // Check that it will accept a hex value in upper case too. name2 = new Name( "/hello/sha256digest=" + "28BAD4B5275BD392DBB670C75CF0B66F13F7942B21E80F55C0E86B374753A548"); Assert.AssertEquals(name.get(0), name2.get(1)); // This is not valid sha256digest component. It should be treated as generic. name2 = new Name( "/hello/SHA256DIGEST=" + "28BAD4B5275BD392DBB670C75CF0B66F13F7942B21E80F55C0E86B374753A548"); Assert.AssertFalse(name.get(0).equals(name2.get(1))); Assert.AssertTrue(name2.get(1).isGeneric()); }
/// <summary> /// Check if the last component in the name is a segment number. /// </summary> /// /// <param name="name">The name to check.</param> /// <returns>True if the name ends with a segment number, otherwise false.</returns> private static bool endsWithSegmentNumber(Name name) { return name.size() >= 1 && name.get(-1).isSegment(); }
public void testTimestamp() { Name expected = new Name("/%FC%00%04%7BE%E3%1B%00%00"); Assert.AssertTrue(expected.get(0).isTimestamp()); // 40 years (not counting leap years) in microseconds. long number = (long) 40 * 365 * 24 * 3600 * 1000000; Assert.AssertEquals("appendTimestamp did not create the expected component", expected, new Name().appendTimestamp(number)); try { Assert.AssertEquals("toTimestamp did not return the expected value", number, expected.get(0).toTimestamp()); } catch (EncodingException ex) { Assert.Fail("Error while parsing a nonNegativeInteger: " + ex.Message); } }
static void Main(string[] args) { var data = new Data(); data.wireDecode(new Blob(TlvData)); Console.Out.WriteLine("Decoded Data:"); dumpData(data); // Set the content again to clear the cached encoding so we encode again. data.setContent(data.getContent()); var encoding = data.wireEncode(); var reDecodedData = new Data(); reDecodedData.wireDecode(encoding); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-decoded Data:"); dumpData(reDecodedData); var identityStorage = new MemoryIdentityStorage(); var privateKeyStorage = new MemoryPrivateKeyStorage(); var keyChain = new KeyChain (new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); // Initialize the storage. var keyName = new Name("/testname/DSK-123"); var certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER)); privateKeyStorage.setKeyPairForKeyName (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER), new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER)); VerifyCallbacks callbacks = new VerifyCallbacks("Re-decoded Data"); keyChain.verifyData(reDecodedData, callbacks, callbacks); var freshData = new Data(new Name("/ndn/abc")); freshData.setContent(new Blob("SUCCESS!")); freshData.getMetaInfo().setFreshnessPeriod(5000); freshData.getMetaInfo().setFinalBlockId(new Name("/%00%09").get(0)); keyChain.sign(freshData, certificateName); Console.Out.WriteLine(""); Console.Out.WriteLine("Freshly-signed Data:"); dumpData(freshData); callbacks = new VerifyCallbacks("Freshly-signed Data"); keyChain.verifyData(freshData, callbacks, callbacks); }
static void Main(string[] args) { var face = new Face (new TcpTransport(), new TcpTransport.ConnectionInfo("localhost")); // For now, when setting face.setCommandSigningInfo, use a key chain with // a default private key instead of the system default key chain. This // is OK for now because NFD is configured to skip verification, so it // ignores the system default key chain. var identityStorage = new MemoryIdentityStorage(); var privateKeyStorage = new MemoryPrivateKeyStorage(); var keyChain = new KeyChain (new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); keyChain.setFace(face); // Initialize the storage. var keyName = new Name("/testname/DSK-123"); var certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER)); privateKeyStorage.setKeyPairForKeyName (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER), new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER)); face.setCommandSigningInfo(keyChain, certificateName); var echo = new Echo(keyChain, certificateName); var prefix = new Name("/testecho"); Console.Out.WriteLine("Register prefix " + prefix.toUri()); face.registerPrefix(prefix, echo, echo); // The main event loop. // Wait to receive one interest for the prefix. while (echo.responseCount_ < 1) { face.processEvents(); // We need to sleep for a few milliseconds so we don't use 100% of // the CPU. System.Threading.Thread.Sleep(5); } }
/// <summary> /// In table Key, set 'active' to isActive for the keyName. /// </summary> /// /// <param name="keyName">The name of the key.</param> /// <param name="isActive">The value for the 'active' field.</param> protected internal override void updateKeyStatus(Name keyName, bool isActive) { String keyId = keyName.get(-1).toEscapedString(); Name identityName = keyName.getPrefix(-1); try { PreparedStatement statement = database_ .prepareStatement("UPDATE Key SET active=? WHERE " + net.named_data.jndn.security.identity.Sqlite3IdentityStorageBase.WHERE_updateKeyStatus); statement.setInt(1, ((isActive) ? 1 : 0)); statement.setString(2, identityName.toUri()); statement.setString(3, keyId); try { statement.executeUpdate(); } finally { statement.close(); } } catch (SQLException exception) { throw new SecurityException("BasicIdentityStorage: SQLite error: " + exception); } }
public void setUp() { MemoryIdentityStorage identityStorage = new MemoryIdentityStorage(); MemoryPrivateKeyStorage privateKeyStorage = new MemoryPrivateKeyStorage(); keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); // Initialize the storage. Name keyName = new Name("/testname/DSK-123"); certificateName = keyName.getSubName(0, keyName.size() - 1) .append("KEY").append(keyName.get(-1)).append("ID-CERT") .append("0"); try { identityStorage.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob( DEFAULT_RSA_PUBLIC_KEY_DER, false)); privateKeyStorage.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER); } catch (SecurityException ex) { // We don't expect this to happen. ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(TestLink).FullName).log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); } }
/// <summary> /// Encode the name as NDN-TLV to the encoder. /// </summary> /// /// <param name="name">The name to encode.</param> /// <param name="signedPortionBeginOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param> /// <param name="signedPortionEndOffset">name component and ends just before the final name component (which is assumed to be a signature for a signed interest).</param> /// <param name="encoder">The TlvEncoder to receive the encoding.</param> private static void encodeName(Name name, int[] signedPortionBeginOffset, int[] signedPortionEndOffset, TlvEncoder encoder) { int saveLength = encoder.getLength(); // Encode the components backwards. int signedPortionEndOffsetFromBack = 0; for (int i = name.size() - 1; i >= 0; --i) { encodeNameComponent(name.get(i), encoder); if (i == name.size() - 1) signedPortionEndOffsetFromBack = encoder.getLength(); } int signedPortionBeginOffsetFromBack = encoder.getLength(); encoder.writeTypeAndLength(net.named_data.jndn.encoding.tlv.Tlv.Name, encoder.getLength() - saveLength); signedPortionBeginOffset[0] = encoder.getLength() - signedPortionBeginOffsetFromBack; if (name.size() == 0) // There is no "final component", so set signedPortionEndOffset // arbitrarily. signedPortionEndOffset[0] = signedPortionBeginOffset[0]; else signedPortionEndOffset[0] = encoder.getLength() - signedPortionEndOffsetFromBack; }
public void testGetComponent() { Name name = new Name(expectedURI); Name.Component component2 = name.get(2); Assert.AssertTrue("Component at index 2 is incorrect", comp2.equals(component2)); }
private static Name getKeyNameFromCertificatePrefix(Name certificatePrefix) { Name result = new Name(); String keyString = "KEY"; int i = 0; for (; i < certificatePrefix.size(); i++) { if (certificatePrefix.get(i).toEscapedString().equals(keyString)) break; } if (i >= certificatePrefix.size()) throw new SecurityException( "Identity Certificate Prefix does not have a KEY component"); result.append(certificatePrefix.getSubName(0, i)); result.append(certificatePrefix.getSubName(i + 1, certificatePrefix.size() - i - 1)); return result; }
public void testPrefix() { Name name = new Name("/edu/cmu/andrew/user/3498478"); Name prefix1 = name.getPrefix(2); Assert.AssertEquals("Name prefix has " + prefix1.size() + " components instead of 2", 2, prefix1.size()); for (int i = 0; i < 2; ++i) Assert.AssertTrue(name.get(i).getValue().equals(prefix1.get(i).getValue())); Name prefix2 = name.getPrefix(100); Assert.AssertEquals( "Prefix with more components than original should stop at end of original name", name, prefix2); }
/// <summary> /// Prepare an unsigned identity certificate. /// </summary> /// /// <param name="keyName">The key name, e.g., `/{identity_name}/ksk-123456`.</param> /// <param name="publicKey">The public key to sign.</param> /// <param name="signingIdentity">The signing identity.</param> /// <param name="notBefore">See IdentityCertificate.</param> /// <param name="notAfter">See IdentityCertificate.</param> /// <param name="subjectDescription">on the keyName.</param> /// <param name="certPrefix">signingIdentity and the subject identity. If the signingIdentity is a prefix of the subject identity, `KEY` will be inserted after the signingIdentity, otherwise `KEY` is inserted after subject identity (i.e., before `ksk-...`).</param> /// <returns>The unsigned IdentityCertificate, or null if the inputs are invalid.</returns> public IdentityCertificate prepareUnsignedIdentityCertificate( Name keyName, PublicKey publicKey, Name signingIdentity, double notBefore, double notAfter, IList subjectDescription, Name certPrefix) { if (keyName.size() < 1) return null; String tempKeyIdPrefix = keyName.get(-1).toEscapedString(); if (tempKeyIdPrefix.Length < 4) return null; String keyIdPrefix = tempKeyIdPrefix.Substring(0,(4)-(0)); if (!keyIdPrefix.equals("ksk-") && !keyIdPrefix.equals("dsk-")) return null; IdentityCertificate certificate = new IdentityCertificate(); Name certName = new Name(); if (certPrefix == null) { // No certificate prefix hint, so infer the prefix. if (signingIdentity.match(keyName)) certName.append(signingIdentity).append("KEY") .append(keyName.getSubName(signingIdentity.size())) .append("ID-CERT") .appendVersion((long) net.named_data.jndn.util.Common.getNowMilliseconds()); else certName.append(keyName.getPrefix(-1)).append("KEY") .append(keyName.get(-1)).append("ID-CERT") .appendVersion((long) net.named_data.jndn.util.Common.getNowMilliseconds()); } else { // A cert prefix hint is supplied, so determine the cert name. if (certPrefix.match(keyName) && !certPrefix.equals(keyName)) certName.append(certPrefix).append("KEY") .append(keyName.getSubName(certPrefix.size())) .append("ID-CERT") .appendVersion((long) net.named_data.jndn.util.Common.getNowMilliseconds()); else return null; } certificate.setName(certName); certificate.setNotBefore(notBefore); certificate.setNotAfter(notAfter); certificate.setPublicKeyInfo(publicKey); if (subjectDescription == null || (subjectDescription.Count==0)) certificate .addSubjectDescription(new CertificateSubjectDescription( "2.5.4.41", keyName.getPrefix(-1).toUri())); else { for (int i = 0; i < subjectDescription.Count; ++i) certificate .addSubjectDescription((CertificateSubjectDescription) subjectDescription[i]); } try { certificate.encode(); } catch (DerEncodingException ex) { throw new SecurityException("DerEncodingException: " + ex); } catch (DerDecodingException ex_0) { throw new SecurityException("DerDecodingException: " + ex_0); } return certificate; }
public void testFullName() { Data data = new Data(); try { data.wireDecode(codedData); } catch (EncodingException ex) { Assert.Fail("Can't decode codedData"); } // Check the full name format. Assert.AssertEquals(data.getName().size() + 1, data.getFullName().size()); Assert.AssertEquals(data.getName(), data.getFullName().getPrefix(-1)); Assert.AssertEquals(32, data.getFullName().get(-1).getValue().size()); // Check the independent digest calculation. Blob newDigest = new Blob(net.named_data.jndn.util.Common.digestSha256(codedData)); Assert.AssertTrue(newDigest.equals(data.getFullName().get(-1).getValue())); // Check the expected URI. Assert.AssertEquals( "/ndn/abc/sha256digest=" + "96556d685dcb1af04be4ae57f0e7223457d4055ea9b3d07c0d337bef4a8b3ee9", data.getFullName().toUri()); // Changing the Data packet should change the full name. Name saveFullName = new Name(data.getFullName()); data.setContent(new Blob()); Assert.AssertFalse(data.getFullName().get(-1).equals(saveFullName.get(-1))); }
/// <summary> /// Generate a self-signed certificate for a public key. /// </summary> /// /// <param name="keyName">The name of the public key.</param> /// <returns>The generated certificate.</returns> public IdentityCertificate selfSign(Name keyName) { IdentityCertificate certificate = new IdentityCertificate(); Blob keyBlob = identityStorage_.getKey(keyName); PublicKey publicKey = new PublicKey(keyBlob); Calendar calendar = ILOG.J2CsMapping.Util.Calendar.getInstance(); double notBefore = (double) calendar.getTimeInMillis(); calendar.add(ILOG.J2CsMapping.Util.Calendar.YEAR, 2); double notAfter = (double) calendar.getTimeInMillis(); certificate.setNotBefore(notBefore); certificate.setNotAfter(notAfter); Name certificateName = keyName.getPrefix(-1).append("KEY") .append(keyName.get(-1)).append("ID-CERT") .appendVersion((long) certificate.getNotBefore()); certificate.setName(certificateName); certificate.setPublicKeyInfo(publicKey); certificate.addSubjectDescription(new CertificateSubjectDescription( "2.5.4.41", keyName.toUri())); try { certificate.encode(); } catch (DerEncodingException ex) { // We don't expect this to happen. ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(IdentityManager).FullName).log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); return null; } catch (DerDecodingException ex_0) { // We don't expect this to happen. ILOG.J2CsMapping.Util.Logging.Logger.getLogger(typeof(IdentityManager).FullName).log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_0); return null; } signByCertificate(certificate, certificate.getName()); return certificate; }
private static bool isCorrectName(Name name) { int i = name.size() - 1; String idString = "ID-CERT"; for (; i >= 0; i--) { if (name.get(i).toEscapedString().equals(idString)) break; } if (i < 0) return false; int keyIdx = 0; String keyString = "KEY"; for (; keyIdx < name.size(); keyIdx++) { if (name.get(keyIdx).toEscapedString().equals(keyString)) break; } if (keyIdx >= name.size()) return false; return true; }
/** * Loop to decode a data packet nIterations times. * @param nIterations The number of iterations. * @param useCrypto If true, verify the signature. If false, don't verify. * @param keyType KeyType.RSA or EC, used if useCrypto is true. * @param encoding The wire encoding to decode. * @return The number of seconds for all iterations. * @throws EncodingException */ private static double benchmarkDecodeDataSeconds(int nIterations, bool useCrypto, KeyType keyType, Blob encoding) { // Initialize the KeyChain storage in case useCrypto is true. MemoryIdentityStorage identityStorage = new MemoryIdentityStorage(); KeyChain keyChain = new KeyChain (new IdentityManager(identityStorage, new MemoryPrivateKeyStorage()), new SelfVerifyPolicyManager(identityStorage)); Name keyName = new Name("/testname/DSK-123"); Name certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER)); VerifyCallbacks callbacks = new VerifyCallbacks(); double start = getNowSeconds(); for (int i = 0; i < nIterations; ++i) { Data data = new Data(); data.wireDecode(encoding.buf()); if (useCrypto) keyChain.verifyData(data, callbacks, callbacks); } double finish = getNowSeconds(); return finish - start; }
/// <summary> /// Create a KeyChain with the a default name and key pair. /// </summary> /// /// <param name="certificateName">Set certificateName[0] to the signing certificateName.</param> /// <returns>The KeyChain.</returns> /// <exception cref="System.Security.SecurityException"></exception> public static KeyChain buildKeyChain(Name[] certificateName) { MemoryIdentityStorage identityStorage = new MemoryIdentityStorage(); MemoryPrivateKeyStorage privateKeyStorage = new MemoryPrivateKeyStorage(); KeyChain keyChain = new KeyChain(new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); // initialize the storage with Name keyName = new Name("/testname/DSK-123"); certificateName[0] = keyName.getSubName(0, keyName.size() - 1) .append("KEY").append(keyName.get(-1)).append("ID-CERT") .append("0"); identityStorage.addKey(keyName, net.named_data.jndn.security.KeyType.RSA, new Blob( DEFAULT_RSA_PUBLIC_KEY_DER, false)); privateKeyStorage.setKeyPairForKeyName(keyName, net.named_data.jndn.security.KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER); return keyChain; }
/** * Loop to encode a data packet nIterations times. * @param nIterations The number of iterations. * @param useComplex If true, use a large name, large content and all fields. * If false, use a small name, small content * and only required fields. * @param useCrypto If true, sign the data packet. If false, use a blank * signature. * @param keyType KeyType.RSA or EC, used if useCrypto is true. * @param encoding Set encoding[0] to the wire encoding. * @return The number of seconds for all iterations. */ private static double benchmarkEncodeDataSeconds(int nIterations, bool useComplex, bool useCrypto, KeyType keyType, Blob[] encoding) { Name name; Blob content; if (useComplex) { // Use a large name and content. name = new Name ("/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00"); StringBuilder contentStream = new StringBuilder(); int count = 1; contentStream.append(count++); while (contentStream.toString().Length < 1115) contentStream.append(" ").append(count++); content = new Blob(contentStream.toString()); } else { // Use a small name and content. name = new Name("/test"); content = new Blob("abc"); } Name.Component finalBlockId = new Name.Component(new Blob(new byte[] { (byte)0 })); // Initialize the KeyChain storage in case useCrypto is true. MemoryIdentityStorage identityStorage = new MemoryIdentityStorage(); MemoryPrivateKeyStorage privateKeyStorage = new MemoryPrivateKeyStorage(); KeyChain keyChain = new KeyChain (new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); Name keyName = new Name("/testname/DSK-123"); Name certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); privateKeyStorage.setKeyPairForKeyName (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER), new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER)); Blob signatureBits = new Blob(new byte[256]); Blob emptyBlob = new Blob(new byte[0]); double start = getNowSeconds(); for (int i = 0; i < nIterations; ++i) { Data data = new Data(name); data.setContent(content); if (useComplex) { data.getMetaInfo().setFreshnessPeriod(30000); data.getMetaInfo().setFinalBlockId(finalBlockId); } if (useCrypto) // This sets the signature fields. keyChain.sign(data, certificateName); else { // Imitate IdentityManager.signByCertificate to set up the signature // fields, but don't sign. KeyLocator keyLocator = new KeyLocator(); keyLocator.setType(KeyLocatorType.KEYNAME); keyLocator.setKeyName(certificateName); Sha256WithRsaSignature sha256Signature = (Sha256WithRsaSignature)data.getSignature(); sha256Signature.setKeyLocator(keyLocator); sha256Signature.setSignature(signatureBits); } encoding[0] = data.wireEncode(); } double finish = getNowSeconds(); return finish - start; }
/// <summary> /// Check if this name has the same component count and components as the given /// name. /// </summary> /// /// <param name="name">The Name to check.</param> /// <returns>true if the names are equal, otherwise false.</returns> public bool equals(Name name) { if (components_.Count != name.components_.Count) return false; // Check from last to first since the last components are more likely to differ. for (int i = components_.Count - 1; i >= 0; --i) { if (!get(i).getValue().equals(name.get(i).getValue())) return false; } return true; }
/// <summary> /// Check if this Interest's name matches the given name (using Name.match) /// and the given name also conforms to the interest selectors. /// </summary> /// /// <param name="name">The name to check.</param> /// <returns>True if the name and interest selectors match, otherwise false.</returns> public bool matchesName(Name name) { if (!getName().match(name)) return false; if (minSuffixComponents_ >= 0 && // Add 1 for the implicit digest. !(name.size() + 1 - getName().size() >= minSuffixComponents_)) return false; if (maxSuffixComponents_ >= 0 && // Add 1 for the implicit digest. !(name.size() + 1 - getName().size() <= maxSuffixComponents_)) return false; if (getExclude().size() > 0 && name.size() > getName().size() && getExclude().matches(name.get(getName().size()))) return false; return true; }
static void Main(string[] args) { var interest = new Interest(); interest.wireDecode(new Blob(TlvInterest)); Console.Out.WriteLine("Interest:"); dumpInterest(interest); // Set the name again to clear the cached encoding so we encode again. interest.setName(interest.getName()); var encoding = interest.wireEncode(); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-encoded interest " + encoding.toHex()); var reDecodedInterest = new Interest(); reDecodedInterest.wireDecode(encoding); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-decoded Interest:"); dumpInterest(reDecodedInterest); var freshInterest = new Interest(new Name("/ndn/abc")); freshInterest.setMinSuffixComponents(4); freshInterest.setMaxSuffixComponents(6); freshInterest.setInterestLifetimeMilliseconds(30000); freshInterest.setChildSelector(1); freshInterest.setMustBeFresh(true); freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST); freshInterest.getKeyLocator().setKeyData (new Blob(new byte[] { 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(new Name("abc").get(0)).appendAny(); var identityStorage = new MemoryIdentityStorage(); var privateKeyStorage = new MemoryPrivateKeyStorage(); var keyChain = new KeyChain (new IdentityManager(identityStorage, privateKeyStorage), new SelfVerifyPolicyManager(identityStorage)); // Initialize the storage. var keyName = new Name("/testname/DSK-123"); var certificateName = keyName.getSubName(0, keyName.size() - 1).append ("KEY").append(keyName.get(-1)).append("ID-CERT").append("0"); identityStorage.addKey(keyName, KeyType.RSA, new Blob(DEFAULT_RSA_PUBLIC_KEY_DER)); privateKeyStorage.setKeyPairForKeyName (keyName, KeyType.RSA, new ByteBuffer(DEFAULT_RSA_PUBLIC_KEY_DER), new ByteBuffer(DEFAULT_RSA_PRIVATE_KEY_DER)); // Make a Face just so that we can sign the interest. var face = new Face("localhost"); face.setCommandSigningInfo(keyChain, certificateName); face.makeCommandInterest(freshInterest); Interest reDecodedFreshInterest = new Interest(); reDecodedFreshInterest.wireDecode(freshInterest.wireEncode()); Console.Out.WriteLine(""); Console.Out.WriteLine("Re-decoded fresh Interest:"); dumpInterest(reDecodedFreshInterest); VerifyCallbacks callbacks = new VerifyCallbacks("Freshly-signed Interest"); keyChain.verifyInterest(reDecodedFreshInterest, callbacks, callbacks); }
/// <summary> /// Get the public key DER blob from the identity storage. /// </summary> /// /// <param name="keyName">The name of the requested public key.</param> /// <returns>The DER Blob.</returns> /// <exception cref="System.Security.SecurityException">if the key doesn't exist.</exception> public override sealed Blob getKey(Name keyName) { if (keyName.size() == 0) throw new SecurityException( "BasicIdentityStorage::getKey: Empty keyName"); String keyId = keyName.get(-1).toEscapedString(); Name identityName = keyName.getPrefix(-1); try { PreparedStatement statement = database_ .prepareStatement(net.named_data.jndn.security.identity.Sqlite3IdentityStorageBase.SELECT_getKey); statement.setString(1, identityName.toUri()); statement.setString(2, keyId); try { SqlDataReader result = statement.executeQuery(); if (result.NextResult()) return new Blob(result.getBytes("public_key"), false); else throw new SecurityException( "BasicIdentityStorage::getKey: The key does not exist"); } finally { statement.close(); } } catch (SQLException exception) { throw new SecurityException("BasicIdentityStorage: SQLite error: " + exception); } }