static void Main(string[] args) { try { var face = new Face (new TcpTransport(), new TcpTransport.ConnectionInfo("localhost")); var counter = new Counter1(); Console.Out.WriteLine("Enter a word to echo:"); var word = Console.In.ReadLine(); var name = new Name("/testecho"); name.append(word); Console.Out.WriteLine("Express name " + name.toUri()); face.expressInterest(name, counter, counter); // The main event loop. while (counter.callbackCount_ < 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); } } catch (Exception e) { Console.Out.WriteLine("exception: " + e.Message); } }
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 testOperateAesDecryptionKey() { // Test construction. ConsumerDb database = new Sqlite3ConsumerDb(System.IO.Path.GetFullPath(databaseFilePath.Name)); // Generate key blobs. Blob[] encryptionKeyBlob = { null }; Blob[] decryptionKeyBlob = { null }; generateAesKeys(encryptionKeyBlob, decryptionKeyBlob); Name keyName = new Name( "/alice/health/samples/activity/steps/C-KEY/20150928080000/20150928090000!"); keyName.append(new Name("FOR/alice/health/read/activity!")); database.addKey(keyName, decryptionKeyBlob[0]); Blob resultBlob = database.getKey(keyName); AssertTrue(decryptionKeyBlob[0].equals(resultBlob)); database.deleteKey(keyName); resultBlob = database.getKey(keyName); AssertEquals(0, resultBlob.size()); }
/// <summary> /// Prepare an encrypted data packet by encrypting the payload using the key /// according to the params. In addition, this prepares the encoded /// EncryptedContent with the encryption result using keyName and params. The /// encoding is set as the content of the data packet. If params defines an /// asymmetric encryption algorithm and the payload is larger than the maximum /// plaintext size, this encrypts the payload with a symmetric key that is /// asymmetrically encrypted and provided as a nonce in the content of the data /// packet. The packet's /{dataName}/ is updated to be /// /{dataName}/FOR/{keyName} /// </summary> /// /// <param name="data">The data packet which is updated.</param> /// <param name="payload">The payload to encrypt.</param> /// <param name="keyName">The key name for the EncryptedContent.</param> /// <param name="key">The encryption key value.</param> /// <param name="params">The parameters for encryption.</param> public static void encryptData(Data data, Blob payload, Name keyName, Blob key, EncryptParams paras) { data.getName().append(NAME_COMPONENT_FOR).append(keyName); EncryptAlgorithmType algorithmType = paras.getAlgorithmType(); if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc || algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesEcb) { EncryptedContent content = encryptSymmetric(payload, key, keyName, paras); data.setContent(content.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get())); } else if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaPkcs || algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep) { // Java doesn't have a direct way to get the maximum plain text size, so // try to encrypt the payload first and catch the error if it is too big. try { EncryptedContent content_0 = encryptAsymmetric(payload, key, keyName, paras); data.setContent(content_0.wireEncode(net.named_data.jndn.encoding.TlvWireFormat.get())); return; } catch (IllegalBlockSizeException ex) { // The payload is larger than the maximum plaintext size. Continue. } // 128-bit nonce. ByteBuffer nonceKeyBuffer = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(16); net.named_data.jndn.util.Common.getRandom().nextBytes(nonceKeyBuffer.array()); Blob nonceKey = new Blob(nonceKeyBuffer, false); Name nonceKeyName = new Name(keyName); nonceKeyName.append("nonce"); EncryptParams symmetricParams = new EncryptParams( net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc, net.named_data.jndn.encrypt.algo.AesAlgorithm.BLOCK_SIZE); EncryptedContent nonceContent = encryptSymmetric(payload, nonceKey, nonceKeyName, symmetricParams); EncryptedContent payloadContent = encryptAsymmetric(nonceKey, key, keyName, paras); Blob nonceContentEncoding = nonceContent.wireEncode(); Blob payloadContentEncoding = payloadContent.wireEncode(); ByteBuffer content_1 = ILOG.J2CsMapping.NIO.ByteBuffer.allocate(nonceContentEncoding .size() + payloadContentEncoding.size()); content_1.put(payloadContentEncoding.buf()); content_1.put(nonceContentEncoding.buf()); content_1.flip(); data.setContent(new Blob(content_1, false)); } else throw new Exception("Unsupported encryption method"); }
/// <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; }
/// <summary> /// Create an identity certificate for a public key supplied by the caller. /// </summary> /// /// <param name="certificatePrefix">The name of public key to be signed.</param> /// <param name="publicKey">The public key to be signed.</param> /// <param name="signerCertificateName">The name of signing certificate.</param> /// <param name="notBefore">The notBefore value in the validity field of the generated certificate.</param> /// <param name="notAfter">The notAfter vallue in validity field of the generated certificate.</param> /// <returns>The generated identity certificate.</returns> public IdentityCertificate createIdentityCertificate( Name certificatePrefix, PublicKey publicKey, Name signerCertificateName, double notBefore, double notAfter) { IdentityCertificate certificate = new IdentityCertificate(); Name keyName = getKeyNameFromCertificatePrefix(certificatePrefix); Name certificateName = new Name(certificatePrefix); certificateName.append("ID-CERT").appendVersion( (long) net.named_data.jndn.util.Common.getNowMilliseconds()); certificate.setName(certificateName); certificate.setNotBefore(notBefore); certificate.setNotAfter(notAfter); certificate.setPublicKeyInfo(publicKey); certificate.addSubjectDescription(new CertificateSubjectDescription( "2.5.4.41", keyName.toUri())); try { certificate.encode(); } catch (DerEncodingException ex) { throw new SecurityException("DerDecodingException: " + ex); } catch (DerDecodingException ex_0) { throw new SecurityException("DerEncodingException: " + ex_0); } Sha256WithRsaSignature sha256Sig = new Sha256WithRsaSignature(); KeyLocator keyLocator = new KeyLocator(); keyLocator.setType(net.named_data.jndn.KeyLocatorType.KEYNAME); keyLocator.setKeyName(signerCertificateName); sha256Sig.setKeyLocator(keyLocator); certificate.setSignature(sha256Sig); SignedBlob unsignedData = certificate.wireEncode(); IdentityCertificate signerCertificate; try { signerCertificate = getCertificate(signerCertificateName); } catch (DerDecodingException ex_1) { throw new SecurityException("DerDecodingException: " + ex_1); } Name signerkeyName = signerCertificate.getPublicKeyName(); Blob sigBits = privateKeyStorage_.sign(unsignedData.signedBuf(), signerkeyName); sha256Sig.setSignature(sigBits); return certificate; }
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; }
/// <summary> /// Decrypt the data packet. /// </summary> /// /// <param name="data">The data packet. This does not verify the packet.</param> /// <param name="onPlainText_0"></param> /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param> internal void decryptContent(Data data, Consumer.OnPlainText onPlainText_0, net.named_data.jndn.encrypt.EncryptError.OnError onError_1) { // Get the encrypted content. EncryptedContent dataEncryptedContent_2 = new EncryptedContent(); try { dataEncryptedContent_2.wireDecode(data.getContent()); } catch (EncodingException ex) { try { onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat, ex.Message); } catch (Exception exception) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception); } return; } Name cKeyName_3 = dataEncryptedContent_2.getKeyLocator().getKeyName(); // Check if the content key is already in the store. Blob cKey = (Blob) ILOG.J2CsMapping.Collections.Collections.Get(cKeyMap_,cKeyName_3); if (cKey != null) decrypt(dataEncryptedContent_2, cKey, onPlainText_0, onError_1); else { // Retrieve the C-KEY Data from the network. Name interestName = new Name(cKeyName_3); interestName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_FOR) .append(groupName_); Interest interest_4 = new Interest(interestName); // Prepare the callback functions. OnData onData_5 = new Consumer.Anonymous_C4 (this, cKeyName_3, onError_1, onPlainText_0, dataEncryptedContent_2); OnTimeout onTimeout = new Consumer.Anonymous_C3 (this, onData_5, onError_1, interest_4); // Express the Interest. try { face_.expressInterest(interest_4, onData_5, onTimeout); } catch (IOException ex_6) { try { onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.IOException, "expressInterest error: " + ex_6.Message); } catch (Exception exception_7) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_7); } } } }
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> /// Create a D-KEY Data packet with an EncryptedContent for the given private /// key, encrypted with the certificate key. /// </summary> /// /// <param name="startTimeStamp">The start time stamp string to put in the name.</param> /// <param name="endTimeStamp">The end time stamp string to put in the name.</param> /// <param name="keyName"></param> /// <param name="privateKeyBlob">A Blob of the encoded private key.</param> /// <param name="certificateKey"></param> /// <returns>The Data packet.</returns> /// <exception cref="System.Security.SecurityException">for an error using the security KeyChain.</exception> private Data createDKeyData(String startTimeStamp, String endTimeStamp, Name keyName, Blob privateKeyBlob, Blob certificateKey) { Name name = new Name(namespace_); name.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_D_KEY); name.append(startTimeStamp).append(endTimeStamp); Data data = new Data(name); data.getMetaInfo().setFreshnessPeriod( freshnessHours_ * MILLISECONDS_IN_HOUR); EncryptParams encryptParams = new EncryptParams( net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep); try { net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, privateKeyBlob, keyName, certificateKey, encryptParams); } catch (Exception ex) { // Consolidate errors such as InvalidKeyException. throw new SecurityException( "createDKeyData: Error in encryptData: " + ex.Message); } keyChain_.sign(data); return data; }
/// <summary> /// Get the content key from the database_ and encrypt it for the timeSlot /// using encryptionKey. /// </summary> /// /// <param name="encryptionKey">The encryption key value.</param> /// <param name="eKeyName">The key name for the EncryptedContent.</param> /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="onEncryptedKeys_1">encrypted content key Data packets. If onEncryptedKeys is null, this does not use it.</param> /// <returns>True if encryption succeeds, otherwise false.</returns> private bool encryptContentKey(Blob encryptionKey, Name eKeyName, double timeSlot_0, Producer.OnEncryptedKeys onEncryptedKeys_1, net.named_data.jndn.encrypt.EncryptError.OnError onError_2) { double timeCount = Math.Round(timeSlot_0,MidpointRounding.AwayFromZero); Producer.KeyRequest keyRequest = (Producer.KeyRequest ) ILOG.J2CsMapping.Collections.Collections.Get(keyRequests_,timeCount); Name keyName = new Name(namespace_); keyName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_C_KEY); keyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(getRoundedTimeSlot(timeSlot_0))); Blob contentKey = database_.getContentKey(timeSlot_0); Data cKeyData = new Data(); cKeyData.setName(keyName); EncryptParams paras = new EncryptParams(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep); try { net.named_data.jndn.encrypt.algo.Encryptor.encryptData(cKeyData, contentKey, eKeyName, encryptionKey, paras); } catch (Exception ex) { try { onError_2.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.EncryptionFailure, ex.Message); } catch (Exception exception) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception); } return false; } keyChain_.sign(cKeyData); ILOG.J2CsMapping.Collections.Collections.Add(keyRequest.encryptedKeys,cKeyData); updateKeyRequest(keyRequest, timeCount, onEncryptedKeys_1); return true; }
private void construct(Name prefix, Name dataType) { Name fixedPrefix = new Name(prefix); Name fixedDataType = new Name(dataType); // Fill ekeyInfo_ with all permutations of dataType, including the 'E-KEY' // component of the name. This will be used in createContentKey to send // interests without reconstructing names every time. fixedPrefix.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_READ); while (fixedDataType.size() > 0) { Name nodeName = new Name(fixedPrefix); nodeName.append(fixedDataType); nodeName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_E_KEY); ILOG.J2CsMapping.Collections.Collections.Put(eKeyInfo_,nodeName,new Producer.KeyInfo ()); fixedDataType = fixedDataType.getPrefix(-1); } fixedPrefix.append(dataType); namespace_ = new Name(prefix); namespace_.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_SAMPLE); namespace_.append(dataType); }
/// <summary> /// Encrypt the given content with the content key that covers timeSlot, and /// update the data packet with the encrypted content and an appropriate data /// name. /// </summary> /// /// <param name="data">An empty Data object which is updated.</param> /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="content">The content to encrypt.</param> /// <param name="onError_1">better error handling the callback should catch and properly handle any exceptions.</param> public void produce(Data data, double timeSlot_0, Blob content, net.named_data.jndn.encrypt.EncryptError.OnError onError_1) { // Get a content key. Name contentKeyName = createContentKey(timeSlot_0, null, onError_1); Blob contentKey = database_.getContentKey(timeSlot_0); // Produce data. Name dataName = new Name(namespace_); dataName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(timeSlot_0)); data.setName(dataName); EncryptParams paras = new EncryptParams(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc, 16); net.named_data.jndn.encrypt.algo.Encryptor .encryptData(data, content, contentKeyName, contentKey, paras); keyChain_.sign(data); }
/// <summary> /// Create the content key corresponding to the timeSlot. This first checks if /// the content key exists. For an existing content key, this returns the /// content key name directly. If the key does not exist, this creates one and /// encrypts it using the corresponding E-KEYs. The encrypted content keys are /// passed to the onEncryptedKeys callback. /// </summary> /// /// <param name="timeSlot_0">The time slot as milliseconds since Jan 1, 1970 UTC.</param> /// <param name="onEncryptedKeys_1">content key Data packets. If onEncryptedKeys is null, this does not use it. NOTE: The library will log any exceptions thrown by this callback, but for better error handling the callback should catch and properly handle any exceptions.</param> /// <param name="onError_2">better error handling the callback should catch and properly handle any exceptions.</param> /// <returns>The content key name.</returns> public Name createContentKey(double timeSlot_0, Producer.OnEncryptedKeys onEncryptedKeys_1, net.named_data.jndn.encrypt.EncryptError.OnError onError_2) { double hourSlot = getRoundedTimeSlot(timeSlot_0); // Create the content key name. Name contentKeyName = new Name(namespace_); contentKeyName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_C_KEY); contentKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(hourSlot)); Blob contentKeyBits; // Check if we have created the content key before. if (database_.hasContentKey(timeSlot_0)) // We have created the content key. Return its name directly. return contentKeyName; // We haven't created the content key. Create one and add it into the database. AesKeyParams aesParams = new AesKeyParams(128); contentKeyBits = net.named_data.jndn.encrypt.algo.AesAlgorithm.generateKey(aesParams).getKeyBits(); database_.addContentKey(timeSlot_0, contentKeyBits); // Now we need to retrieve the E-KEYs for content key encryption. double timeCount = Math.Round(timeSlot_0,MidpointRounding.AwayFromZero); ILOG.J2CsMapping.Collections.Collections.Put(keyRequests_,timeCount,new Producer.KeyRequest (eKeyInfo_.Count)); Producer.KeyRequest keyRequest = (Producer.KeyRequest ) ILOG.J2CsMapping.Collections.Collections.Get(keyRequests_,timeCount); // Check if the current E-KEYs can cover the content key. Exclude timeRange = new Exclude(); excludeAfter(timeRange, new Name.Component(net.named_data.jndn.encrypt.Schedule.toIsoString(timeSlot_0))); new ILOG.J2CsMapping.Collections.IteratorAdapter(eKeyInfo_.GetEnumerator()); for (IIterator i = new ILOG.J2CsMapping.Collections.IteratorAdapter(eKeyInfo_.GetEnumerator()); i.HasNext();) { // For each current E-KEY. DictionaryEntry entry = (DictionaryEntry) i.Next(); Producer.KeyInfo keyInfo = (Producer.KeyInfo ) ((DictionaryEntry) entry).Value; if (timeSlot_0 < keyInfo.beginTimeSlot || timeSlot_0 >= keyInfo.endTimeSlot) { // The current E-KEY cannot cover the content key, so retrieve one. ILOG.J2CsMapping.Collections.Collections.Put(keyRequest.repeatAttempts,((DictionaryEntry) entry).Key,0); sendKeyInterest( new Interest((Name) ((DictionaryEntry) entry).Key).setExclude( timeRange).setChildSelector(1), timeSlot_0, onEncryptedKeys_1, onError_2); } else { // The current E-KEY can cover the content key. // Encrypt the content key directly. Name eKeyName = new Name((Name) ((DictionaryEntry) entry).Key); eKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(keyInfo.beginTimeSlot)); eKeyName.append(net.named_data.jndn.encrypt.Schedule.toIsoString(keyInfo.endTimeSlot)); encryptContentKey(keyInfo.keyBits, eKeyName, timeSlot_0, onEncryptedKeys_1, onError_2); } } return contentKeyName; }
public void testRegisterPrefixResponse() { Name prefixName = new Name("/test"); int[] interestCallbackCount_0 = new int[] { 0 }; int[] failedCallbackCount_1 = new int[] { 0 }; faceIn.registerPrefix(prefixName, new TestFaceCallRegisterMethods.Anonymous_C3 (this, interestCallbackCount_0), new TestFaceCallRegisterMethods.Anonymous_C2 (failedCallbackCount_1)); // Give the "server" time to register the interest. double timeout = 1000; double startTime = getNowMilliseconds(); while (getNowMilliseconds() - startTime < timeout) { try { faceIn.processEvents(); } catch (IOException ex) { logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex); break; } catch (EncodingException ex_2) { logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_2); break; } try { // We need to sleep for a few milliseconds so we don't use 100% of the CPU. ILOG.J2CsMapping.Threading.ThreadWrapper.sleep(10); } catch (ThreadInterruptedException ex_3) { logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_3); break; } } // Now express an interest on this new face, and see if onInterest is called. // Add the timestamp so it is unique and we don't get a cached response. int[] dataCallbackCount_4 = new int[] { 0 }; int[] timeoutCallbackCount_5 = new int[] { 0 }; Data[] receivedData_6 = new Data[1]; Name interestName = prefixName.append("hello" + getNowMilliseconds()); faceOut.expressInterest(interestName, new TestFaceCallRegisterMethods.Anonymous_C1 (receivedData_6, dataCallbackCount_4), new TestFaceCallRegisterMethods.Anonymous_C0 (timeoutCallbackCount_5)); // Process events for the in and out faces. timeout = 10000; startTime = getNowMilliseconds(); while (getNowMilliseconds() - startTime < timeout) { try { faceIn.processEvents(); faceOut.processEvents(); } catch (IOException ex_7) { logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_7); break; } catch (EncodingException ex_8) { logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_8); break; } bool done = true; if (interestCallbackCount_0[0] == 0 && failedCallbackCount_1[0] == 0) // Still processing faceIn. done = false; if (dataCallbackCount_4[0] == 0 && timeoutCallbackCount_5[0] == 0) // Still processing face_out. done = false; if (done) break; try { // We need to sleep for a few milliseconds so we don't use 100% of the CPU. ILOG.J2CsMapping.Threading.ThreadWrapper.sleep(10); } catch (ThreadInterruptedException ex_9) { logger.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, null, ex_9); break; } } AssertEquals("Failed to register prefix at all", 0, failedCallbackCount_1[0]); AssertEquals("Expected 1 onInterest callback", 1, interestCallbackCount_0[0]); AssertEquals("Expected 1 onData callback", 1, dataCallbackCount_4[0]); // Check the message content. Blob expectedBlob = new Blob("SUCCESS"); AssertTrue( "Data received on the face does not match the expected format", expectedBlob.equals(receivedData_6[0].getContent())); }
public void testHashCode() { Name foo1 = new Name("/ndn/foo"); Name foo2 = new Name("/ndn/foo"); Assert.AssertEquals("Hash codes for same Name value are not equal", foo1.GetHashCode(), foo2.GetHashCode()); Name bar1 = new Name("/ndn/bar"); // Strictly speaking, it is possible for a hash collision, but unlikely. Assert.AssertTrue("Hash codes for different Name values are not different", foo1.GetHashCode() != bar1.GetHashCode()); Name bar2 = new Name("/ndn"); int beforeHashCode = bar2.GetHashCode(); bar2.append("bar"); Assert.AssertTrue("Hash code did not change when changing the Name object", beforeHashCode != bar2.GetHashCode()); Assert.AssertEquals( "Hash codes for same Name value after changes are not equal", bar1.GetHashCode(), bar2.GetHashCode()); }
/// <summary> /// Create an E-KEY Data packet for the given public key. /// </summary> /// /// <param name="startTimeStamp">The start time stamp string to put in the name.</param> /// <param name="endTimeStamp">The end time stamp string to put in the name.</param> /// <param name="publicKeyBlob">A Blob of the public key DER.</param> /// <returns>The Data packet.</returns> /// <exception cref="System.Security.SecurityException">for an error using the security KeyChain.</exception> private Data createEKeyData(String startTimeStamp, String endTimeStamp, Blob publicKeyBlob) { Name name = new Name(namespace_); name.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_E_KEY).append(startTimeStamp) .append(endTimeStamp); Data data = new Data(name); data.getMetaInfo().setFreshnessPeriod( freshnessHours_ * MILLISECONDS_IN_HOUR); data.setContent(publicKeyBlob); keyChain_.sign(data); return data; }
/// <summary> /// Decode the name as NDN-TLV and set the fields in name. /// </summary> /// /// <param name="name">The name object whose fields are set.</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). If you are not decoding in order to verify, you can ignore this returned value.</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). If you are not decoding in order to verify, you can ignore this returned value.</param> /// <param name="decoder">The decoder with the input to decode.</param> /// <param name="copy">unchanged while the Blob values are used.</param> /// <exception cref="EncodingException"></exception> private static void decodeName(Name name, int[] signedPortionBeginOffset, int[] signedPortionEndOffset, TlvDecoder decoder, bool copy) { name.clear(); int endOffset = decoder.readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Name); signedPortionBeginOffset[0] = decoder.getOffset(); // In case there are no components, set signedPortionEndOffset arbitrarily. signedPortionEndOffset[0] = signedPortionBeginOffset[0]; while (decoder.getOffset() < endOffset) { signedPortionEndOffset[0] = decoder.getOffset(); name.append(decodeNameComponent(decoder, copy)); } decoder.finishNestedTlvs(endOffset); }
public void testContentAsymmetricEncryptLarge() { /* foreach */ foreach (TestEncryptor.AsymmetricEncryptInput input in encryptorRsaTestInputs) { Blob largeContent = new Blob(toBuffer(new int[] { 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 = new Data(); RsaKeyParams rsaParams = new RsaKeyParams(1024); Name keyName = new Name("test"); DecryptKey decryptKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.generateKey(rsaParams); EncryptKey encryptKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.deriveEncryptKey(decryptKey .getKeyBits()); Blob eKey = encryptKey.getKeyBits(); Blob dKey = decryptKey.getKeyBits(); EncryptParams encryptParams = new EncryptParams(input.type()); net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, largeContent, keyName, eKey, encryptParams); Assert.AssertEquals(input.testName(), new Name("/FOR").append(keyName), data.getName()); Blob largeDataContent = data.getContent(); // largeDataContent is a sequence of the two EncryptedContent. EncryptedContent encryptedNonce = new EncryptedContent(); encryptedNonce.wireDecode(largeDataContent); Assert.AssertEquals(input.testName(), keyName, encryptedNonce .getKeyLocator().getKeyName()); Assert.AssertEquals(input.testName(), 0, encryptedNonce.getInitialVector() .size()); Assert.AssertEquals(input.testName(), input.type(), encryptedNonce.getAlgorithmType()); // Use the size of encryptedNonce to find the start of encryptedPayload. ByteBuffer payloadContent = largeDataContent.buf().duplicate(); payloadContent.position(encryptedNonce.wireEncode().size()); EncryptedContent encryptedPayload = new EncryptedContent(); encryptedPayload.wireDecode(payloadContent); Name nonceKeyName = new Name(keyName); nonceKeyName.append("nonce"); Assert.AssertEquals(input.testName(), nonceKeyName, encryptedPayload .getKeyLocator().getKeyName()); Assert.AssertEquals(input.testName(), 16, encryptedPayload .getInitialVector().size()); Assert.AssertEquals(input.testName(), net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc, encryptedPayload.getAlgorithmType()); Assert.AssertTrue(input.testName(), encryptedNonce.wireEncode().size() + encryptedPayload.wireEncode().size() == largeDataContent .size()); Blob blobNonce = encryptedNonce.getPayload(); Blob nonce = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(dKey, blobNonce, encryptParams); encryptParams.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc); encryptParams.setInitialVector(encryptedPayload.getInitialVector()); Blob bufferPayload = encryptedPayload.getPayload(); Blob largePayload = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(nonce, bufferPayload, encryptParams); Assert.AssertTrue(input.testName(), largeContent.equals(largePayload)); } }
/// <summary> /// Get the successor of this name which is defined as follows. /// N represents the set of NDN Names, and X,Y ∈ N. /// Operator < is defined by the NDN canonical order on N. /// Y is the successor of X, if (a) X < Y, and (b) ∄ Z ∈ N s.t. X < Z < Y. /// In plain words, the successor of a name is the same name, but with its last /// component advanced to a next possible value. /// Examples: /// - The successor of / is /%00 /// - The successor of /%00%01/%01%02 is /%00%01/%01%03 /// - The successor of /%00%01/%01%FF is /%00%01/%02%00 /// - The successor of /%00%01/%FF%FF is /%00%01/%00%00%00 /// </summary> /// /// <returns>A new name which is the successor of this.</returns> public Name getSuccessor() { if (size() == 0) { // Return "/%00". Name result = new Name(); result.append(new byte[1]); return result; } else return getPrefix(-1).append(get(-1).getSuccessor()); }
/// <summary> /// Decrypt cKeyData. /// </summary> /// /// <param name="cKeyData">The C-KEY data packet.</param> /// <param name="onPlainText_0"></param> /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param> internal void decryptCKey(Data cKeyData, Consumer.OnPlainText onPlainText_0, net.named_data.jndn.encrypt.EncryptError.OnError onError_1) { // Get the encrypted content. Blob cKeyContent = cKeyData.getContent(); EncryptedContent cKeyEncryptedContent_2 = new EncryptedContent(); try { cKeyEncryptedContent_2.wireDecode(cKeyContent); } catch (EncodingException ex) { try { onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat, ex.Message); } catch (Exception exception) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception); } return; } Name eKeyName = cKeyEncryptedContent_2.getKeyLocator().getKeyName(); Name dKeyName_3 = eKeyName.getPrefix(-3); dKeyName_3.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_D_KEY).append( eKeyName.getSubName(-2)); // Check if the decryption key is already in the store. Blob dKey = (Blob) ILOG.J2CsMapping.Collections.Collections.Get(dKeyMap_,dKeyName_3); if (dKey != null) decrypt(cKeyEncryptedContent_2, dKey, onPlainText_0, onError_1); else { // Get the D-Key Data. Name interestName = new Name(dKeyName_3); interestName.append(net.named_data.jndn.encrypt.algo.Encryptor.NAME_COMPONENT_FOR).append( consumerName_); Interest interest_4 = new Interest(interestName); // Prepare the callback functions. OnData onData_5 = new Consumer.Anonymous_C2 (this, onError_1, onPlainText_0, dKeyName_3, cKeyEncryptedContent_2); OnTimeout onTimeout = new Consumer.Anonymous_C1 (this, interest_4, onData_5, onError_1); // Express the Interest. try { face_.expressInterest(interest_4, onData_5, onTimeout); } catch (IOException ex_6) { try { onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.IOException, "expressInterest error: " + ex_6.Message); } catch (Exception exception_7) { logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_7); } } } }