private void TestEncryptProcessArguments(PlainDataContainer pdc)
        {
            PlainFileKey         pfk       = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);
            FileEncryptionCipher encCipher = Crypto.CreateFileEncryptionCipher(pfk);

            encCipher.ProcessBytes(pdc);
        }
        private EncryptedFileKey TestEncryptFileKey(byte[] plainFileKeyResource, byte[] userPublicKeyResource)
        {
            PlainFileKey  pfk = TestUtilities.ReadTestResource <PlainFileKey>(plainFileKeyResource);
            UserPublicKey upk = TestUtilities.ReadTestResource <UserPublicKey>(userPublicKeyResource);

            return(Crypto.EncryptFileKey(pfk, upk));
        }
        public void TestEncryptMultiBlock_Success()
        {
            PlainFileKey pfk = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);

            byte[] ft  = Convert.FromBase64String(pfk.Tag);
            byte[] pfc = Convert.FromBase64String(TestResources.plain_file);
            byte[] efc = Convert.FromBase64String(TestResources.enc_file);

            FileEncryptionCipher encCipher = Crypto.CreateFileEncryptionCipher(pfk);

            using (MemoryStream output = new MemoryStream()) {
                using (MemoryStream input = new MemoryStream(pfc)) {
                    byte[] buffer = new byte[16];
                    int    bytesRead;
                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        byte[] blockBytes = new byte[bytesRead];
                        Array.Copy(buffer, blockBytes, bytesRead);
                        EncryptedDataContainer currentEdc = encCipher.ProcessBytes(new PlainDataContainer(blockBytes));
                        output.Write(currentEdc.Content, 0, currentEdc.Content.Length);
                    }
                }
                EncryptedDataContainer testEdc = encCipher.DoFinal();
                output.Write(testEdc.Content, 0, testEdc.Content.Length);

                byte[] testFt  = testEdc.Tag;
                byte[] testEfc = output.ToArray();

                CollectionAssert.AreEqual(efc, testEfc, "File content does not match!");
                CollectionAssert.AreEqual(ft, testFt, "File tag does not match!");
            }
        }
        /// <summary>
        /// Encrypts a file key.
        /// </summary>
        /// <param name="plainFileKey">The file key to encrypt.</param>
        /// <param name="userPublicKey">The public key which should be used for the encryption.</param>
        /// <returns>The encrypted file key.</returns>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the provided file key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided public key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error occured.</exception>
        public static EncryptedFileKey EncryptFileKey(PlainFileKey plainFileKey, UserPublicKey userPublicKey)
        {
            ValidatePlainFileKey(plainFileKey);
            ValidateUserPublicKey(userPublicKey);

            AsymmetricKeyParameter pubKey = ConvertPublicKey(userPublicKey.PublicKey);

            byte[] eFileKey;
            try {
                OaepEncoding engine = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null);
                engine.Init(true, pubKey);
                byte[] pFileKey = Convert.FromBase64String(plainFileKey.Key);
                eFileKey = engine.ProcessBlock(pFileKey, 0, pFileKey.Length);
            } catch (Exception e) {
                throw new CryptoException("Could not encrypt file key. Encryption failed.", e);
            }
            EncryptedFileKey encFileKey = new EncryptedFileKey()
            {
                Key     = Convert.ToBase64String(eFileKey),
                Iv      = plainFileKey.Iv,
                Tag     = plainFileKey.Tag,
                Version = plainFileKey.Version
            };

            return(encFileKey);
        }
        /// <summary>
        /// Decrypts a file key.
        /// </summary>
        /// <param name="encFileKey">The file key to decrypt.</param>
        /// <param name="userPrivateKey">The private key which should be used for the decryption.</param>
        /// <param name="password">The password which secures the private key.</param>
        /// <returns>The decrypted file key.</returns>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the provided encrypted file key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidKeyPairException">If the provided private key is invalid.</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidPasswordException">If the provided private key password is invalid</exception>
        /// <exception cref="Dracoon.Crypto.Sdk.CryptoException">If an unexpected error in the decryption occured.</exception>
        public static PlainFileKey DecryptFileKey(EncryptedFileKey encFileKey, UserPrivateKey userPrivateKey, string password)
        {
            ValidateEncryptedFileKey(encFileKey);
            ValidateUserPrivateKey(userPrivateKey);
            ValidatePassword(password);

            AsymmetricKeyParameter privateKey = DecryptPrivateKey(userPrivateKey.PrivateKey, password);

            byte[] dFileKey;
            try {
                OaepEncoding engine = new OaepEncoding(new RsaEngine(), new Sha256Digest(), new Sha1Digest(), null);
                engine.Init(false, privateKey);
                byte[] eFileKey = Convert.FromBase64String(encFileKey.Key);
                dFileKey = engine.ProcessBlock(eFileKey, 0, eFileKey.Length);
            } catch (InvalidCipherTextException e) {
                throw new CryptoException("Could not decrypt file key. Decryption failed.", e);
            }

            PlainFileKey plainFileKey = new PlainFileKey()
            {
                Key     = Convert.ToBase64String(dFileKey),
                Iv      = encFileKey.Iv,
                Tag     = encFileKey.Tag,
                Version = encFileKey.Version
            };

            return(plainFileKey);
        }
        private void TestDecryptDoFinalArguments(EncryptedDataContainer edc)
        {
            PlainFileKey         pfk       = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);
            FileDecryptionCipher decCipher = Crypto.CreateFileDecryptionCipher(pfk);

            decCipher.DoFinal(edc);
        }
        //[TestMethod()]
        public void TestEnDecryption()
        {
            PlainFileKey generatedFK = Crypto.GenerateFileKey();

            byte[] plainFileBytes = Encoding.UTF8.GetBytes("Dinge die ich jetzt testen will.");

            // Encrypt text
            PlainDataContainer     plainDC   = new PlainDataContainer(plainFileBytes);
            FileEncryptionCipher   encCipher = Crypto.CreateFileEncryptionCipher(generatedFK);
            EncryptedDataContainer encryptedResult;

            using (MemoryStream ms = new MemoryStream()) {
                EncryptedDataContainer encryptedDC = encCipher.ProcessBytes(plainDC);
                ms.Write(encryptedDC.Content, 0, encryptedDC.Content.Length);
                encryptedDC = encCipher.DoFinal();
                ms.Write(encryptedDC.Content, 0, encryptedDC.Content.Length);
                encryptedResult = new EncryptedDataContainer(ms.ToArray(), encryptedDC.Tag);
            }
            generatedFK.Tag = Convert.ToBase64String(encryptedResult.Tag);

            // Decrypt text
            FileDecryptionCipher decCipher = Crypto.CreateFileDecryptionCipher(generatedFK);
            PlainDataContainer   decryptedResult;

            using (MemoryStream ms = new MemoryStream()) {
                PlainDataContainer decryptedDC = decCipher.ProcessBytes(new EncryptedDataContainer(encryptedResult.Content, null));
                ms.Write(decryptedDC.Content, 0, decryptedDC.Content.Length);
                decryptedDC = decCipher.DoFinal(new EncryptedDataContainer(null, Convert.FromBase64String(generatedFK.Tag)));
                ms.Write(decryptedDC.Content, 0, decryptedDC.Content.Length);
                decryptedResult = new PlainDataContainer(ms.ToArray());
            }

            System.Diagnostics.Debug.WriteLine("Result: " + Encoding.UTF8.GetString(decryptedResult.Content));
        }
예제 #8
0
        private void HandlePendingMissingFileKeys(ApiMissingFileKeys missingFileKeys, UserPrivateKey thisUserPrivateKey)
        {
            if (missingFileKeys == null || missingFileKeys.Items.Count == 0)
            {
                return;
            }

            Dictionary <long, UserPublicKey> userPublicKeys         = UserMapper.ConvertApiUserIdPublicKeys(missingFileKeys.UserPublicKey);
            Dictionary <long, PlainFileKey>  plainFileKeys          = GeneratePlainFileKeyMap(missingFileKeys.FileKeys, thisUserPrivateKey);
            ApiSetUserFileKeysRequest        setUserFileKeysRequest = new ApiSetUserFileKeysRequest {
                Items = new List <ApiSetUserFileKey>(missingFileKeys.UserPublicKey.Count)
            };

            foreach (ApiUserIdFileId currentMissingFileKey in missingFileKeys.Items)
            {
                UserPublicKey currentUsersPublicKey = userPublicKeys[currentMissingFileKey.UserId];
                PlainFileKey  currentPlainFileKey   = plainFileKeys[currentMissingFileKey.FileId];

                EncryptedFileKey currentEncryptedFileKey = EncryptFileKey(currentPlainFileKey, currentUsersPublicKey, currentMissingFileKey.FileId);

                ApiSetUserFileKey newRequestEntry = new ApiSetUserFileKey {
                    FileId  = currentMissingFileKey.FileId,
                    UserId  = currentMissingFileKey.UserId,
                    FileKey = FileMapper.ToApiFileKey(currentEncryptedFileKey)
                };
                setUserFileKeysRequest.Items.Add(newRequestEntry);
            }

            IRestRequest restRequest = _client.Builder.PostMissingFileKeys(setUserFileKeysRequest);

            _client.Executor.DoSyncApiCall <VoidResponse>(restRequest, RequestType.PostMissingFileKeys);
        }
예제 #9
0
 private EncryptedFileKey EncryptFileKey(PlainFileKey plainFileKey)
 {
     try {
         return(Crypto.Sdk.Crypto.EncryptFileKey(plainFileKey, _userPublicKey));
     } catch (CryptoException ce) {
         string message = "Encryption of file key for upload " + ActionId + " failed!";
         DracoonClient.Log.Debug(LogTag, message);
         throw new DracoonCryptoException(CryptoErrorMapper.ParseCause(ce));
     }
 }
예제 #10
0
 /// <summary>
 /// Checks the file key for file encryption.
 /// </summary>
 /// <param name="fileKey">The file key to check.</param>
 /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException"/>
 private static void ValidatePlainFileKey(PlainFileKey fileKey)
 {
     if (fileKey == null)
     {
         throw new InvalidFileKeyException("File key cannot be null.");
     }
     if (fileKey.Version == null || !fileKey.Version.Equals(CryptoConstants.defaultVersion))
     {
         throw new InvalidFileKeyException("Unknown file key version.");
     }
 }
        public void TestDecryptFileKey_Success()
        {
            string       pw      = "Pass1234!";
            PlainFileKey pfk     = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);
            PlainFileKey testPfk = TestDecryptFileKey(TestResources.enc_file_key, TestResources.private_key, pw);

            Assert.AreEqual(pfk.Key, testPfk.Key, "File key is incorrect!");
            Assert.AreEqual(pfk.Iv, testPfk.Iv, "Initialization vector is incorrect!");
            Assert.AreEqual(pfk.Tag, testPfk.Tag, "Tag is incorrect!");
            Assert.AreEqual(pfk.Version, testPfk.Version, "Version is incorrect!");
        }
예제 #12
0
 internal EncryptedFileKey EncryptFileKey(PlainFileKey plainFileKey, UserPublicKey userPublicKey, long?nodeId = null)
 {
     try {
         return(Crypto.Sdk.Crypto.EncryptFileKey(plainFileKey, userPublicKey));
     } catch (CryptoException ce) {
         string message = "Encryption file key for node " + (nodeId.HasValue ? nodeId.Value.ToString() : "NULL") + " failed with " +
                          ce.Message;
         DracoonClient.Log.Debug(Logtag, message);
         throw new DracoonCryptoException(CryptoErrorMapper.ParseCause(ce));
     }
 }
예제 #13
0
 protected FileCipher(bool forEncryption, PlainFileKey fileKey)
 {
     try {
         byte[]         key        = Convert.FromBase64String(fileKey.Key);
         byte[]         iv         = Convert.FromBase64String(fileKey.Iv);
         AeadParameters parameters = new AeadParameters(new KeyParameter(key), 8 * tagSize, iv);
         realCipher = new GcmBlockCipher(new AesEngine());
         realCipher.Init(forEncryption, parameters);
     } catch (Exception e) {
         throw new CryptoSystemException("Could not create " + (forEncryption ? "encryption" : "decryption") + " ciper.", e);
     }
 }
        private PlainDataContainer TestDecryptSingleBlock(PlainFileKey pfk, EncryptedDataContainer edc)
        {
            FileDecryptionCipher decryptCipher = Crypto.CreateFileDecryptionCipher(pfk);

            using (MemoryStream ms = new MemoryStream()) {
                PlainDataContainer pdc = decryptCipher.ProcessBytes(new EncryptedDataContainer(edc.Content, null));
                ms.Write(pdc.Content, 0, pdc.Content.Length);
                pdc = decryptCipher.DoFinal(new EncryptedDataContainer(null, edc.Tag));
                ms.Write(pdc.Content, 0, pdc.Content.Length);
                return(new PlainDataContainer(ms.ToArray()));
            }
        }
        public void TestEncryptSingleBlock_DifferentContent()
        {
            PlainFileKey pfk = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);

            byte[] pfc = Convert.FromBase64String(TestResources.plain_file_modified);
            byte[] efc = Convert.FromBase64String(TestResources.enc_file);

            PlainDataContainer     testPdc = new PlainDataContainer(pfc);
            EncryptedDataContainer testEdc = TestEncryptSingleBlock(pfk, testPdc);

            CollectionAssert.AreNotEqual(efc, testEdc.Content, "File content does match!");
        }
        public void TestEncryptSingleBlock_DifferentTag()
        {
            PlainFileKey pfk = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key_bad_tag);

            byte[] ft  = Convert.FromBase64String(pfk.Tag);
            byte[] pfc = Convert.FromBase64String(TestResources.plain_file);

            PlainDataContainer     testPdc = new PlainDataContainer(pfc);
            EncryptedDataContainer testEdc = TestEncryptSingleBlock(pfk, testPdc);

            CollectionAssert.AreNotEqual(ft, testEdc.Tag, "File tag does not match!");
        }
        private EncryptedDataContainer TestEncryptSingleBlock(PlainFileKey pfk, PlainDataContainer pdc)
        {
            FileEncryptionCipher encCipher = Crypto.CreateFileEncryptionCipher(pfk);

            using (MemoryStream output = new MemoryStream()) {
                EncryptedDataContainer currentEdc = encCipher.ProcessBytes(pdc);
                output.Write(currentEdc.Content, 0, currentEdc.Content.Length);
                currentEdc = encCipher.DoFinal();
                output.Write(currentEdc.Content, 0, currentEdc.Content.Length);
                return(new EncryptedDataContainer(output.ToArray(), currentEdc.Tag));
            }
        }
        public void TestEncryptFileKey_Success()
        {
            EncryptedFileKey efk     = TestUtilities.ReadTestResource <EncryptedFileKey>(TestResources.enc_file_key);
            EncryptedFileKey testEfk = TestEncryptFileKey(TestResources.plain_file_key, TestResources.public_key);

            PlainFileKey pfk     = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);
            PlainFileKey testPfk = Crypto.DecryptFileKey(testEfk, TestUtilities.ReadTestResource <UserPrivateKey>(TestResources.private_key), "Pass1234!");

            Assert.AreEqual(pfk.Key, testPfk.Key, "File key is incorrect!");
            Assert.AreEqual(efk.Iv, testEfk.Iv, "Initialization vector is incorrect!");
            Assert.AreEqual(efk.Tag, testEfk.Tag, "Tag is incorrect!");
            Assert.AreEqual(efk.Version, testEfk.Version, "Version is incorrect!");
        }
예제 #19
0
        private Dictionary <long, PlainFileKey> GeneratePlainFileKeyMap(List <ApiFileIdFileKey> fileIdFileKeys, UserPrivateKey thisUserPrivateKey)
        {
            Dictionary <long, PlainFileKey> plainFileKeys = new Dictionary <long, PlainFileKey>(fileIdFileKeys.Count);

            foreach (ApiFileIdFileKey currentEncryptedFileKey in fileIdFileKeys)
            {
                EncryptedFileKey encryptedFileKey = FileMapper.FromApiFileKey(currentEncryptedFileKey.FileKeyContainer);
                PlainFileKey     decryptedFileKey = DecryptFileKey(encryptedFileKey, thisUserPrivateKey, currentEncryptedFileKey.FileId);
                plainFileKeys.Add(currentEncryptedFileKey.FileId, decryptedFileKey);
            }

            return(plainFileKeys);
        }
예제 #20
0
        private void EncryptedDownload(Uri downloadUri, PlainFileKey plainFileKey)
        {
            FileDecryptionCipher cipher;

            try {
                cipher = Crypto.Sdk.Crypto.CreateFileDecryptionCipher(plainFileKey);
            } catch (CryptoException ce) {
                string message = "Creation of decryption engine for encrypted download " + ActionId + " failed!";
                DracoonClient.Log.Debug(Logtag, message);
                throw new DracoonCryptoException(CryptoErrorMapper.ParseCause(ce), ce);
            }

            try {
                ProgressReportTimer = Stopwatch.StartNew();
                long downloadedByteCount = 0;
                while (downloadedByteCount < AssociatedNode.Size.GetValueOrDefault(0))
                {
                    byte[] chunk = DownloadChunk(downloadUri, downloadedByteCount, AssociatedNode.Size.GetValueOrDefault(0));
                    EncryptedDataContainer encryptedContainer = new EncryptedDataContainer(chunk, null);
                    PlainDataContainer     plainContainer     = cipher.ProcessBytes(encryptedContainer);
                    OutputStream.Write(plainContainer.Content, 0, plainContainer.Content.Length);
                    downloadedByteCount += chunk.Length;
                }

                byte[] encryptionTag = Convert.FromBase64String(plainFileKey.Tag);
                EncryptedDataContainer tagContainer   = new EncryptedDataContainer(null, encryptionTag);
                PlainDataContainer     finalContainer = cipher.DoFinal(tagContainer);
                OutputStream.Write(finalContainer.Content, 0, finalContainer.Content.Length);
                if (LastNotifiedProgressValue != downloadedByteCount)
                {
                    // Notify 100 percent progress
                    NotifyProgress(ActionId, downloadedByteCount, AssociatedNode.Size.GetValueOrDefault(0));
                }
            } catch (CryptoException ce) {
                const string message = "Decryption of file failed while downloading!";
                DracoonClient.Log.Debug(Logtag, message);
                throw new DracoonFileIOException(message, ce);
            } catch (IOException ioe) {
                if (IsInterrupted)
                {
                    throw new ThreadInterruptedException();
                }

                const string message = "Write to stream failed!";
                DracoonClient.Log.Debug(Logtag, message);
                throw new DracoonFileIOException(message, ioe);
            } finally {
                ProgressReportTimer.Stop();
            }
        }
        public void TestDecryptSingleBlock_ModifiedContent()
        {
            PlainFileKey pfk = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);

            byte[] ft  = Convert.FromBase64String(pfk.Tag);
            byte[] efc = Convert.FromBase64String(TestResources.enc_file_modified);
            EncryptedDataContainer testEdc = new EncryptedDataContainer(efc, ft);

            try {
                TestDecryptSingleBlock(pfk, testEdc);
            } catch (BadFileException) {
                return;
            }
            Assert.Fail();
        }
        public void TestDecryptSingleBlock_Success()
        {
            PlainFileKey pfk = TestUtilities.ReadTestResource <PlainFileKey>(TestResources.plain_file_key);

            byte[] fileTag = Convert.FromBase64String(pfk.Tag);
            byte[] ef      = Convert.FromBase64String(TestResources.enc_file);
            byte[] pf      = Convert.FromBase64String(TestResources.plain_file);

            EncryptedDataContainer testEdc = new EncryptedDataContainer(ef, fileTag);
            PlainDataContainer     testPdc = TestDecryptSingleBlock(pfk, testEdc);

            System.Diagnostics.Debug.WriteLine(Convert.ToBase64String(testPdc.Content));
            System.Diagnostics.Debug.WriteLine(Convert.ToBase64String(pf));
            CollectionAssert.AreEqual(pf, testPdc.Content, "File content does not match!");
        }
        /// <summary>
        /// Decrypts some bytes.
        /// </summary>
        /// <param name="fileKey">The file key to use.</param>
        ///  <param name="data">The encrypted bytes.</param>
        /// <returns>Plain bytes.</returns>
        private static byte[] DecryptData(PlainFileKey fileKey, byte[] data)
        {
            // !!! This method is an example for decryption. Like the method 'encryptData(...)', it uses
            //     byte array streams for input and output. However, any kind of stream
            //     (e.g. FileInputStream) could be used here.

            FileDecryptionCipher cipher = Crypto.CreateFileDecryptionCipher(fileKey);

            byte[] decData;
            using (MemoryStream is2 = new MemoryStream(data))
            {
                using (MemoryStream os = new MemoryStream())
                {
                    byte[] buffer = new byte[BLOCK_SIZE];
                    int    count;

                    try
                    {
                        PlainDataContainer pDataContainer;

                        // Decrypt blocks
                        while ((count = is2.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            byte[] eData = createByteArray(buffer, count);
                            pDataContainer = cipher.ProcessBytes(new EncryptedDataContainer(eData, null));
                            os.Write(pDataContainer.Content, 0, pDataContainer.Content.Length);
                        }

                        // Complete decryption
                        byte[] tag = Convert.FromBase64String(fileKey.Tag);
                        pDataContainer = cipher.DoFinal(new EncryptedDataContainer(null, tag));
                        os.Write(pDataContainer.Content, 0, pDataContainer.Content.Length);

                        decData = os.ToArray();
                    }
                    catch (IOException e)
                    {
                        throw new Exception("Error while reading/writing data!", e);
                    }
                    catch (CryptoException e)
                    {
                        throw new Exception("Error while decrypting data!", e);
                    }
                }
            }
            return(decData);
        }
        /// <summary>
        /// Encrypts some bytes.
        /// </summary>
        /// <param name="fileKey">The file key to use.</param>
        ///  <param name="data">The plain bytes.</param>
        /// <returns>Encrypted bytes.</returns>
        private static byte[] EncryptData(PlainFileKey fileKey, byte[] data)
        {
            // !!! This method is an example for encryption. It uses byte array streams for input and
            //     output. However, any kind of stream (e.g. FileInputStream) could be used here.

            FileEncryptionCipher cipher = Crypto.CreateFileEncryptionCipher(fileKey);

            byte[] encData;
            using (Stream is2 = new MemoryStream(data))
            {
                using (MemoryStream os = new MemoryStream())
                {
                    byte[] buffer = new byte[BLOCK_SIZE];
                    int    count;
                    try
                    {
                        EncryptedDataContainer eDataContainer;

                        // Encrypt blocks
                        while ((count = is2.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            byte[] pData = createByteArray(buffer, count);
                            eDataContainer = cipher.ProcessBytes(new PlainDataContainer(pData));
                            os.Write(eDataContainer.Content, 0, eDataContainer.Content.Length);
                        }

                        // Complete encryption
                        eDataContainer = cipher.DoFinal();
                        os.Write(eDataContainer.Content, 0, eDataContainer.Content.Length);
                        String tag = Convert.ToBase64String(eDataContainer.Tag);
                        fileKey.Tag = tag;

                        encData = os.ToArray();
                    }
                    catch (IOException e)
                    {
                        throw new Exception("Error while reading/writing data!", e);
                    }
                    catch (CryptoException e)
                    {
                        throw new Exception("Error while encrypting data!", e);
                    }
                }
            }
            return(encData);
        }
예제 #25
0
        private void EncryptedUpload(ref PlainFileKey plainFileKey)
        {
            DracoonClient.Log.Debug(LogTag, "Uploading file [" + FileUploadRequest.Name + "] in encrypted proxied way.");
            FileEncryptionCipher cipher;

            try {
                cipher = Crypto.Sdk.Crypto.CreateFileEncryptionCipher(plainFileKey);
            } catch (CryptoException ce) {
                string message = "Creation of encryption engine for encrypted upload " + ActionId + " failed!";
                DracoonClient.Log.Debug(LogTag, message);
                throw new DracoonCryptoException(CryptoErrorMapper.ParseCause(ce));
            }

            try {
                long   uploadedByteCount = 0;
                byte[] buffer            = new byte[DracoonClient.HttpConfig.ChunkSize];
                int    bytesRead         = 0;
                while ((bytesRead = InputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    EncryptedDataContainer encryptedContainer = EncryptChunk(cipher, bytesRead, buffer, false);
                    ProcessEncryptedChunk(new Uri(UploadToken.UploadUrl), encryptedContainer, uploadedByteCount, cipher, false);
                    uploadedByteCount += encryptedContainer.Content.Length;
                }

                EncryptedDataContainer finalEncryptedContainer = EncryptChunk(cipher, bytesRead, buffer, true);
                plainFileKey.Tag   = ProcessEncryptedChunk(new Uri(UploadToken.UploadUrl), finalEncryptedContainer, uploadedByteCount, cipher, true);
                uploadedByteCount += finalEncryptedContainer.Content.Length;
                if (LastNotifiedProgressValue != uploadedByteCount)
                {
                    // Notify 100 percent progress
                    NotifyProgress(ActionId, uploadedByteCount, OptionalFileSize);
                }
            } catch (IOException ioe) {
                if (IsInterrupted)
                {
                    throw new ThreadInterruptedException();
                }

                string message = "Read from stream failed!";
                DracoonClient.Log.Debug(LogTag, message);
                throw new DracoonFileIOException(message, ioe);
            } finally {
                ProgressReportTimer?.Stop();
            }
        }
        static void Main(String[] args)
        {
            // --- INITIALIZATION ---
            // Generate key pair
            UserKeyPair userKeyPair = Crypto.GenerateUserKeyPair(USER_PASSWORD);

            // Check key pair
            if (!Crypto.CheckUserKeyPair(userKeyPair, USER_PASSWORD))
            {
                Trace.WriteLine("Invalid user password!");
                return;
            }

            byte[] plainData = Encoding.UTF8.GetBytes(DATA);

            Trace.WriteLine("Plain Data:");
            Trace.WriteLine(Encoding.UTF8.GetString(plainData));
            Trace.WriteLine("Plain Data: (BASE64)");
            Trace.WriteLine(Convert.ToBase64String(plainData));

            // --- ENCRYPTION ---
            // Generate plain file key
            PlainFileKey fileKey = Crypto.GenerateFileKey();

            // Encrypt blocks
            byte[] encData = EncryptData(fileKey, plainData);
            // Encrypt file key
            EncryptedFileKey encFileKey = Crypto.EncryptFileKey(fileKey, userKeyPair.UserPublicKey);

            Trace.WriteLine("Encrypted Data: (Base64)");
            Trace.WriteLine(Convert.ToBase64String(encData));

            // --- DECRYPTION ---
            // Decrypt file key
            PlainFileKey decFileKey = Crypto.DecryptFileKey(encFileKey, userKeyPair.UserPrivateKey,
                                                            USER_PASSWORD);

            // Decrypt blocks
            byte[] decData = DecryptData(decFileKey, encData);

            Trace.WriteLine("Decrypted Data:");
            Trace.WriteLine(Encoding.UTF8.GetString(decData));
            Trace.WriteLine("Decrypted Data: (BASE64)");
            Trace.WriteLine(Convert.ToBase64String(plainData));
        }
예제 #27
0
        /// <summary>
        /// Generates a random file key.
        /// </summary>
        /// <param name="version">The encryption version for which the file key should be created.</param>
        /// <returns>The generated file key.</returns>
        /// <exception cref="Dracoon.Crypto.Sdk.InvalidFileKeyException">If the version for the file key is not supported.</exception>
        public static PlainFileKey GenerateFileKey(string version)
        {
            ValidateFileKeyVersion(version);

            byte[] key = new byte[fileKeySize];
            new SecureRandom().NextBytes(key);
            byte[] iv = new byte[ivSize];
            new SecureRandom().NextBytes(iv);

            PlainFileKey fileKey = new PlainFileKey()
            {
                Key     = Convert.ToBase64String(key),
                Iv      = Convert.ToBase64String(iv),
                Tag     = null,
                Version = version
            };

            return(fileKey);
        }
예제 #28
0
        protected override Node StartUpload()
        {
            NotifyStarted(ActionId);
            ApiCreateFileUpload apiFileUploadRequest = FileMapper.ToApiCreateFileUpload(FileUploadRequest);

            try {
                apiFileUploadRequest.UseS3 = CheckUseS3();
            } catch (DracoonApiException apiException) {
                DracoonClient.Log.Warn(LogTag, "S3 direct upload is not possible.", apiException);
            }

            IRestRequest uploadTokenRequest = Client.Builder.PostCreateFileUpload(apiFileUploadRequest);

            UploadToken = Client.Executor.DoSyncApiCall <ApiUploadToken>(uploadTokenRequest, RequestType.PostUploadToken);

            Node                  publicResultNode;
            PlainFileKey          plainFileKey          = CreateFileKey();
            ApiCompleteFileUpload apiCompleteFileUpload = FileMapper.ToApiCompleteFileUpload(FileUploadRequest);

            if (apiFileUploadRequest.UseS3.HasValue && apiFileUploadRequest.UseS3.Value)
            {
                List <ApiS3FileUploadPart> s3Parts          = EncryptedS3Upload(ref plainFileKey);
                EncryptedFileKey           encryptedFileKey = EncryptFileKey(plainFileKey);
                apiCompleteFileUpload.FileKey = FileMapper.ToApiFileKey(encryptedFileKey);
                apiCompleteFileUpload.Parts   = s3Parts;
                IRestRequest completeFileUploadRequest = Client.Builder.PutCompleteS3FileUpload(UploadToken.UploadId, apiCompleteFileUpload);
                Client.Executor.DoSyncApiCall <VoidResponse>(completeFileUploadRequest, RequestType.PutCompleteS3Upload);
                publicResultNode = NodeMapper.FromApiNode(S3Finished());
            }
            else
            {
                EncryptedUpload(ref plainFileKey);
                EncryptedFileKey encryptedFileKey = EncryptFileKey(plainFileKey);
                apiCompleteFileUpload.FileKey = FileMapper.ToApiFileKey(encryptedFileKey);
                IRestRequest completeFileUploadRequest =
                    Client.Builder.PutCompleteFileUpload(new Uri(UploadToken.UploadUrl).PathAndQuery, apiCompleteFileUpload);
                ApiNode resultNode = Client.Executor.DoSyncApiCall <ApiNode>(completeFileUploadRequest, RequestType.PutCompleteUpload);
                publicResultNode = NodeMapper.FromApiNode(resultNode);
            }

            NotifyFinished(ActionId, publicResultNode);
            return(publicResultNode);
        }
 internal FileDecryptionCipher(PlainFileKey fileKey) : base(false, fileKey)
 {
 }
예제 #30
0
        public DownloadShare CreateDownloadShare(CreateDownloadShareRequest request)
        {
            _client.Executor.CheckApiServerVersion();

            #region Parameter Validation

            request.MustNotNull(nameof(request));

            Node targetNode = _client.NodesImpl.GetNode(request.NodeId);
            // Node id is still checked in previous called getNode()
            // To save much effort throw this restriction instantly and not let the rest api throw this error
            if (targetNode.IsEncrypted.GetValueOrDefault(false) && targetNode.Type != NodeType.File)
            {
                throw new DracoonApiException(DracoonApiCode.VALIDATION_DL_SHARE_CANNOT_CREATE_ON_ENCRYPTED_ROOM_FOLDER);
            }

            request.Name.MustNotNullOrEmptyOrWhitespace(nameof(request.Name), true);
            request.MaxAllowedDownloads.NullableMustPositive(nameof(request.MaxAllowedDownloads));
            if (targetNode.IsEncrypted.GetValueOrDefault(false) && string.IsNullOrWhiteSpace(request.EncryptionPassword) &&
                !string.IsNullOrWhiteSpace(request.AccessPassword))
            {
                throw new ArgumentException("Download share of a encrypted node must have a encryption password and no access password.");
            }

            if (!targetNode.IsEncrypted.GetValueOrDefault(false) && string.IsNullOrWhiteSpace(request.AccessPassword) &&
                !string.IsNullOrWhiteSpace(request.EncryptionPassword))
            {
                throw new ArgumentException("Download share of a not encrypted node must have a access password and no encryption password.");
            }

            if (targetNode.IsEncrypted.GetValueOrDefault(false) && string.IsNullOrWhiteSpace(request.EncryptionPassword))
            {
                throw new ArgumentException("Download share of a encrypted node must have a encryption password.");
            }

            if (!targetNode.IsEncrypted.GetValueOrDefault(false))
            {
                request.AccessPassword?.MustNotNullOrEmptyOrWhitespace(nameof(request.AccessPassword));
            }

            if (request.EmailRecipients != null)
            {
                request.EmailRecipients.EnumerableMustNotNullOrEmpty(nameof(request.EmailRecipients));
                request.EmailRecipients.ForEach(current => current.MustNotNullOrEmptyOrWhitespace(nameof(request.EmailRecipients) + " element"));
                request.EmailBody.MustNotNullOrEmptyOrWhitespace(nameof(request.EmailBody));
                request.EmailSubject.MustNotNullOrEmptyOrWhitespace(nameof(request.EmailSubject));
            }

            if (request.SmsRecipients != null)
            {
                request.SmsRecipients.EnumerableMustNotNullOrEmpty(nameof(request.SmsRecipients));
                request.SmsRecipients.ForEach(current => current.MustNotNullOrEmptyOrWhitespace(nameof(request.SmsRecipients) + " element"));
                if (string.IsNullOrEmpty(request.AccessPassword))
                {
                    throw new ArgumentException("If a SMS should be sent, a access password must be set.");
                }
            }

            #endregion

            ApiCreateDownloadShareRequest apiRequest = ShareMapper.ToUnencryptedApiCreateDownloadShareRequest(request);
            if (targetNode.IsEncrypted.GetValueOrDefault(false))
            {
                UserKeyPair      creatorKeyPair          = _client.AccountImpl.GetAndCheckUserKeyPair();
                EncryptedFileKey creatorEncryptedFileKey = _client.NodesImpl.GetEncryptedFileKey(request.NodeId);
                PlainFileKey     plainFileKey            = _client.NodesImpl.DecryptFileKey(creatorEncryptedFileKey, creatorKeyPair.UserPrivateKey, request.NodeId);
                UserKeyPair      newGeneratedKeyPair     = _client.AccountImpl.GenerateNewUserKeyPair(request.EncryptionPassword);
                EncryptedFileKey newEncryptedFileKey     =
                    _client.NodesImpl.EncryptFileKey(plainFileKey, newGeneratedKeyPair.UserPublicKey, request.NodeId);

                apiRequest.KeyPair = UserMapper.ToApiUserKeyPair(newGeneratedKeyPair);
                apiRequest.FileKey = FileMapper.ToApiFileKey(newEncryptedFileKey);
            }

            IRestRequest     restRequest = _client.Builder.PostCreateDownloadShare(apiRequest);
            ApiDownloadShare resultShare =
                _client.Executor.DoSyncApiCall <ApiDownloadShare>(restRequest, DracoonRequestExecutor.RequestType.PostCreateDownloadShare);
            return(ShareMapper.FromApiDownloadShare(resultShare));
        }