public async Task <IUser> AddNew(IUser entity)
        {
            TUser tEntity = entity as TUser;

            var errors = await this.ValidateEntityToAdd(tEntity);

            if (errors.Count() > 0)
            {
                await this.ThrowEntityException(errors);
            }

            try
            {
                this.StartTransaction();
                tEntity.CreatedDate = DateTime.Now;
                tEntity.CreatedBy   = LoggedUser.Id;
                if (tEntity.Password != "" && tEntity.Password != null)
                {
                    tEntity.Password = _encryptionProvider.Encrypt(tEntity.Password);
                }

                if (tEntity.RoleId == 1)
                { //ONshore
                    tEntity.AccountId     = null;
                    tEntity.CoordinatorId = null;
                }
                else if (tEntity.RoleId == 2)
                {//OFFshore
                    tEntity.AccountId = null;
                }
                else if (tEntity.RoleId == 3)
                {//Client
                    tEntity.CoordinatorId = null;
                }

                var savedEntity = await base.AddNew(tEntity);

                long userId = savedEntity.Id;
                await this._groupUserRepository.DeleteGroupUserByUserId(userId);

                await this.SaveGroupUser(tEntity, userId);

                this.CommitTransaction();
                return(savedEntity);
            }
            catch (PostgresException ex)
            {
                throw new EntityUpdateException(ex);
            }
            catch
            {
                throw;
            }
        }
Esempio n. 2
0
        async private Task Save(XDocument xdoc, string path)
        {
            StringWriter swriter = new StringWriter();

            xdoc.Save(swriter, SaveOptions.None);
            string  xmlString          = swriter.GetStringBuilder().ToString();
            IBuffer xmlEncryptedBuffer = EncryptionProvider.Encrypt(xmlString);

            StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\");

            var file = await sf.GetFileAsync(Path.GetFileName(path));

            using (IRandomAccessStream ras = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outs = ras.GetOutputStreamAt(0))
                {
                    await outs.WriteAsync(xmlEncryptedBuffer);

                    bool suc = await outs.FlushAsync();

                    outs.Dispose();
                }
                ras.Dispose();
            }
        }
Esempio n. 3
0
        public MailOutputDto Save([FromBody] MailDto mailDto)
        {
            var setPassword = (mailDto.Id != 0 && !string.IsNullOrEmpty(mailDto.Password)) ||
                              mailDto.Id == 0;
            var secret = Guid.NewGuid().ToString();
            var mail   = new Mail
            {
                Id           = mailDto.Id,
                EmailAddress = mailDto.EmailAddress,
                EnableSsl    = mailDto.EnableSsl,
                Host         = mailDto.Host,
                Name         = mailDto.Name,
                Password     = setPassword ? encryption.Encrypt(mailDto.Password, secret) : string.Empty,
                Port         = mailDto.Port,
                UserId       = user.Id
            };

            context.Update(mail);
            context.Entry(mail).Property(x => x.Password).IsModified = setPassword;
            context.SaveChanges();

            return(new MailOutputDto
            {
                Id = mail.Id,
                EmailAddress = mail.EmailAddress,
                EnableSsl = mail.EnableSsl,
                Host = mail.Host,
                Name = mail.Name,
                Password = mailDto.Password,
                Port = mail.Port,
                Secret = setPassword ? secret : null
            });
        }
Esempio n. 4
0
        public void EncryptionProvider_Encrypt_ReturnsExpectedCiphertext()
        {
            EncryptionProvider cipher     = new EncryptionProvider(validKey);
            string             ciphertext = cipher.Encrypt(validPlaintext, validNonce);

            Assert.AreEqual(validCiphertext, ciphertext);
        }
Esempio n. 5
0
        public MailDto Save([FromBody] InputMailDto mailDto)
        {
            var isUpdatePassword = (mailDto.Id != 0 && !string.IsNullOrEmpty(mailDto.Password)) ||
                                   mailDto.Id == 0;

            var secret            = configuration.GetValue <string>("PasswordSecret");
            var encryptedPassword = encryption.Encrypt(mailDto.Password, secret);

            var mail = new Mail
            {
                Id           = mailDto.Id,
                EmailAddress = mailDto.EmailAddress,
                EnableSsl    = mailDto.EnableSsl,
                Host         = mailDto.Host,
                Name         = mailDto.Name,
                Password     = isUpdatePassword ? encryptedPassword : string.Empty,
                Port         = mailDto.Port,
                UserId       = user.Id
            };

            context.Update(mail);
            context.Entry(mail).Property(x => x.Password).IsModified = isUpdatePassword;
            context.SaveChanges();

            return(new MailDto
            {
                Id = mail.Id,
                EmailAddress = mail.EmailAddress,
                EnableSsl = mail.EnableSsl,
                Host = mail.Host,
                Name = mail.Name,
                Port = mail.Port
            });
        }
Esempio n. 6
0
        public void EncryptionProvider_EncryptSuccessfullyDecrypts_EncryptMethod()
        {
            EncryptionProvider cipher = new EncryptionProvider(validKey);

            string ciphertext = cipher.Encrypt(validPlaintext, validNonce);

            Assert.AreEqual(validCiphertext, ciphertext);
        }
Esempio n. 7
0
        public void MetroHmacSHA1Encryption_MarkerMetro_Failed()
        {
            string originalString = "MarkerMetro";
            string key            = "encryptionKey";

            Assert.ThrowsException <Exception>(() => EncryptionProvider.Encrypt(originalString, key, HashFunctionType.SHA1));
            Assert.ThrowsException <Exception>(() => EncryptionProvider.Decrypt(originalString, key, HashFunctionType.SHA1));
        }
        public void EncryptRoundTripv2(string data)
        {
            EncryptionProvider p = new EncryptionProvider();
            var cert             = this.certificateProvider.CreateSelfSignedCert("test");

            string encrypted = p.Encrypt(cert, data, 2);
            string decrypted = p.Decrypt(encrypted, _ => cert);

            Assert.AreEqual(data, decrypted);
        }
Esempio n. 9
0
        public void EncryptRoundTripv1(string data)
        {
            EncryptionProvider p = new EncryptionProvider();
            var cert             = this.certificateProvider.CreateSelfSignedCert("test", CertificateProvider.LithnetAccessManagerPasswordEncryptionEku);

            string encrypted = p.Encrypt(cert, data, 1);
            string decrypted = p.Decrypt(encrypted, _ => cert);

            Assert.AreEqual(data, decrypted);
        }
Esempio n. 10
0
        public void MetroEncryptionProvider_EncryptDecrypt_MD5_ShouldEqualOriginal()
        {
            string originalString = "MarkerMetro";
            string key            = "encryptionKey";

            //test using MD5 algorithm
            string encryptedString = EncryptionProvider.Encrypt(originalString, key);
            string decryptedString = EncryptionProvider.Decrypt(encryptedString, key);

            Assert.IsTrue(originalString == decryptedString);
        }
        private void GenerateUtility_class_UserPasswordAndName(out string nameCrypt, out string passwordCrypt)
        {
            string nameForEncription = Statics.GetUniqueKeyOriginal_BIASED(_rnd.Next(5, 8));
            string passForEncription = Statics.GetUniqueKeyOriginal_BIASED(_rnd.Next(5, 15));

            string encryptedName     = EncryptionProvider.Encrypt(nameForEncription);
            string encryptedPassword = EncryptionProvider.Encrypt(passForEncription);

            nameCrypt     = encryptedName;
            passwordCrypt = encryptedPassword;
        }
Esempio n. 12
0
        /// <summary>
        /// Test EncryptionProvider HMACSHA256 encrypt and decrypt.
        /// </summary>
        public void MetroEncryptionProvider_EncryptDecrypt_HMACSHA256_ShouldEqualOriginal()
        {
            string originalString = "MarkerMetro";
            string key            = "encryptionKey";

            //test using HMACSHA256 algorithm
            var encryptedString = EncryptionProvider.Encrypt(originalString, key, HashFunctionType.HMACSHA256, Encoding.UTF8.GetBytes("secret"));
            var decryptedString = EncryptionProvider.Decrypt(encryptedString, key, HashFunctionType.HMACSHA256, Encoding.UTF8.GetBytes("secret"));

            Assert.IsTrue(originalString == decryptedString);
        }
        public override void WriteLine(string value)
        {
            try
            {
                value = EncryptionProvider.Encrypt(value, CurrentApp.AppId.ToString());

                base.WriteLine(value);
            }
            catch
            {
            }
        }
Esempio n. 14
0
        public static void Encryption(EncryptionProvider provider)
        {
            var cipher_s = provider.Encrypt("192.168.1.22 2323 foo bar", Encoding.ASCII);

            File.WriteAllText("credwin.txt", cipher_s + "\n", Encoding.ASCII);

            string read_s = File.ReadAllText("credwin.txt", Encoding.ASCII);

            string plaintext = provider.Decrypt(read_s, Encoding.ASCII);

            Console.WriteLine(plaintext);
        }
Esempio n. 15
0
        public async Task <bool> ValidateUserPassword(long userId, string password)
        {
            ICollection <ValidationCodeResult> errors = new List <ValidationCodeResult>();

            string encryptedPassword = _encryptionProvider.Encrypt(password);

            var requestedtuser = await this.Connection.FirstOrDefaultAsync <TUser>(i => i.Id == userId);

            if (requestedtuser == null)
            {
                errors.Add(new ValidationCodeResult(ErrorCodes[EnumErrorCode.UserIdDoesNotExists, userId.ToString()]));
            }
            else
            {
                if (requestedtuser.Password == encryptedPassword)
                {
                    errors.Add(new ValidationCodeResult(ErrorCodes[EnumErrorCode.OldAndNewPwdNotSame]));
                }
            }

            /* throw error password is same or user does not exist, does not make sense to validate further */
            if (errors.Count > 0)
            {
                await this.ThrowEntityException(errors);
            }

            /* checked again if still an error */
            if (errors.Count > 0)
            {
                await this.ThrowEntityException(errors);
            }

            var existingReocrd = (await this.Connection
                                  .SelectAsync <IUserPasswordLog>(i => i.UserId == userId))
                                 .OrderByDescending(i => i.DateChanged)
                                 .Take(5)
                                 .FirstOrDefault(i => i.PreviousPassword == encryptedPassword);

            if (existingReocrd != null)
            {
                errors.Add(new ValidationCodeResult(ErrorCodes[EnumErrorCode.PasswordUsedBefore]));
            }

            if (errors.Count > 0)
            {
                await this.ThrowEntityException(errors);
            }
            return(true);
        }
Esempio n. 16
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Constructor. </summary>
        ///
        /// <remarks>   Aedmonds, 8/25/2017. </remarks>
        ///
        /// <param name="registerViewModel">    The register view model. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public Invitation(RegisterViewModel registerViewModel)
        {
            EncryptionProvider encProv = new EncryptionProvider();

            email       = registerViewModel.Email;
            password    = encProv.Encrypt(registerViewModel.Password);
            FirstName   = registerViewModel.FirstName;
            LastName    = registerViewModel.LastName;
            CompanyName = registerViewModel.CompanyName;
            Title       = registerViewModel.Title;
            Phone       = registerViewModel.Phone;
            Website     = registerViewModel.Website;
            DesignRole  = registerViewModel.DesignRole;
            status      = InvitationStatus.Pending;
        }
Esempio n. 17
0
        // Returns Success
        public bool Encrypt(Letter letter)
        {
            if (!letter.LetterMetadata.Encrypted)
            {
                letter.Body = EncryptionProvider.Encrypt(letter.Body);
                letter.LetterMetadata.Encrypted = true;
                letter.LetterMetadata.CustomFields[Constants.HeaderForEncrypted]   = true;
                letter.LetterMetadata.CustomFields[Constants.HeaderForEncryption]  = EncryptionProvider.Type;
                letter.LetterMetadata.CustomFields[Constants.HeaderForEncryptDate] = Time.GetDateTimeNow(Time.Formats.CatRFC3339);

                return(true);
            }

            return(false);
        }
Esempio n. 18
0
    private byte[] EncryptResponse(byte[] requestData, EncryptionProvider crpyter)
    {
        try
        {
            return(crpyter.Encrypt(requestData));
        }
        catch (CryptographicException ex)
        {
            if (CryptoError != null)
            {
                CryptoError(null, ex);
            }

            return(null);
        }
    }
        private static void LoginNavigationStarted(Uri url, object state)
        {
            FacebookOAuthResult result;

            // Check if we're waiting for user input or if login is complete
            if (_client.TryParseOAuthCallbackUrl(url, out result))
            {
                // Login complete
                if (result.IsSuccess)
                {
                    AccessToken         = result.AccessToken;
                    Expires             = result.Expires;
                    _client.AccessToken = AccessToken;
                    Settings.Set(TOKEN_KEY, EncryptionProvider.Encrypt(AccessToken, AppId));
                    Settings.Set(EXPIRY_DATE_BIN, Expires.ToBinary());
                }
                _web.Finish();
                if (_onHideUnity != null)
                {
                    _onHideUnity(false);
                }

                API("/me?fields=id,name", HttpMethod.GET, fbResult =>
                {
                    if (IsLoggedIn)
                    {
                        UserId   = fbResult.Json["id"] as string;
                        UserName = fbResult.Json["name"] as string;
                        Settings.Set(FBID_KEY, UserId);
                        Settings.Set(FBNAME_KEY, UserName);
                    }

                    if (state is FacebookDelegate)
                    {
                        JsonObject jResult = new JsonObject();
                        jResult.Add(new KeyValuePair <string, object>("authToken", AccessToken));
                        jResult.Add(new KeyValuePair <string, object>("authTokenExpiry", Expires.ToString()));

                        ((FacebookDelegate)state)(new FBResult()
                        {
                            Json = jResult,
                            Text = jResult.ToString()
                        });
                    }
                });
            }
        }
Esempio n. 20
0
    private byte[] EncryptRequest(Request request, EncryptionProvider crypter)
    {
        try
        {
            byte[] requestData = formatter.Format(request);
            return(crypter.Encrypt(requestData));
        }
        catch (CryptographicException ex)
        {
            if (CryptoError != null)
            {
                CryptoError(request, ex);
            }

            return(null);
        }
    }
Esempio n. 21
0
        // Returns Success
        public bool Encrypt(IMessage message)
        {
            var metadata = message.GetMetadata();

            if (!metadata.Encrypted)
            {
                message.Body       = EncryptionProvider.Encrypt(message.Body).Array;
                metadata.Encrypted = true;
                metadata.CustomFields[Constants.HeaderForEncrypted]   = true;
                metadata.CustomFields[Constants.HeaderForEncryption]  = EncryptionProvider.Type;
                metadata.CustomFields[Constants.HeaderForEncryptDate] = Time.GetDateTimeNow(Time.Formats.CatRFC3339);

                return(true);
            }

            return(false);
        }
Esempio n. 22
0
        public static void EncryptionFromFile(EncryptionProvider provider)
        {
            string plainfile     = "resources\\security-plain.xml";
            string encryptedfile = "resources\\security-enc.xml";
            string decryptedfile = "resources\\security-restored.txt";

            if (System.Environment.OSVersion.Platform == PlatformID.Unix)
            {
                plainfile     = plainfile.Replace("\\", "/");
                encryptedfile = encryptedfile.Replace("\\", "/");
                decryptedfile = decryptedfile.Replace("\\", "/");
            }

            var credstring = File.ReadAllText(plainfile, Encoding.UTF8);
            var cipher_s   = provider.Encrypt(credstring, Encoding.UTF8);

            File.WriteAllText(encryptedfile, cipher_s, Encoding.UTF8);

            string read_s    = File.ReadAllText(encryptedfile, Encoding.UTF8);
            string plaintext = provider.Decrypt(read_s, Encoding.UTF8);

            Console.WriteLine(plaintext);
            File.WriteAllText(decryptedfile, plaintext + "\n", Encoding.UTF8);

            var    doc = XDocument.Parse(plaintext);
            string module = "Click", store = "GRANTS", environment = "STAGING";

            var el       = doc.Descendants("Module").FirstOrDefault(e => e.Attribute("name").Value == module).Descendants("Store").FirstOrDefault(e => e.Attribute("name").Value == store).Descendants("Credential").FirstOrDefault(e => e.Attribute("environment").Value == environment);
            var username = el.Attribute("username").Value;
            var password = el.Attribute("password").Value;

            module   = "Epic";
            el       = doc.Descendants("Module").FirstOrDefault(e => e.Attribute("name").Value == module).Descendants("Credential").FirstOrDefault(e => e.Attribute("environment").Value == environment);
            username = el.Attribute("username").Value;
            password = el.Attribute("password").Value;

            module   = "OnBase";
            el       = doc.Descendants("Module").FirstOrDefault(e => e.Attribute("name").Value == module).Descendants("Credential").FirstOrDefault(e => e.Attribute("environment").Value == environment);
            username = el.Attribute("username").Value;
            password = el.Attribute("password").Value;
        }
Esempio n. 23
0
        /// <summary>
        /// Register an unique account.
        /// </summary>
        /// <param name="model">User details to register.</param>
        /// <returns>0 on failure, 1 on success, 2 on unexpected database error.</returns>
        public int Register(User model)
        {
            int  result     = 0;
            bool isUsername = false;

            if (model != null)
            {
                if (!string.IsNullOrEmpty(model.Username))
                {
                    isUsername = Regex.IsMatch(model.Username, @"^(?=.{3,32}$)(?![_-])[a-zA-Z0-9-_ ]+(?<![_-])$", RegexOptions.None);
                }
            }

            if (isUsername == true)
            {
                try
                {
                    using (DataConnection db = new DataConnection())
                    {
                        User query = (from user in db.User
                                      where user.Username == model.Username
                                      select user).SingleOrDefault();

                        if (query == null)
                        {
                            model.Password = EncryptionProvider.Encrypt(model.Password);
                            result         = db.Insert(model);
                        }
                    }
                }
                catch (Exception)
                {
                    result = 2;
                }
            }

            return(result);
        }
Esempio n. 24
0
        /// <summary>
        /// Sign an existing account in.
        /// </summary>
        /// <param name="model">User details to validate login.</param>
        /// <returns>Null on failure, User object on success.</returns>
        public User Login(User model)
        {
            User result = null;

            try
            {
                using (DataConnection db = new DataConnection())
                {
                    User query = (from user in db.User
                                  where user.Username == model.Username && user.Password == EncryptionProvider.Encrypt(model.Password)
                                  select user).SingleOrDefault();

                    if (query != null)
                    {
                        model.Id = query.Id;
                        result   = new User()
                        {
                            Id       = query.Id,
                            Username = query.Username,
                            Password = query.Password,
                            Role     = query.Role
                        };
                    }
                }
            }
            catch (Exception)
            {
                result = new User()
                {
                    Role = "Error"
                };
            }

            return(result);
        }
Esempio n. 25
0
        public void EncryptTest()
        {
            string userNamePayload = EncryptionProvider.Encrypt("Ji-Feng Tsai");

            Assert.IsNotNull(userNamePayload);
        }
Esempio n. 26
0
        public static void SaveSetting(string key, string setting)
        {
            var encrypted = EncryptionProvider.Encrypt(setting, CurrentApp.AppId.ToString());

            ApplicationData.Current.LocalSettings.Values[key] = encrypted;
        }