Exemple #1
0
        /// <returns>True for success, false for error (where this has called onError).</returns>
        internal bool decryptAndImportKdk(Data kdkData,
                                          EncryptError.OnError onError_0)
        {
            try {
                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.INFO, "Decrypting and importing KDK {0}",
                            kdkData.getName());
                EncryptedContent encryptedContent_1 = new EncryptedContent();
                encryptedContent_1.wireDecodeV2(kdkData.getContent());

                SafeBag safeBag = new SafeBag(encryptedContent_1.getPayload());
                Blob    secret  = keyChain_.getTpm().decrypt(
                    encryptedContent_1.getPayloadKey().buf(),
                    credentialsKey_.getName());
                if (secret.isNull())
                {
                    onError_0.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.TpmKeyNotFound,
                                      "Could not decrypt secret, "
                                      + credentialsKey_.getName().toUri()
                                      + " not found in TPM");
                    return(false);
                }

                internalKeyChain_.importSafeBag(safeBag, secret.buf());
                return(true);
            } catch (Exception ex) {
                // This can be EncodingException, Pib.Error, Tpm.Error, or a bunch of
                // other runtime-derived errors.
                onError_0.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.DecryptionFailure,
                                  "Failed to decrypt KDK [" + kdkData.getName().toUri()
                                  + "]: " + ex);
                return(false);
            }
        }
Exemple #2
0
        private static void doDecrypt(EncryptedContent content, Blob ckBits,
                                      DecryptorV2.DecryptSuccessCallback onSuccess_0, EncryptError.OnError onError_1)
        {
            if (!content.hasInitialVector())
            {
                onError_1.onError(
                    net.named_data.jndn.encrypt.EncryptError.ErrorCode.MissingRequiredInitialVector,
                    "Expecting Initial Vector in the encrypted content, but it is not present");
                return;
            }

            Blob plainData;

            try {
                Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5PADDING");
                cipher.init(javax.crypto.Cipher.DECRYPT_MODE,
                            new SecretKeySpec(ckBits.getImmutableArray(), "AES"),
                            new IvParameterSpec(content.getInitialVector()
                                                .getImmutableArray()));
                plainData = new Blob(cipher.doFinal(content.getPayload()
                                                    .getImmutableArray()), false);
            } catch (Exception ex) {
                onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.DecryptionFailure,
                                  "Decryption error in doDecrypt: " + ex);
                return;
            }

            try {
                onSuccess_0.onSuccess(plainData);
            } catch (Exception exception) {
                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onSuccess", exception);
            }
        }
Exemple #3
0
        /// <summary>
        /// Encrypt the plainData using the existing Content Key (CK) and return a new
        /// EncryptedContent.
        /// </summary>
        ///
        /// <param name="plainData">The data to encrypt.</param>
        /// <returns>The new EncryptedContent.</returns>
        public EncryptedContent encrypt(byte[] plainData)
        {
            // Generate the initial vector.
            byte[] initialVector = new byte[AES_IV_SIZE];
            net.named_data.jndn.util.Common.getRandom().nextBytes(initialVector);

            Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/PKCS5PADDING");

            try {
                cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, new SecretKeySpec(ckBits_, "AES"),
                            new IvParameterSpec(initialVector));
            } catch (InvalidKeyException ex) {
                throw new Exception(
                          "If the error is 'Illegal key size', try installing the "
                          + "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files: "
                          + ex);
            }
            byte[] encryptedData = cipher.doFinal(plainData);

            EncryptedContent content = new EncryptedContent();

            content.setInitialVector(new Blob(initialVector, false));
            content.setPayload(new Blob(encryptedData, false));
            content.setKeyLocatorName(ckName_);

            return(content);
        }
Exemple #4
0
        /// <summary>
        /// Make a CK Data packet for ckName_ encrypted by the KEK in kekData_ and
        /// insert it in the storage_.
        /// </summary>
        ///
        /// <param name="onError_0">error string.</param>
        /// <returns>True on success, else false.</returns>
        internal bool makeAndPublishCkData(net.named_data.jndn.encrypt.EncryptError.OnError onError_0)
        {
            try {
                PublicKey kek = new PublicKey(kekData_.getContent());

                EncryptedContent content = new EncryptedContent();
                content.setPayload(kek.encrypt(ckBits_,
                                               net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep));

                Data ckData = new Data(new Name(ckName_).append(
                                           NAME_COMPONENT_ENCRYPTED_BY).append(kekData_.getName()));
                ckData.setContent(content.wireEncodeV2());
                // FreshnessPeriod can serve as a soft access control for revoking access.
                ckData.getMetaInfo().setFreshnessPeriod(
                    DEFAULT_CK_FRESHNESS_PERIOD_MS);
                keyChain_.sign(ckData, ckDataSigningInfo_);
                storage_.insert(ckData);

                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.INFO, "Publishing CK data: {0}", ckData.getName());
                return(true);
            } catch (Exception ex) {
                onError_0.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.EncryptionFailure,
                                  "Failed to encrypt generated CK with KEK "
                                  + kekData_.getName().toUri());
                return(false);
            }
        }
Exemple #5
0
 public PendingDecrypt(EncryptedContent encryptedContent,
                       DecryptorV2.DecryptSuccessCallback onSuccess,
                       EncryptError.OnError onError_0)
 {
     this.encryptedContent = encryptedContent;
     this.onSuccess        = onSuccess;
     this.onError          = onError_0;
 }
Exemple #6
0
        /// <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, cKeyEncryptedContent_2,
                                                            dKeyName_3);

                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);
                    }
                }
            }
        }
Exemple #7
0
 public Anonymous_C5(Consumer paramouter_Consumer,
                     EncryptedContent dataEncryptedContent_0, net.named_data.jndn.encrypt.EncryptError.OnError onError_1,
                     Consumer.OnPlainText onPlainText_2, Name cKeyName_3)
 {
     this.dataEncryptedContent = dataEncryptedContent_0;
     this.onError        = onError_1;
     this.onPlainText    = onPlainText_2;
     this.cKeyName       = cKeyName_3;
     this.outer_Consumer = paramouter_Consumer;
 }
Exemple #8
0
 public Anonymous_C4(Consumer paramouter_Consumer,
                     Consumer.OnPlainText onPlainText_0, Name dKeyName_1, net.named_data.jndn.encrypt.EncryptError.OnError onError_2,
                     EncryptedContent cKeyEncryptedContent_3)
 {
     this.onPlainText          = onPlainText_0;
     this.dKeyName             = dKeyName_1;
     this.onError              = onError_2;
     this.cKeyEncryptedContent = cKeyEncryptedContent_3;
     this.outer_Consumer       = paramouter_Consumer;
 }
Exemple #9
0
 /// <summary>
 /// Create an EncryptedContent as a deep copy of the given object.
 /// </summary>
 ///
 /// <param name="encryptedContent">The other encryptedContent to copy.</param>
 public EncryptedContent(EncryptedContent encryptedContent)
 {
     this.algorithmType_ = default(EncryptAlgorithmType) /* was: null */;
     this.keyLocator_    = new KeyLocator();
     this.initialVector_ = new Blob();
     this.payload_       = new Blob();
     algorithmType_      = encryptedContent.algorithmType_;
     keyLocator_         = new KeyLocator(encryptedContent.keyLocator_);
     initialVector_      = encryptedContent.initialVector_;
     payload_            = encryptedContent.payload_;
 }
 /// <summary>
 /// Create an EncryptedContent as a deep copy of the given object.
 /// </summary>
 ///
 /// <param name="encryptedContent">The other encryptedContent to copy.</param>
 public EncryptedContent(EncryptedContent encryptedContent)
 {
     this.algorithmType_ = net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.NONE;
     this.keyLocator_ = new KeyLocator();
     this.initialVector_ = new Blob();
     this.payload_ = new Blob();
     algorithmType_ = encryptedContent.algorithmType_;
     keyLocator_ = new KeyLocator(encryptedContent.keyLocator_);
     initialVector_ = encryptedContent.initialVector_;
     payload_ = encryptedContent.payload_;
 }
 /// <summary>
 /// Create an EncryptedContent as a deep copy of the given object.
 /// </summary>
 ///
 /// <param name="encryptedContent">The other encryptedContent to copy.</param>
 public EncryptedContent(EncryptedContent encryptedContent)
 {
     this.algorithmType_ = net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.NONE;
     this.keyLocator_    = new KeyLocator();
     this.initialVector_ = new Blob();
     this.payload_       = new Blob();
     this.payloadKey_    = new Blob();
     algorithmType_      = encryptedContent.algorithmType_;
     keyLocator_         = new KeyLocator(encryptedContent.keyLocator_);
     initialVector_      = encryptedContent.initialVector_;
     payload_            = encryptedContent.payload_;
 }
Exemple #12
0
        /// <summary>
        /// Decrypt the data packet.
        /// </summary>
        ///
        /// <param name="data">The data 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, dataEncryptedContent_2, onPlainText_0,
                                                            onError_1);

                OnTimeout onTimeout = new Consumer.Anonymous_C3(this, onError_1, interest_4, onData_5);

                // 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);
                    }
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Asynchronously decrypt the encryptedContent.
        /// </summary>
        ///
        /// <param name="encryptedContent">the EncryptedContent object. If you may change it later, then pass in a copy of the object.</param>
        /// <param name="onSuccess">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_0">error string. 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>
        public void decrypt(EncryptedContent encryptedContent,
                            DecryptorV2.DecryptSuccessCallback onSuccess, EncryptError.OnError onError_0)
        {
            if (encryptedContent.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.KEYNAME)
            {
                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.INFO,
                            "Missing required KeyLocator in the supplied EncryptedContent block");
                onError_0.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.MissingRequiredKeyLocator,
                                  "Missing required KeyLocator in the supplied EncryptedContent block");
                return;
            }

            if (!encryptedContent.hasInitialVector())
            {
                logger_.log(ILOG.J2CsMapping.Util.Logging.Level.INFO,
                            "Missing required initial vector in the supplied EncryptedContent block");
                onError_0.onError(
                    net.named_data.jndn.encrypt.EncryptError.ErrorCode.MissingRequiredInitialVector,
                    "Missing required initial vector in the supplied EncryptedContent block");
                return;
            }

            Name ckName_1 = encryptedContent.getKeyLocatorName();

            DecryptorV2.ContentKey contentKey_2 = ILOG.J2CsMapping.Collections.Collections.Get(contentKeys_, ckName_1);
            bool isNew = (contentKey_2 == null);

            if (isNew)
            {
                contentKey_2 = new DecryptorV2.ContentKey();
                ILOG.J2CsMapping.Collections.Collections.Put(contentKeys_, ckName_1, contentKey_2);
            }

            if (contentKey_2.isRetrieved)
            {
                doDecrypt(encryptedContent, contentKey_2.bits, onSuccess, onError_0);
            }
            else
            {
                logger_.log(
                    ILOG.J2CsMapping.Util.Logging.Level.INFO,
                    "CK {0} not yet available, so adding to the pending decrypt queue",
                    ckName_1);
                ILOG.J2CsMapping.Collections.Collections.Add(contentKey_2.pendingDecrypts, new ContentKey.PendingDecrypt(
                                                                 encryptedContent, onSuccess, onError_0));
            }

            if (isNew)
            {
                fetchCk(ckName_1, contentKey_2, onError_0, net.named_data.jndn.encrypt.EncryptorV2.N_RETRIES);
            }
        }
        /// <summary>
        /// Authorize a member identified by memberCertificate to decrypt data under
        /// the policy.
        /// </summary>
        ///
        /// <param name="memberCertificate"></param>
        /// <returns>The published KDK Data packet.</returns>
        public Data addMember(CertificateV2 memberCertificate)
        {
            Name kdkName = new Name(nacKey_.getIdentityName());

            kdkName.append(net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_KDK)
            .append(nacKey_.getName().get(-1))
            // key-id
            .append(net.named_data.jndn.encrypt.EncryptorV2.NAME_COMPONENT_ENCRYPTED_BY)
            .append(memberCertificate.getKeyName());

            int secretLength = 32;

            byte[] secret = new byte[secretLength];
            net.named_data.jndn.util.Common.getRandom().nextBytes(secret);
            // To be compatible with OpenSSL which uses a null-terminated string,
            // replace each 0 with 1. And to be compatible with the Java security
            // library which interprets the secret as a char array converted to UTF8,
            // limit each byte to the ASCII range 1 to 127.
            for (int i = 0; i < secretLength; ++i)
            {
                if (secret[i] == 0)
                {
                    secret[i] = 1;
                }

                secret[i] &= 0x7f;
            }

            SafeBag kdkSafeBag = keyChain_.exportSafeBag(
                nacKey_.getDefaultCertificate(), ILOG.J2CsMapping.NIO.ByteBuffer.wrap(secret));

            PublicKey memberKey = new PublicKey(memberCertificate.getPublicKey());

            EncryptedContent encryptedContent = new EncryptedContent();

            encryptedContent.setPayload(kdkSafeBag.wireEncode());
            encryptedContent.setPayloadKey(memberKey.encrypt(secret,
                                                             net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep));

            Data kdkData = new Data(kdkName);

            kdkData.setContent(encryptedContent.wireEncodeV2());
            // FreshnessPeriod can serve as a soft access control for revoking access.
            kdkData.getMetaInfo().setFreshnessPeriod(
                DEFAULT_KDK_FRESHNESS_PERIOD_MS);
            keyChain_.sign(kdkData, new SigningInfo(identity_));

            storage_.insert(kdkData);

            return(kdkData);
        }
Exemple #15
0
        internal void decryptCkAndProcessPendingDecrypts(DecryptorV2.ContentKey contentKey_0,
                                                         Data ckData_1, Name kdkKeyName, EncryptError.OnError onError_2)
        {
            logger_.log(ILOG.J2CsMapping.Util.Logging.Level.INFO, "Decrypting CK data {0}", ckData_1.getName());

            EncryptedContent content = new EncryptedContent();

            try {
                content.wireDecodeV2(ckData_1.getContent());
            } catch (Exception ex) {
                onError_2.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                                  "Error decrypting EncryptedContent: " + ex);
                return;
            }

            Blob ckBits;

            try {
                ckBits = internalKeyChain_.getTpm().decrypt(
                    content.getPayload().buf(), kdkKeyName);
            } catch (Exception ex_3) {
                // We don't expect this from the in-memory KeyChain.
                onError_2.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.DecryptionFailure,
                                  "Error decrypting the CK EncryptedContent " + ex_3);
                return;
            }

            if (ckBits.isNull())
            {
                onError_2.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.TpmKeyNotFound,
                                  "Could not decrypt secret, " + kdkKeyName.toUri()
                                  + " not found in TPM");
                return;
            }

            contentKey_0.bits        = ckBits;
            contentKey_0.isRetrieved = true;

            /* foreach */
            foreach (ContentKey.PendingDecrypt pendingDecrypt  in  contentKey_0.pendingDecrypts)
            {
                // TODO: If this calls onError, should we quit?
                doDecrypt(pendingDecrypt.encryptedContent, contentKey_0.bits,
                          pendingDecrypt.onSuccess, pendingDecrypt.onError);
            }

            ILOG.J2CsMapping.Collections.Collections.Clear(contentKey_0.pendingDecrypts);
        }
Exemple #16
0
        /// <summary>
        /// Decode encryptedBlob as an EncryptedContent and decrypt using keyBits.
        /// </summary>
        ///
        /// <param name="encryptedBlob">The encoded EncryptedContent to decrypt.</param>
        /// <param name="keyBits">The key value.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        private static void decrypt(Blob encryptedBlob, Blob keyBits,
                                    Consumer.OnPlainText onPlainText_0, net.named_data.jndn.encrypt.EncryptError.OnError onError_1)
        {
            EncryptedContent encryptedContent = new EncryptedContent();

            try {
                encryptedContent.wireDecode(encryptedBlob);
            } 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;
            }

            decrypt(encryptedContent, keyBits, onPlainText_0, onError_1);
        }
Exemple #17
0
        /// <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 = new Interest(interestName);
                sendInterest(interest, 1, cKeyLink_, new Consumer.Anonymous_C5(this, dataEncryptedContent_2, onError_1, onPlainText_0,
                                                                               cKeyName_3), onError_1);
            }
        }
Exemple #18
0
            public Anonymous_C4(Consumer paramouter_Consumer, Name cKeyName_0,
						net.named_data.jndn.encrypt.EncryptError.OnError  onError_1, Consumer.OnPlainText  onPlainText_2,
						EncryptedContent dataEncryptedContent_3)
            {
                this.cKeyName = cKeyName_0;
                    this.onError = onError_1;
                    this.onPlainText = onPlainText_2;
                    this.dataEncryptedContent = dataEncryptedContent_3;
                    this.outer_Consumer = paramouter_Consumer;
            }
        public void testSetterGetter()
        {
            EncryptedContent content = new EncryptedContent();
            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.NONE, content.getAlgorithmType());
            Assert.AssertEquals(true, content.getPayload().isNull());
            Assert.AssertEquals(true, content.getInitialVector().isNull());
            Assert.AssertEquals(net.named_data.jndn.KeyLocatorType.NONE, content.getKeyLocator().getType());

            content.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);
            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep, content.getAlgorithmType());
            Assert.AssertEquals(true, content.getPayload().isNull());
            Assert.AssertEquals(true, content.getInitialVector().isNull());
            Assert.AssertEquals(net.named_data.jndn.KeyLocatorType.NONE, content.getKeyLocator().getType());

            KeyLocator keyLocator = new KeyLocator();
            keyLocator.setType(net.named_data.jndn.KeyLocatorType.KEYNAME);
            keyLocator.getKeyName().set("/test/key/locator");
            content.setKeyLocator(keyLocator);
            Assert.AssertTrue(content.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE);
            Assert.AssertTrue(content.getKeyLocator().getKeyName()
                    .equals(new Name("/test/key/locator")));
            Assert.AssertEquals(true, content.getPayload().isNull());
            Assert.AssertEquals(true, content.getInitialVector().isNull());

            content.setPayload(new Blob(message, false));
            Assert.AssertTrue(content.getPayload().equals(new Blob(message, false)));

            content.setInitialVector(new Blob(iv, false));
            Assert.AssertTrue(content.getInitialVector().equals(new Blob(iv, false)));

            Blob encoded = content.wireEncode();
            Blob contentBlob = new Blob(encrypted, false);
            Assert.AssertTrue(contentBlob.equals(encoded));
        }
        public void testDecodingError()
        {
            EncryptedContent encryptedContent = new EncryptedContent();

            Blob errorBlob1 = new Blob(toBuffer(new int[] {
                    0x1f,
                    0x30, // Wrong EncryptedContent (0x82, 0x24)
                    0x1c,
                    0x16, // KeyLocator
                    0x07,
                    0x14, // Name
                    0x08, 0x04, 0x74, 0x65, 0x73, 0x74, 0x08, 0x03, 0x6b, 0x65,
                    0x79, 0x08, 0x07, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x6f, 0x72,
                    0x83,
                    0x01, // EncryptedAlgorithm
                    0x00, 0x85,
                    0x0a, // InitialVector
                    0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x62, 0x69, 0x74, 0x73,
                    0x84, 0x07, // EncryptedPayload
                    0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74 }), false);
            try {
                encryptedContent.wireDecode(errorBlob1);
                Assert.Fail("wireDecode did not throw an exception");
            } catch (EncodingException ex) {
            } catch (Exception ex_0) {
                Assert.Fail("wireDecode did not throw EncodingException");
            }

            Blob errorBlob2 = new Blob(toBuffer(new int[] {
                    0x82,
                    0x30, // EncryptedContent
                    0x1d,
                    0x16, // Wrong KeyLocator (0x1c, 0x16)
                    0x07,
                    0x14, // Name
                    0x08, 0x04, 0x74, 0x65, 0x73, 0x74, 0x08, 0x03, 0x6b, 0x65,
                    0x79, 0x08, 0x07, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x6f, 0x72,
                    0x83,
                    0x01, // EncryptedAlgorithm
                    0x00, 0x85,
                    0x0a, // InitialVector
                    0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x62, 0x69, 0x74, 0x73,
                    0x84, 0x07, // EncryptedPayload
                    0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74 }), false);
            try {
                encryptedContent.wireDecode(errorBlob2);
                Assert.Fail("wireDecode did not throw an exception");
            } catch (EncodingException ex_1) {
            } catch (Exception ex_2) {
                Assert.Fail("wireDecode did not throw EncodingException");
            }

            Blob errorBlob3 = new Blob(toBuffer(new int[] {
                    0x82,
                    0x30, // EncryptedContent
                    0x1c,
                    0x16, // KeyLocator
                    0x07,
                    0x14, // Name
                    0x08, 0x04, 0x74, 0x65, 0x73, 0x74, 0x08, 0x03, 0x6b, 0x65,
                    0x79, 0x08, 0x07, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x6f, 0x72,
                    0x1d,
                    0x01, // Wrong EncryptedAlgorithm (0x83, 0x01)
                    0x00, 0x85,
                    0x0a, // InitialVector
                    0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x62, 0x69, 0x74, 0x73,
                    0x84, 0x07, // EncryptedPayload
                    0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74 }), false);
            try {
                encryptedContent.wireDecode(errorBlob3);
                Assert.Fail("wireDecode did not throw an exception");
            } catch (EncodingException ex_3) {
            } catch (Exception ex_4) {
                Assert.Fail("wireDecode did not throw EncodingException");
            }

            Blob errorBlob4 = new Blob(toBuffer(new int[] { 0x82,
                    0x30, // EncryptedContent
                    0x1c,
                    0x16, // KeyLocator
                    0x07,
                    0x14, // Name
                    0x08, 0x04, 0x74, 0x65, 0x73,
                    0x74, // 'test'
                    0x08, 0x03, 0x6b, 0x65,
                    0x79, // 'key'
                    0x08, 0x07, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x6f,
                    0x72, // 'locator'
                    0x83,
                    0x01, // EncryptedAlgorithm
                    0x00, 0x1f,
                    0x0a, // InitialVector (0x84, 0x0a)
                    0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x62, 0x69, 0x74, 0x73,
                    0x84, 0x07, // EncryptedPayload
                    0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74 }), false);
            try {
                encryptedContent.wireDecode(errorBlob4);
                Assert.Fail("wireDecode did not throw an exception");
            } catch (EncodingException ex_5) {
            } catch (Exception ex_6) {
                Assert.Fail("wireDecode did not throw EncodingException");
            }

            Blob errorBlob5 = new Blob(toBuffer(new int[] { 0x82,
                    0x30, // EncryptedContent
                    0x1c,
                    0x16, // KeyLocator
                    0x07,
                    0x14, // Name
                    0x08, 0x04, 0x74, 0x65, 0x73,
                    0x74, // 'test'
                    0x08, 0x03, 0x6b, 0x65,
                    0x79, // 'key'
                    0x08, 0x07, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x6f,
                    0x72, // 'locator'
                    0x83,
                    0x01, // EncryptedAlgorithm
                    0x00, 0x85,
                    0x0a, // InitialVector
                    0x72, 0x61, 0x6e, 0x64, 0x6f, 0x6d, 0x62, 0x69, 0x74, 0x73,
                    0x21, 0x07, // EncryptedPayload (0x85, 0x07)
                    0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74 }), false);
            try {
                encryptedContent.wireDecode(errorBlob5);
                Assert.Fail("wireDecode did not throw an exception");
            } catch (EncodingException ex_7) {
            } catch (Exception ex_8) {
                Assert.Fail("wireDecode did not throw EncodingException");
            }

            Blob errorBlob6 = new Blob(toBuffer(new int[] { 0x82, 0x00 // Empty EncryptedContent
                    }), false);
            try {
                encryptedContent.wireDecode(errorBlob6);
                Assert.Fail("wireDecode did not throw an exception");
            } catch (EncodingException ex_9) {
            } catch (Exception ex_10) {
                Assert.Fail("wireDecode did not throw EncodingException");
            }
        }
Exemple #21
0
        /// <summary>
        /// Encrypt the payload using the symmetric key according to params, and return
        /// an EncryptedContent.
        /// </summary>
        ///
        /// <param name="payload">The data to encrypt.</param>
        /// <param name="key">The key value.</param>
        /// <param name="keyName">The key name for the EncryptedContent key locator.</param>
        /// <param name="params">The parameters for encryption.</param>
        /// <returns>A new EncryptedContent.</returns>
        private static EncryptedContent encryptSymmetric(Blob payload, Blob key,
				Name keyName, EncryptParams paras)
        {
            EncryptAlgorithmType algorithmType = paras.getAlgorithmType();
            Blob initialVector = paras.getInitialVector();
            KeyLocator keyLocator = new KeyLocator();
            keyLocator.setType(net.named_data.jndn.KeyLocatorType.KEYNAME);
            keyLocator.setKeyName(keyName);

            if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc
                    || algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesEcb) {
                if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc) {
                    if (initialVector.size() != net.named_data.jndn.encrypt.algo.AesAlgorithm.BLOCK_SIZE)
                        throw new Exception("incorrect initial vector size");
                }

                Blob encryptedPayload = net.named_data.jndn.encrypt.algo.AesAlgorithm.encrypt(key, payload, paras);

                EncryptedContent result = new EncryptedContent();
                result.setAlgorithmType(algorithmType);
                result.setKeyLocator(keyLocator);
                result.setPayload(encryptedPayload);
                result.setInitialVector(initialVector);
                return result;
            } else
                throw new Exception("Unsupported encryption method");
        }
        public void testConstructor()
        {
            // Check default settings.
            EncryptedContent content = new EncryptedContent();
            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.NONE, content.getAlgorithmType());
            Assert.AssertEquals(true, content.getPayload().isNull());
            Assert.AssertEquals(true, content.getInitialVector().isNull());
            Assert.AssertEquals(net.named_data.jndn.KeyLocatorType.NONE, content.getKeyLocator().getType());

            // Check an encrypted content with IV.
            KeyLocator keyLocator = new KeyLocator();
            keyLocator.setType(net.named_data.jndn.KeyLocatorType.KEYNAME);
            keyLocator.getKeyName().set("/test/key/locator");
            EncryptedContent rsaOaepContent = new EncryptedContent();
            rsaOaepContent.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep)
                    .setKeyLocator(keyLocator).setPayload(new Blob(message, false))
                    .setInitialVector(new Blob(iv, false));

            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep,
                    rsaOaepContent.getAlgorithmType());
            Assert.AssertTrue(rsaOaepContent.getPayload().equals(new Blob(message, false)));
            Assert.AssertTrue(rsaOaepContent.getInitialVector()
                    .equals(new Blob(iv, false)));
            Assert.AssertTrue(rsaOaepContent.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE);
            Assert.AssertTrue(rsaOaepContent.getKeyLocator().getKeyName()
                    .equals(new Name("/test/key/locator")));

            // Encoding.
            Blob encryptedBlob = new Blob(encrypted, false);
            Blob encoded = rsaOaepContent.wireEncode();

            Assert.AssertTrue(encryptedBlob.equals(encoded));

            // Decoding.
            EncryptedContent rsaOaepContent2 = new EncryptedContent();
            rsaOaepContent2.wireDecode(encryptedBlob);
            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep,
                    rsaOaepContent2.getAlgorithmType());
            Assert.AssertTrue(rsaOaepContent2.getPayload()
                    .equals(new Blob(message, false)));
            Assert.AssertTrue(rsaOaepContent2.getInitialVector().equals(
                    new Blob(iv, false)));
            Assert.AssertTrue(rsaOaepContent2.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE);
            Assert.AssertTrue(rsaOaepContent2.getKeyLocator().getKeyName()
                    .equals(new Name("/test/key/locator")));

            // Check the no IV case.
            EncryptedContent rsaOaepContentNoIv = new EncryptedContent();
            rsaOaepContentNoIv.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep)
                    .setKeyLocator(keyLocator).setPayload(new Blob(message, false));
            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep,
                    rsaOaepContentNoIv.getAlgorithmType());
            Assert.AssertTrue(rsaOaepContentNoIv.getPayload().equals(
                    new Blob(message, false)));
            Assert.AssertTrue(rsaOaepContentNoIv.getInitialVector().isNull());
            Assert.AssertTrue(rsaOaepContentNoIv.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE);
            Assert.AssertTrue(rsaOaepContentNoIv.getKeyLocator().getKeyName()
                    .equals(new Name("/test/key/locator")));

            // Encoding.
            Blob encryptedBlob2 = new Blob(encryptedNoIv, false);
            Blob encodedNoIV = rsaOaepContentNoIv.wireEncode();
            Assert.AssertTrue(encryptedBlob2.equals(encodedNoIV));

            // Decoding.
            EncryptedContent rsaOaepContentNoIv2 = new EncryptedContent();
            rsaOaepContentNoIv2.wireDecode(encryptedBlob2);
            Assert.AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep,
                    rsaOaepContentNoIv2.getAlgorithmType());
            Assert.AssertTrue(rsaOaepContentNoIv2.getPayload().equals(
                    new Blob(message, false)));
            Assert.AssertTrue(rsaOaepContentNoIv2.getInitialVector().isNull());
            Assert.AssertTrue(rsaOaepContentNoIv2.getKeyLocator().getType() != net.named_data.jndn.KeyLocatorType.NONE);
            Assert.AssertTrue(rsaOaepContentNoIv2.getKeyLocator().getKeyName()
                    .equals(new Name("/test/key/locator")));
        }
Exemple #23
0
        /// <summary>
        /// Decode input as an EncryptedContent and set the fields of the
        /// encryptedContent object. Your derived class should override.
        /// </summary>
        ///
        /// <param name="encryptedContent"></param>
        /// <param name="input"></param>
        /// <param name="copy">unchanged while the Blob values are used.</param>
        /// <exception cref="EncodingException">For invalid encoding.</exception>
        /// <exception cref="System.NotSupportedException">for unimplemented if the derivedclass does not override.</exception>
        public virtual void decodeEncryptedContent(EncryptedContent encryptedContent,
				ByteBuffer input, bool copy)
        {
            throw new NotSupportedException(
                    "decodeEncryptedContent is not implemented");
        }
Exemple #24
0
        /// <summary>
        /// Encrypt the payload using the asymmetric key according to params, and
        /// return an EncryptedContent.
        /// </summary>
        ///
        /// <param name="payload"></param>
        /// <param name="key">The key value.</param>
        /// <param name="keyName">The key name for the EncryptedContent key locator.</param>
        /// <param name="params">The parameters for encryption.</param>
        /// <returns>A new EncryptedContent.</returns>
        private static EncryptedContent encryptAsymmetric(Blob payload, Blob key,
				Name keyName, EncryptParams paras)
        {
            EncryptAlgorithmType algorithmType = paras.getAlgorithmType();
            KeyLocator keyLocator = new KeyLocator();
            keyLocator.setType(net.named_data.jndn.KeyLocatorType.KEYNAME);
            keyLocator.setKeyName(keyName);

            if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaPkcs
                    || algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep) {
                Blob encryptedPayload = net.named_data.jndn.encrypt.algo.RsaAlgorithm.encrypt(key, payload, paras);

                EncryptedContent result = new EncryptedContent();
                result.setAlgorithmType(algorithmType);
                result.setKeyLocator(keyLocator);
                result.setPayload(encryptedPayload);
                return result;
            } else
                throw new Exception("Unsupported encryption method");
        }
Exemple #25
0
        /// <summary>
        /// Decrypt dKeyData.
        /// </summary>
        ///
        /// <param name="dKeyData">The D-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 decryptDKey(Data dKeyData, Consumer.OnPlainText onPlainText_0,
                                  net.named_data.jndn.encrypt.EncryptError.OnError onError_1)
        {
            // Get the encrypted content.
            Blob dataContent = dKeyData.getContent();

            // Process the nonce.
            // dataContent is a sequence of the two EncryptedContent.
            EncryptedContent encryptedNonce = new EncryptedContent();

            try {
                encryptedNonce.wireDecode(dataContent);
            } 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 consumerKeyName = encryptedNonce.getKeyLocator().getKeyName();

            // Get consumer decryption key.
            Blob consumerKeyBlob;

            try {
                consumerKeyBlob = getDecryptionKey(consumerKeyName);
            } catch (ConsumerDb.Error ex_2) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.NoDecryptKey,
                                      "Database error: " + ex_2.Message);
                } catch (Exception exception_3) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_3);
                }
                return;
            }
            if (consumerKeyBlob.size() == 0)
            {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.NoDecryptKey,
                                      "The desired consumer decryption key in not in the database");
                } catch (Exception exception_4) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_4);
                }
                return;
            }

            // Process the D-KEY.
            // Use the size of encryptedNonce to find the start of encryptedPayload.
            ByteBuffer encryptedPayloadBuffer = dataContent.buf().duplicate();

            encryptedPayloadBuffer.position(encryptedNonce.wireEncode().size());
            Blob encryptedPayloadBlob_5 = new Blob(encryptedPayloadBuffer,
                                                   false);

            if (encryptedPayloadBlob_5.size() == 0)
            {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                                      "The data packet does not satisfy the D-KEY packet format");
                } catch (Exception ex_6) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex_6);
                }
                return;
            }

            // Decrypt the D-KEY.
            Consumer.OnPlainText callerOnPlainText_7 = onPlainText_0;
            decrypt(encryptedNonce, consumerKeyBlob, new Consumer.Anonymous_C3(callerOnPlainText_7, onError_1, encryptedPayloadBlob_5), onError_1);
        }
Exemple #26
0
            public Anonymous_C2(Consumer paramouter_Consumer, net.named_data.jndn.encrypt.EncryptError.OnError  onError_0,
						Consumer.OnPlainText  onPlainText_1, Name dKeyName_2,
						EncryptedContent cKeyEncryptedContent_3)
            {
                this.onError = onError_0;
                    this.onPlainText = onPlainText_1;
                    this.dKeyName = dKeyName_2;
                    this.cKeyEncryptedContent = cKeyEncryptedContent_3;
                    this.outer_Consumer = paramouter_Consumer;
            }
        /// <summary>
        /// Encode the EncryptedContent in NDN-TLV and return the encoding.
        /// </summary>
        ///
        /// <param name="encryptedContent">The EncryptedContent object to encode.</param>
        /// <returns>A Blob containing the encoding.</returns>
        public override Blob encodeEncryptedContent(EncryptedContent encryptedContent)
        {
            TlvEncoder encoder = new TlvEncoder(256);
            int saveLength = encoder.getLength();

            // Encode backwards.
            encoder.writeBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_EncryptedPayload, encryptedContent
                    .getPayload().buf());
            encoder.writeOptionalBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_InitialVector,
                    encryptedContent.getInitialVector().buf());
            // Assume the algorithmType value is the same as the TLV type.
            encoder.writeNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_EncryptionAlgorithm,
                    encryptedContent.getAlgorithmType().getNumericType());
            Tlv0_2WireFormat.encodeKeyLocator(net.named_data.jndn.encoding.tlv.Tlv.KeyLocator,
                    encryptedContent.getKeyLocator(), encoder);

            encoder.writeTypeAndLength(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_EncryptedContent,
                    encoder.getLength() - saveLength);

            return new Blob(encoder.getOutput(), false);
        }
        public void testContentAsymmetricEncryptSmall()
        {
            /* foreach */
            foreach (TestEncryptor.AsymmetricEncryptInput  input  in  encryptorRsaTestInputs) {
                Blob rawContent = new Blob(toBuffer(new int[] { 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 = 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, rawContent, keyName, eKey,
                        encryptParams);

                Assert.AssertEquals(input.testName(), new Name("/FOR").append(keyName),
                        data.getName());

                EncryptedContent extractContent = new EncryptedContent();
                extractContent.wireDecode(data.getContent());
                Assert.AssertEquals(input.testName(), keyName, extractContent
                        .getKeyLocator().getKeyName());
                Assert.AssertEquals(input.testName(), 0, extractContent.getInitialVector()
                        .size());
                Assert.AssertEquals(input.testName(), input.type(),
                        extractContent.getAlgorithmType());

                Blob recovered = extractContent.getPayload();
                Blob decrypted = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(dKey, recovered,
                        encryptParams);
                Assert.AssertTrue(input.testName(), rawContent.equals(decrypted));
            }
        }
        /// <summary>
        /// Decode input as a EncryptedContent in NDN-TLV and set the fields of the
        /// encryptedContent object.
        /// </summary>
        ///
        /// <param name="encryptedContent"></param>
        /// <param name="input"></param>
        /// <param name="copy">unchanged while the Blob values are used.</param>
        /// <exception cref="EncodingException">For invalid encoding</exception>
        public override void decodeEncryptedContent(EncryptedContent encryptedContent,
				ByteBuffer input, bool copy)
        {
            TlvDecoder decoder = new TlvDecoder(input);
            int endOffset = decoder
                    .readNestedTlvsStart(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_EncryptedContent);

            Tlv0_2WireFormat.decodeKeyLocator(net.named_data.jndn.encoding.tlv.Tlv.KeyLocator,
                    encryptedContent.getKeyLocator(), decoder, copy);

            int algorithmType = (int) decoder
                    .readNonNegativeIntegerTlv(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_EncryptionAlgorithm);
            if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesEcb.getNumericType())
                encryptedContent.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesEcb);
            else if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc.getNumericType())
                encryptedContent.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc);
            else if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaPkcs.getNumericType())
                encryptedContent.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaPkcs);
            else if (algorithmType == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep.getNumericType())
                encryptedContent.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);
            else
                throw new EncodingException(
                        "Unrecognized EncryptionAlgorithm code " + algorithmType);

            encryptedContent.setInitialVector(new Blob(decoder.readOptionalBlobTlv(
                    net.named_data.jndn.encoding.tlv.Tlv.Encrypt_InitialVector, endOffset), copy));
            encryptedContent.setPayload(new Blob(decoder
                    .readBlobTlv(net.named_data.jndn.encoding.tlv.Tlv.Encrypt_EncryptedPayload), copy));

            decoder.finishNestedTlvs(endOffset);
        }
Exemple #30
0
        /// <summary>
        /// Decrypt encryptedContent using keyBits.
        /// </summary>
        ///
        /// <param name="encryptedContent">The EncryptedContent to decrypt.</param>
        /// <param name="keyBits">The key value.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        internal static void decrypt(EncryptedContent encryptedContent,
				Blob keyBits, Consumer.OnPlainText  onPlainText_0, net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            Blob payload = encryptedContent.getPayload();

            if (encryptedContent.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc) {
                // Prepare the parameters.
                EncryptParams decryptParams = new EncryptParams(
                        net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc);
                decryptParams.setInitialVector(encryptedContent.getInitialVector());

                // Decrypt the content.
                Blob content;
                try {
                    content = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(keyBits, payload, decryptParams);
                } catch (Exception 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;
                }
                try {
                    onPlainText_0.onPlainText(content);
                } catch (Exception ex_2) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onPlainText", ex_2);
                }
            } else if (encryptedContent.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep) {
                // Prepare the parameters.
                EncryptParams decryptParams_3 = new EncryptParams(
                        net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);

                // Decrypt the content.
                Blob content_4;
                try {
                    content_4 = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(keyBits, payload, decryptParams_3);
                } catch (Exception ex_5) {
                    try {
                        onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                                ex_5.Message);
                    } catch (Exception exception_6) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_6);
                    }
                    return;
                }
                try {
                    onPlainText_0.onPlainText(content_4);
                } catch (Exception ex_7) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onPlainText", ex_7);
                }
            } else {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.UnsupportedEncryptionScheme,
                            encryptedContent.getAlgorithmType().toString());
                } catch (Exception ex_8) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex_8);
                }
            }
        }
Exemple #31
0
        /// <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);
                    }
                }
            }
        }
Exemple #32
0
        /// <summary>
        /// Decrypt encryptedContent using keyBits.
        /// </summary>
        ///
        /// <param name="encryptedContent">The EncryptedContent to decrypt.</param>
        /// <param name="keyBits">The key value.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        static internal void decrypt(EncryptedContent encryptedContent,
                                     Blob keyBits, Consumer.OnPlainText onPlainText_0, net.named_data.jndn.encrypt.EncryptError.OnError onError_1)
        {
            Blob payload = encryptedContent.getPayload();

            if (encryptedContent.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc)
            {
                // Prepare the parameters.
                EncryptParams decryptParams = new EncryptParams(
                    net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc);
                decryptParams.setInitialVector(encryptedContent.getInitialVector());

                // Decrypt the content.
                Blob content;
                try {
                    content = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(keyBits, payload, decryptParams);
                } catch (Exception 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;
                }
                try {
                    onPlainText_0.onPlainText(content);
                } catch (Exception ex_2) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onPlainText", ex_2);
                }
            }
            else if (encryptedContent.getAlgorithmType() == net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep)
            {
                // Prepare the parameters.
                EncryptParams decryptParams_3 = new EncryptParams(
                    net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);

                // Decrypt the content.
                Blob content_4;
                try {
                    content_4 = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(keyBits, payload, decryptParams_3);
                } catch (Exception ex_5) {
                    try {
                        onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                                          ex_5.Message);
                    } catch (Exception exception_6) {
                        logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_6);
                    }
                    return;
                }
                try {
                    onPlainText_0.onPlainText(content_4);
                } catch (Exception ex_7) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onPlainText", ex_7);
                }
            }
            else
            {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.UnsupportedEncryptionScheme, ""
                                      + encryptedContent.getAlgorithmType());
                } catch (Exception ex_8) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex_8);
                }
            }
        }
Exemple #33
0
        /// <summary>
        /// Decrypt dKeyData.
        /// </summary>
        ///
        /// <param name="dKeyData">The D-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 decryptDKey(Data dKeyData, Consumer.OnPlainText  onPlainText_0,
				net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            // Get the encrypted content.
            Blob dataContent = dKeyData.getContent();

            // Process the nonce.
            // dataContent is a sequence of the two EncryptedContent.
            EncryptedContent encryptedNonce = new EncryptedContent();
            try {
                encryptedNonce.wireDecode(dataContent);
            } 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 consumerKeyName = encryptedNonce.getKeyLocator().getKeyName();

            // Get consumer decryption key.
            Blob consumerKeyBlob;
            try {
                consumerKeyBlob = getDecryptionKey(consumerKeyName);
            } catch (ConsumerDb.Error ex_2) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.NoDecryptKey,
                            "Database error: " + ex_2.Message);
                } catch (Exception exception_3) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_3);
                }
                return;
            }
            if (consumerKeyBlob.size() == 0) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.NoDecryptKey,
                            "The desired consumer decryption key in not in the database");
                } catch (Exception exception_4) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", exception_4);
                }
                return;
            }

            // Process the D-KEY.
            // Use the size of encryptedNonce to find the start of encryptedPayload.
            ByteBuffer encryptedPayloadBuffer = dataContent.buf().duplicate();
            encryptedPayloadBuffer.position(encryptedNonce.wireEncode().size());
            Blob encryptedPayloadBlob_5 = new Blob(encryptedPayloadBuffer,
                    false);
            if (encryptedPayloadBlob_5.size() == 0) {
                try {
                    onError_1.onError(net.named_data.jndn.encrypt.EncryptError.ErrorCode.InvalidEncryptedFormat,
                            "The data packet does not satisfy the D-KEY packet format");
                } catch (Exception ex_6) {
                    logger_.log(ILOG.J2CsMapping.Util.Logging.Level.SEVERE, "Error in onError", ex_6);
                }
                return;
            }

            // Decrypt the D-KEY.
            Consumer.OnPlainText  callerOnPlainText_7 = onPlainText_0;
            decrypt(encryptedNonce, consumerKeyBlob, new Consumer.Anonymous_C0 (callerOnPlainText_7, encryptedPayloadBlob_5, onError_1), onError_1);
        }
        public void testContentSymmetricEncrypt()
        {
            /* foreach */
            foreach (TestEncryptor.SymmetricEncryptInput  input  in  encryptorAesTestInputs) {
                Data data = new Data();
                net.named_data.jndn.encrypt.algo.Encryptor.encryptData(data, input.plainText(), input.keyName(),
                        input.key(), input.encryptParams());

                Assert.AssertEquals(input.testName(),
                        new Name("/FOR").append(input.keyName()), data.getName());

                Assert.AssertTrue(input.testName(),
                        input.encryptedContent().equals(data.getContent()));

                EncryptedContent content = new EncryptedContent();
                content.wireDecode(data.getContent());
                Blob decryptedOutput = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(input.key(),
                        content.getPayload(), input.encryptParams());

                Assert.AssertTrue(input.testName(),
                        input.plainText().equals(decryptedOutput));
            }
        }
Exemple #35
0
        /// <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 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));
            }
        }
Exemple #37
0
        /// <summary>
        /// Decode encryptedBlob as an EncryptedContent and decrypt using keyBits.
        /// </summary>
        ///
        /// <param name="encryptedBlob">The encoded EncryptedContent to decrypt.</param>
        /// <param name="keyBits">The key value.</param>
        /// <param name="onPlainText_0"></param>
        /// <param name="onError_1">This calls onError.onError(errorCode, message) for an error.</param>
        private static void decrypt(Blob encryptedBlob, Blob keyBits,
				Consumer.OnPlainText  onPlainText_0, net.named_data.jndn.encrypt.EncryptError.OnError  onError_1)
        {
            EncryptedContent encryptedContent = new EncryptedContent();
            try {
                encryptedContent.wireDecode(encryptedBlob);
            } 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;
            }

            decrypt(encryptedContent, keyBits, onPlainText_0, onError_1);
        }
Exemple #38
0
        /// <summary>
        /// Decode input as an EncryptedContent and set the fields of the
        /// encryptedContent object. Copy from the input when making new Blob values.
        /// Your derived class should override.
        /// </summary>
        ///
        /// <param name="encryptedContent"></param>
        /// <param name="input"></param>
        /// <exception cref="EncodingException">For invalid encoding.</exception>
        /// <exception cref="System.NotSupportedException">for unimplemented if the derivedclass does not override.</exception>
        public void decodeEncryptedContent(EncryptedContent encryptedContent,
				ByteBuffer input)
        {
            decodeEncryptedContent(encryptedContent, input, true);
        }
        public void testGetGroupKey()
        {
            // Create the group manager.
            GroupManager manager = new GroupManager(new Name("Alice"), new Name(
                    "data_type"), new Sqlite3GroupManagerDb(
                    System.IO.Path.GetFullPath(groupKeyDatabaseFilePath.Name)), 1024, 1, keyChain);
            setManager(manager);

            // Get the data list from the group manager.
            double timePoint1 = net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20150825T093000");
            IList result = manager.getGroupKey(timePoint1);

            AssertEquals(4, result.Count);

            // The first data packet contains the group's encryption key (public key).
            Data data = (Data) result[0];
            AssertEquals(
                    "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
                    data.getName().toUri());
            EncryptKey groupEKey = new EncryptKey(data.getContent());

            // Get the second data packet and decrypt.
            data = (Data) result[1];
            AssertEquals(
                    "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberA/ksk-123",
                    data.getName().toUri());

            /////////////////////////////////////////////////////// Start decryption.
            Blob dataContent = data.getContent();

            // Get the nonce key.
            // dataContent is a sequence of the two EncryptedContent.
            EncryptedContent encryptedNonce = new EncryptedContent();
            encryptedNonce.wireDecode(dataContent);
            AssertEquals(0, encryptedNonce.getInitialVector().size());
            AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep,
                    encryptedNonce.getAlgorithmType());

            EncryptParams decryptParams = new EncryptParams(
                    net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);
            Blob blobNonce = encryptedNonce.getPayload();
            Blob nonce = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(decryptKeyBlob, blobNonce,
                    decryptParams);

            // Get the payload.
            // Use the size of encryptedNonce to find the start of encryptedPayload.
            ByteBuffer payloadContent = dataContent.buf().duplicate();
            payloadContent.position(encryptedNonce.wireEncode().size());
            EncryptedContent encryptedPayload = new EncryptedContent();
            encryptedPayload.wireDecode(payloadContent);
            AssertEquals(16, encryptedPayload.getInitialVector().size());
            AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc,
                    encryptedPayload.getAlgorithmType());

            decryptParams.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc);
            decryptParams.setInitialVector(encryptedPayload.getInitialVector());
            Blob blobPayload = encryptedPayload.getPayload();
            Blob largePayload = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(nonce, blobPayload,
                    decryptParams);

            // Get the group D-KEY.
            DecryptKey groupDKey = new DecryptKey(largePayload);

            /////////////////////////////////////////////////////// End decryption.

            // Check the D-KEY.
            EncryptKey derivedGroupEKey = net.named_data.jndn.encrypt.algo.RsaAlgorithm.deriveEncryptKey(groupDKey
                    .getKeyBits());
            AssertTrue(groupEKey.getKeyBits().equals(derivedGroupEKey.getKeyBits()));

            // Check the third data packet.
            data = (Data) result[2];
            AssertEquals(
                    "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberB/ksk-123",
                    data.getName().toUri());

            // Check the fourth data packet.
            data = (Data) result[3];
            AssertEquals(
                    "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberC/ksk-123",
                    data.getName().toUri());

            // Check invalid time stamps for getting the group key.
            double timePoint2 = net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20150826T083000");
            AssertEquals(0, manager.getGroupKey(timePoint2).Count);

            double timePoint3 = net.named_data.jndn.tests.unit_tests.UnitTestsCommon.fromIsoString("20150827T023000");
            AssertEquals(0, manager.getGroupKey(timePoint3).Count);
        }
Exemple #40
0
 /// <summary>
 /// Encode the EncryptedContent and return the encoding. Your derived class
 /// should override.
 /// </summary>
 ///
 /// <param name="encryptedContent">The EncryptedContent object to encode.</param>
 /// <returns>A Blob containing the encoding.</returns>
 /// <exception cref="System.NotSupportedException">for unimplemented if the derivedclass does not override.</exception>
 public virtual Blob encodeEncryptedContent(EncryptedContent encryptedContent)
 {
     throw new NotSupportedException(
             "encodeEncryptedContent is not implemented");
 }
        public void testCreateDKeyData()
        {
            // Create the group manager.
            GroupManager manager = new GroupManager(new Name("Alice"), new Name(
                    "data_type"), new Sqlite3GroupManagerDb(
                    System.IO.Path.GetFullPath(dKeyDatabaseFilePath.Name)), 2048, 1, keyChain);

            Blob newCertificateBlob = certificate.wireEncode();
            IdentityCertificate newCertificate = new IdentityCertificate();
            newCertificate.wireDecode(newCertificateBlob);

            // Encrypt the D-KEY.
            Data data = friendAccess.createDKeyData(manager, "20150825T000000",
                    "20150827T000000", new Name("/ndn/memberA/KEY"),
                    decryptKeyBlob, newCertificate.getPublicKeyInfo().getKeyDer());

            // Verify the encrypted D-KEY.
            Blob dataContent = data.getContent();

            // Get the nonce key.
            // dataContent is a sequence of the two EncryptedContent.
            EncryptedContent encryptedNonce = new EncryptedContent();
            encryptedNonce.wireDecode(dataContent);
            AssertEquals(0, encryptedNonce.getInitialVector().size());
            AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep,
                    encryptedNonce.getAlgorithmType());

            Blob blobNonce = encryptedNonce.getPayload();
            EncryptParams decryptParams = new EncryptParams(
                    net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.RsaOaep);
            Blob nonce = net.named_data.jndn.encrypt.algo.RsaAlgorithm.decrypt(decryptKeyBlob, blobNonce,
                    decryptParams);

            // Get the D-KEY.
            // Use the size of encryptedNonce to find the start of encryptedPayload.
            ByteBuffer payloadContent = dataContent.buf().duplicate();
            payloadContent.position(encryptedNonce.wireEncode().size());
            EncryptedContent encryptedPayload = new EncryptedContent();
            encryptedPayload.wireDecode(payloadContent);
            AssertEquals(16, encryptedPayload.getInitialVector().size());
            AssertEquals(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc,
                    encryptedPayload.getAlgorithmType());

            decryptParams.setAlgorithmType(net.named_data.jndn.encrypt.algo.EncryptAlgorithmType.AesCbc);
            decryptParams.setInitialVector(encryptedPayload.getInitialVector());
            Blob blobPayload = encryptedPayload.getPayload();
            Blob largePayload = net.named_data.jndn.encrypt.algo.AesAlgorithm.decrypt(nonce, blobPayload,
                    decryptParams);

            AssertTrue(largePayload.equals(decryptKeyBlob));
        }