public IResult <TUser> SetPassword(TUser user, string password) => Do <TUser> .Try(r =>
        {
            var salt = EncryptionUtils.GenerateSalt();

            user.PasswordHash  = EncryptionUtils.GenerateHash(password, salt);
            user.Salt          = salt;
            user.SecurityStamp = Guid.NewGuid().ToString("N");

            return(user);
        }).Result;
Ejemplo n.º 2
0
        public void TestEncryption1()
        {
            byte[] toEncrypt = Guid.NewGuid().ToByteArray();

            byte[] encrypted = EncryptionUtils.EncryptAES(toEncrypt, StringUtils.HexToByteArray(Key), StringUtils.HexToByteArray(Vector));

            byte[] decrypted = EncryptionUtils.DecryptAES(encrypted, StringUtils.HexToByteArray(Key), StringUtils.HexToByteArray(Vector));

            Assert.True(toEncrypt.SequenceEqual(decrypted));
        }
Ejemplo n.º 3
0
        public static string DecryptMessage(byte[] aes256Key, Stream message)
        {
            using (var inputStream = new BinaryReader(message, Encoding.UTF8, true))
            {
                var iv     = inputStream.ReadBytes(16); // todo: wait for a time
                var msgLen = inputStream.ReadInt32();

                return(Encoding.UTF8.GetString(EncryptionUtils.DecryptDataWithAes256(inputStream.ReadBytes(msgLen), aes256Key, iv)));
            }
        }
Ejemplo n.º 4
0
 public void TestProtectionLocalMachine()
 {
     foreach (var str in _transformedStrings)
     {
         var protectedStr   = EncryptionUtils.ProtectForLocalMachine(str);
         var unprotectedStr = EncryptionUtils.UnprotectForLocalMachine(protectedStr);
         Assert.AreEqual(str, unprotectedStr,
                         "String corruption after protection, then un-protection (local machine)");
     }
 }
Ejemplo n.º 5
0
        /// <inheritdoc/>
        protected override void GenerateEncryptedObjectRequestUsingMetadata(PutObjectRequest putObjectRequest, EncryptionInstructions instructions)
        {
            EncryptionUtils.AddUnencryptedContentLengthToMetadata(putObjectRequest);

            // Encrypt the object data with the instruction
            putObjectRequest.InputStream = EncryptionUtils.EncryptRequestUsingInstructionV2(putObjectRequest.InputStream, instructions);

            // Update the metadata
            EncryptionUtils.UpdateMetadataWithEncryptionInstructionsV2(putObjectRequest, instructions, EncryptionClient);
        }
Ejemplo n.º 6
0
 public void TestProtectionCurrentUserLegacy()
 {
     foreach (var str in _transformedStrings)
     {
         var legacyProtectedStr = LegacyProtection(str, DataProtectionScope.CurrentUser);
         var unprotectedStr     = EncryptionUtils.UnprotectForLocalMachine(legacyProtectedStr);
         Assert.AreEqual(str, unprotectedStr,
                         "String corruption after legacy protection, then un-protection (current user)");
     }
 }
        public void Bad_key_generates_exception()
        {
            const string testString = "This is a test string";
            var          data       = Encoding.UTF8.GetBytes(testString);
            var          password   = "******";
            var          salt       = EncryptionUtils.GenerateRandomSalt();
            var          encrypted  = Encryptor.SimmetricEncrypt(password, salt, data);

            Assert.Throws <SecurityException>(() => Encryptor.SimmetricDecrypt(password + "hello", salt, encrypted));
        }
Ejemplo n.º 8
0
 public void TestProtectionCurrentUser()
 {
     foreach (var str in _transformedStrings)
     {
         var protectedStr   = EncryptionUtils.Protect(str);
         var unprotectedStr = EncryptionUtils.Unprotect(protectedStr);
         Assert.AreEqual(str, unprotectedStr,
                         "String corruption after protection, then un-protection (current user)");
     }
 }
Ejemplo n.º 9
0
        protected override string GetMessageToBeSent()
        {
            switch (proxyStyle)
            {
            case HTTPHelper.ProxyStyle.SpecifiedProxy:
                var proxyUsername = "";
                try
                {
                    if (!string.IsNullOrEmpty(protectedProxyUsername))
                    {
                        proxyUsername = EncryptionUtils.Unprotect(protectedProxyUsername);
                    }
                }
                catch (Exception e)
                {
                    log.Error("Could not unprotect internet proxy username.", e);
                    return(null);
                }

                var proxyPassword = "";
                try
                {
                    if (!string.IsNullOrEmpty(protectedProxyPassword))
                    {
                        proxyPassword = EncryptionUtils.Unprotect(protectedProxyPassword);
                    }
                }
                catch (Exception e)
                {
                    log.Error("Could not unprotect internet proxy password.", e);
                    return(null);
                }

                return(string.Join(SEPARATOR.ToString(),
                                   HealthCheckSettings.PROXY_SETTINGS,
                                   ((int)HTTPHelper.ProxyStyle.SpecifiedProxy).ToString(),
                                   proxyAddress, proxyPort.ToString(),
                                   timeOut.ToString(),
                                   bypassProxyForServers.ToString(),
                                   provideProxyCredentials.ToString(),
                                   EncryptionUtils.ProtectForLocalMachine(proxyUsername),
                                   EncryptionUtils.ProtectForLocalMachine(proxyPassword),
                                   ((int)proxyAuthenticationMethod).ToString()));

            case HTTPHelper.ProxyStyle.SystemProxy:
                return(string.Join(SEPARATOR.ToString(),
                                   HealthCheckSettings.PROXY_SETTINGS,
                                   ((int)HTTPHelper.ProxyStyle.SystemProxy).ToString()));

            default:
                return(string.Join(SEPARATOR.ToString(),
                                   HealthCheckSettings.PROXY_SETTINGS,
                                   ((int)HTTPHelper.ProxyStyle.DirectConnection).ToString()));
            }
        }
        public void Verify_asymmetric_encription()
        {
            var key = EncryptionUtils.GenerateAsimmetricKey();

            var publicKey = key.GetPublicKey();
            var encrypted = EncryptionUtils.Encrypt(publicKey, "This is a password");

            var decrypted = EncryptionUtils.Decrypt(key, encrypted);

            Assert.That(decrypted, Is.EqualTo("This is a password"));
        }
        public void GenerateHash_When_Default_Arguments_Returns_Base64_Hash()
        {
            // Arrange & Act
            var result = EncryptionUtils.GenerateHash(
                salt: EncryptionUtils.GenerateSalt(),
                value: Random.String()
                );

            // Assert
            result.ShouldBeBase64();
        }
        /// <summary>
        /// Handles the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        public void Handle(EbayRegisterCustomerCommand command)
        {
            //validates market place
            InfoAccumulator info = MarketPlaceQueries.ValidateCustomerMarketPlace(EbayInternalId, command.MarketplaceName);

            if (info.HasErrors)
            {
                SendReply(info, command);
                return;
            }

            int marketPlaceId = MarketPlaceQueries.GetMarketPlaceIdFromTypeId(EbayInternalId)
                                .GetValue();

            CustomerMarketPlace marketPlace = new CustomerMarketPlace {
                CustomerId    = int.Parse(EncryptionUtils.SafeDecrypt(command.CustomerId)),
                DisplayName   = command.MarketplaceName,
                MarketPlaceId = marketPlaceId,
                SecurityData  = SerializationUtils.SerializeToBinaryXml(new EbaySecurityInfo {
                    Token = command.Token
                })
            };

            int marketPlaceTableId = GetIdIfValidOrThrowException(MarketPlaceQueries.UpsertMarketPlace(marketPlace, EbayInternalId), marketplaceUpsertFailed);

            var updateHistory = new CustomerMarketPlaceUpdateHistory()
            {
                CustomerMarketPlaceId = marketPlaceTableId,
                UpdatingStart         = DateTime.UtcNow
            };

            int marketPlaceHistoryId = GetIdIfValidOrThrowException(MarketPlaceQueries.UpsertMarketPlaceUpdatingHistory(updateHistory)
                                                                    .Value, marketplaceHistoryUpsertFailed);

            var validateUserAccountCommand = new EbayValidationCommand();

            validateUserAccountCommand.IsValidateUserAccount = true;
            validateUserAccountCommand.Token   = command.Token;
            validateUserAccountCommand.PayLoad = new Dictionary <string, object> {
                {
                    CustomerId, command.CustomerId
                }, {
                    SessionId, command.SessionId
                }, {
                    MarketplaceId, marketPlaceId
                }, {
                    MarketPlaceUpdatingHistoryId, marketPlaceHistoryId
                }
            };

            //sends command to validate user account
            //the response to this command is handled in this class by another handler method with appropriate response class
            SendCommand(ThirdPartyService.Address, validateUserAccountCommand, command);
        }
Ejemplo n.º 13
0
 private const char SEPARATOR = '\x202f'; // narrow non-breaking space.
 private string ProtectCredential(string Host, string username, string passwordSecret)
 {
     if (username == string.Empty || password == string.Empty)
     {
         return(EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { Host })));
     }
     else
     {
         return(EncryptionUtils.ProtectForLocalMachine(String.Join(SEPARATOR.ToString(), new[] { Host, username, passwordSecret })));
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Updates the request where the metadata contains encryption information
        /// and the input stream contains the encrypted object contents.
        /// </summary>
        /// <param name="putObjectRequest">
        /// The request whose contents are to be encrypted.
        /// </param>
        private void GenerateEncryptedObjectRequestUsingMetadata(PutObjectRequest putObjectRequest, EncryptionInstructions instructions)
        {
            EncryptionUtils.AddUnencryptedContentLengthToMetadata(putObjectRequest);

            // Encrypt the object data with the instruction
            putObjectRequest.InputStream = EncryptionUtils.EncryptRequestUsingInstruction(putObjectRequest.InputStream, instructions);

            // Update the metadata
            EncryptionUtils.UpdateMetadataWithEncryptionInstructions(
                putObjectRequest, instructions, this.EncryptionClient.EncryptionMaterials.KMSKeyID != null);
        }
        /// <summary>
        /// Play the specified file - file will actually be the video id from the website
        /// This method will hide MediaPortal and run the BrowserHost - BorwserHost needs to support the WebAutomationType and have the code to actually navigate to the site
        /// </summary>
        /// <param name="strFile"></param>
        /// <returns></returns>
        public override bool Play(string strFile)
        {
            _lastError = string.Empty;

            if (_browserProcess != null)
            {
                //ReinitialiseService();
                ProcessHelper.SetForeground(_browserProcess.MainWindowHandle);
                return(true);
            }


            // Set up the process
            // Process requires path to MediaPortal, Web Automation Type, Video Id, Username, Password
            _browserProcess = new Process();
            _browserProcess.StartInfo.UseShellExecute       = false;
            _browserProcess.StartInfo.RedirectStandardError = true;
            _browserProcess.EnableRaisingEvents             = true;
            //_browserProcess.StartInfo.FileName = "plugins\\Windows\\OnlineVideos\\OnlineVideos.Sites.WebAutomation.BrowserHost.exe";
            var dir = MediaPortal.Configuration.Config.GetFolder(MediaPortal.Configuration.Config.Dir.Base);

            _browserProcess.StartInfo.FileName  = Path.Combine(OnlineVideoSettings.Instance.DllsDir, _hostProcessName + ".exe");
            _browserProcess.StartInfo.Arguments = string.Format("\"{0} \" \"{1}\" \"{2}\" \"{3}\" \"{4}\" \"{5}\"",
                                                                dir,
                                                                strFile,
                                                                _automationType,
                                                                EncryptionUtils.SymEncryptLocalPC(string.IsNullOrEmpty(_username) ? "_" : _username),
                                                                EncryptionUtils.SymEncryptLocalPC(string.IsNullOrEmpty(_password) ? "_" : _password),
                                                                _emulationLevel);
            _browserProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;

            // Restart MP or Restore MP Window if needed
            _browserProcess.Exited += new EventHandler(BrowserProcess_Exited);

            // Hide MediaPortal
            if (_browserProcess.Start())
            {
                Thread.Sleep(2000); // Sleep for 2 seconds to allow the browser host to load - should prevent the desktop flashing up
                if (_browserProcess != null)
                {
                    ReinitialiseService();
                    SuspendMP(true);
                    ProcessHelper.SetForeground(_browserProcess.MainWindowHandle);
                    Redirect(_browserProcess.StandardError);
                }
                else
                {
                    OnlineVideos.Log.Error("Browser process closed on startup");
                    SuspendMP(false);
                }
            }

            return(true);
        }
Ejemplo n.º 16
0
        private void m_Timer_Tick(object sender, EventArgs e)
        {
            while (this.m_TcpClient.Available > 0)
            {
                string _base64String = this.m_StreamReader.ReadLine();
                byte[] _base64       = Convert.FromBase64String(_base64String);

                byte[] _message = EncryptionUtils.RSADecrypt(this.m_MyRSADecoder, _base64);
                this.ReadFromServer(Encoding.Default.GetString(_message));
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Decrypts the authority identifier.
        /// </summary>
        /// <param name="authorityId">The authority identifier.</param>
        /// <param name="origin">The origin.</param>
        /// <param name="isDirector">if set to <c>true</c> [is director].</param>
        /// <param name="encryptionTime">The encryption time.</param>
        /// <returns></returns>
        /// <exception cref="System.Exception">
        /// Invalid authority id.
        /// or
        /// Not a authority id.
        /// or
        /// Origin validation failed.
        /// or
        /// Invalid authority id.
        /// or
        /// Not a director id
        /// or
        /// Not a shareholder id
        /// </exception>
        public static int DecryptAuthorityId(string authorityId, string origin, bool isDirector, out DateTime encryptionTime)
        {
            string str = EncryptionUtils.SafeDecrypt(authorityId);

            var split = str.Split(splitStrings, StringSplitOptions.None);

            if (split.Length != 5)
            {
                throw new Exception("Invalid authority id " + authorityId);
            }

            if (split[0] != "3" || split[5] != "3")
            {
                throw new Exception("Not a authority id " + authorityId);
            }

            if (!origin.Equals(split[3], StringComparison.InvariantCultureIgnoreCase))
            {
                throw new Exception("Origin validation failed " + authorityId);
            }

            int n = int.Parse(split[4]);

            if (n != 0 || n != 1)
            {
                throw new Exception("Invalid authority id " + authorityId);
            }

            if (isDirector && n == 0)
            {
                throw new Exception("Not a director id " + authorityId);
            }

            if (!isDirector && n == 1)
            {
                throw new Exception("Not a share holder id " + authorityId);
            }

            try {
                encryptionTime = DateTime.Parse(split[2]);
            } catch (Exception ex) {
                throw new Exception("Could not parse date for authority id" + authorityId);
            }

            int res;

            try {
                res = int.Parse(split[1]);
            } catch (Exception ex) {
                throw new Exception("Could no parse authority id " + authorityId);
            }

            return(res);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Updates the request where the instruction file contains encryption information
        /// and the input stream contains the encrypted object contents.
        /// </summary>
        /// <param name="putObjectRequest"></param>
        private void GenerateEncryptedObjectRequestUsingInstructionFile(PutObjectRequest putObjectRequest, EncryptionInstructions instructions)
        {
            EncryptionUtils.AddUnencryptedContentLengthToMetadata(putObjectRequest);

            // Encrypt the object data with the instruction
            putObjectRequest.InputStream = EncryptionUtils.EncryptRequestUsingInstruction(putObjectRequest.InputStream, instructions);

            // Create request for uploading instruction file
            PutObjectRequest instructionFileRequest = EncryptionUtils.CreateInstructionFileRequest(putObjectRequest, instructions);

            this.EncryptionClient.S3ClientForInstructionFile.PutObject(instructionFileRequest);
        }
Ejemplo n.º 19
0
 public EmailSender(string host, string username, string password, int port)
 {
     client = new SmtpClient
     {
         Port                  = port,
         DeliveryMethod        = SmtpDeliveryMethod.Network,
         EnableSsl             = true,
         UseDefaultCredentials = false,
         Host                  = host,
         Credentials           = new NetworkCredential(username, EncryptionUtils.Unprotect(password))
     };
 }
Ejemplo n.º 20
0
        public void VerifyThatSaltIsGenerated()
        {
            var saltString1 = EncryptionUtils.GenerateRandomSaltString();

            Assert.IsNotNull(saltString1);
            Assert.AreEqual(4 * (int)Math.Ceiling(32 / 3.0), saltString1.Length);

            var saltString2 = EncryptionUtils.GenerateRandomSaltString();

            Assert.AreNotEqual(saltString1, saltString2);
            Assert.AreEqual(4 * (int)Math.Ceiling(32 / 3.0), saltString2.Length);
        }
Ejemplo n.º 21
0
        private async Task DeserializeOutboxMails(int mailCount)
        {
            var index  = 1;
            var emails = await PhantasmaService.GetAllOutboxMessages(mailCount);

            var storedEmails = await _db.GetSentMessages(AuthenticationService.AuthenticatedUser.UserBox);

            try
            {
                //deserialization
                foreach (var email in emails)
                {
                    if (email.StartsWith("{") || email.StartsWith("["))
                    {
                        string decryptedText = string.Empty;
                        var    mailObject    =
                            JsonConvert.DeserializeObject <Message>(email, AppSettings.JsonSettings());
                        if (mailObject?.TextContent != null)
                        {
                            if (MessageUtils.IsHex(mailObject.TextContent.ToCharArray()))
                            {
                                var encryptedText = mailObject.TextContent.HexToBytes();
                                var remotePub     = await PhantasmaService.GetMailboxPublicKey(mailObject.ToInbox);

                                decryptedText = EncryptionUtils.Decrypt(encryptedText,
                                                                        AuthenticationService.AuthenticatedUser.GetPrivateKey(), remotePub.HexToBytes());
                            }

                            mailObject.ID = index;
                            var hash = GetHashFromStoredMessage(storedEmails.ToList(), mailObject);
                            if (!string.IsNullOrEmpty(hash))
                            {
                                mailObject.Hash = hash;
                            }
                            if (!string.IsNullOrEmpty(decryptedText))
                            {
                                mailObject.TextContent = decryptedText;
                            }
                            SentList.Add(mailObject);
                        }
                    }
                    index++;
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            SentList = new ObservableCollection <Message>(SentList.OrderByDescending(p => p.Date)
                                                          .ThenByDescending(p => p.Date.Hour).ToList());
            _fullSentList = SentList.ToList();
        }
        /// <summary>
        /// Play the specified file - file will actually be the video id from the website
        /// This method will hide MediaPortal and run the BrowserHost - BorwserHost needs to support the WebAutomationType and have the code to actually navigate to the site
        /// </summary>
        /// <returns></returns>
        public bool Play()
        {
            _lastError = string.Empty;

            if (_browserProcess != null)
            {
                ReinitialiseService();
                ProcessHelper.SetForeground(_browserProcess.MainWindowHandle);
                return(true);
            }


            // Set up the process
            // Process requires path to MediaPortal, Web Automation Type, Video Id, Username, Password
            _browserProcess = new Process();
            _browserProcess.StartInfo.UseShellExecute       = false;
            _browserProcess.StartInfo.RedirectStandardError = true;
            _browserProcess.EnableRaisingEvents             = true;
            var dir = OnlineVideoSettings.Instance.DllsDir;

            _browserProcess.StartInfo.FileName  = _processPath;
            _browserProcess.StartInfo.Arguments = string.Format("\"{0} \" \"{1}\" \"{2}\" \"{3}\" \"{4}\" {5}",
                                                                dir,
                                                                _fileOrUrl,
                                                                _automationType,
                                                                EncryptionUtils.SymEncryptLocalPC(string.IsNullOrEmpty(_username) ? "_" : _username),
                                                                EncryptionUtils.SymEncryptLocalPC(string.IsNullOrEmpty(_password) ? "_" : _password),
                                                                _emulationLevel);
            _browserProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal; // ProcessWindowStyle.Maximized;

            // Restart MP or Restore MP Window if needed
            _browserProcess.Exited += BrowserProcess_Exited;

            // Hide MediaPortal
            if (_browserProcess.Start())
            {
                Thread.Sleep(2000); // Sleep for 2 seconds to allow the browser host to load - should prevent the desktop flashing up
                if (_browserProcess != null)
                {
                    ReinitialiseService();
                    SuspendMP(true);
                    ProcessHelper.SetForeground(_browserProcess.MainWindowHandle);
                    Redirect(_browserProcess.StandardError);
                }
                else
                {
                    Log.Error("Browser process closed on startup");
                    SuspendMP(false);
                }
            }

            return(true);
        }
Ejemplo n.º 23
0
        public static void SendEncrypted(byte[] message, byte[] aes256Key, Stream to)
        {
            using (var outputStream = new BinaryWriter(to, Encoding.UTF8, true))
            {
                var iv = EncryptionUtils.Generate128BitIv();
                outputStream.Write(iv);

                var encrypted = EncryptionUtils.EncryptDataWithAes256(message, aes256Key, iv);
                outputStream.Write(encrypted.Length);
                outputStream.Write(encrypted);
            }
        }
Ejemplo n.º 24
0
        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            var savedPassword = StatePersister.Instance.Load <String>("password");

            if (!String.IsNullOrEmpty(savedPassword))
            {
                var decrypted = EncryptionUtils.Decrypt(savedPassword);
                PasswordBox.Password = decrypted;
            }
        }
        /// <inheritdoc/>
        protected override PutObjectRequest GenerateEncryptedObjectRequestUsingInstructionFile(PutObjectRequest putObjectRequest, EncryptionInstructions instructions)
        {
            EncryptionUtils.AddUnencryptedContentLengthToMetadata(putObjectRequest);

            // Encrypt the object data with the instruction
            putObjectRequest.InputStream = EncryptionUtils.EncryptRequestUsingInstruction(putObjectRequest.InputStream, instructions);

            // Create request for uploading instruction file
            PutObjectRequest instructionFileRequest = EncryptionUtils.CreateInstructionFileRequest(putObjectRequest, instructions);

            return(instructionFileRequest);
        }
Ejemplo n.º 26
0
        public bool VerifySignature(Transaction transaction)
        {
            byte[]     transactionDataHash = transaction.DataHash;
            BigInteger r         = new BigInteger(transaction.SenderSignature[0], 16);
            BigInteger s         = new BigInteger(transaction.SenderSignature[1], 16);
            ECPoint    publicKey = EncryptionUtils.DecompressKey(transaction.SenderPublicKey);

            bool signatureVerified = EncryptionUtils.VerifySignature(
                publicKey, r, s, transactionDataHash);

            return(signatureVerified);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Encrypts the S3 object being uploaded.
        /// </summary>
        /// <param name="executionContext"></param>
        protected void PreInvoke(IExecutionContext executionContext)
        {
            EncryptionInstructions instructions = null;

            if (NeedToGenerateKMSInstructions(executionContext))
            {
                instructions = EncryptionUtils.GenerateInstructionsForKMSMaterials(
                    EncryptionClient.KMSClient, EncryptionClient.EncryptionMaterials);
            }

            PreInvokeSynchronous(executionContext, instructions);
        }
Ejemplo n.º 28
0
        private void UploadFile(FileInfo fileToUpload)
        {
            Logger.DebugFormat("Encrypting File {0}", fileToUpload.FullName);
            var zippedFileName = Path.ChangeExtension(fileToUpload.FullName, ".zip");

            if (File.Exists(zippedFileName))
            {
                File.Delete(zippedFileName);
            }
            using (ZipArchive archive = ZipFile.Open(zippedFileName, ZipArchiveMode.Create))
            {
                archive.CreateEntryFromFile(fileToUpload.FullName, fileToUpload.Name);
            }

            var encryptedFileName = fileToUpload.FullName + ".encrypted";

            if (File.Exists(encryptedFileName))
            {
                File.Delete(encryptedFileName);
            }
            var encryptedKey = EncryptionUtils.EncryptFile(
                zippedFileName,
                encryptedFileName,
                _configuration.Key);

            var keyFileName = fileToUpload.FullName + ".key";

            File.WriteAllText(keyFileName, encryptedKey);

            //now delete the original zip, and re-create the zip adding key and encrypted file
            File.Delete(zippedFileName);

            Logger.DebugFormat("Creating Zip File {0} from logfile {1}", zippedFileName, fileToUpload.FullName);
            using (ZipArchive archive = ZipFile.Open(zippedFileName, ZipArchiveMode.Create))
            {
                archive.CreateEntryFromFile(encryptedFileName, Path.GetFileName(encryptedFileName));
                archive.CreateEntryFromFile(keyFileName, Path.GetFileName(keyFileName));
            }


            var url = String.Format("{0}/api/logs/upload/{1}",
                                    _configuration.ServerAddress, _configuration.CustomerId);

            using (WebClient client = new WebClient())
            {
                client.UploadFile(url, zippedFileName);
            }

            File.Delete(fileToUpload.FullName);
            File.Delete(zippedFileName);
            File.Delete(encryptedFileName);
            File.Delete(keyFileName);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Encrypts the S3 object being uploaded.
        /// </summary>
        /// <param name="executionContext"></param>
        protected async System.Threading.Tasks.Task PreInvokeAsync(IExecutionContext executionContext)
        {
            EncryptionInstructions instructions = null;

            if (NeedToGenerateKMSInstructions(executionContext))
            {
                instructions = await EncryptionUtils.GenerateInstructionsForKMSMaterialsAsync(
                    EncryptionClient.KMSClient, EncryptionClient.EncryptionMaterials).ConfigureAwait(false);
            }

            PreInvokeSynchronous(executionContext, instructions);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Permet la vérification du mot de passe par rapport au mot de passe hasher
 /// </summary>
 /// <param name="hashedPassword">Le mot de passe hasher</param>
 /// <param name="providedPassword">le mot de passe en plainText</param>
 /// <returns></returns>
 public PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
 {
     try
     {
         EncryptionUtils.Compare(providedPassword, hashedPassword);
     }
     catch (ManahostException)
     {
         return(PasswordVerificationResult.Failed);
     }
     return(PasswordVerificationResult.Success);
 }