Esempio n. 1
0
        /// <summary>
        /// protect a spreadsheet with a password (not encrypted, just sets protect flags and the password.)
        /// </summary>
        /// <param name="password">password to set;Pass <code>null</code> to remove all protection</param>
        /// <param name="shouldProtectObjects">shouldProtectObjects are protected</param>
        /// <param name="shouldProtectScenarios">shouldProtectScenarios are protected</param>
        public void ProtectSheet(String password, bool shouldProtectObjects,
                                 bool shouldProtectScenarios)
        {
            if (password == null)
            {
                _passwordRecord        = null;
                _protectRecord         = null;
                _objectProtectRecord   = null;
                _scenarioProtectRecord = null;
                return;
            }

            ProtectRecord  prec = this.Protect;
            PasswordRecord pass = this.Password;

            prec.Protect  = true;
            pass.Password = (short)CryptoFunctions.CreateXorVerifier1(password);
            if (_objectProtectRecord == null && shouldProtectObjects)
            {
                ObjectProtectRecord rec = CreateObjectProtect();
                rec.Protect          = (true);
                _objectProtectRecord = rec;
            }
            if (_scenarioProtectRecord == null && shouldProtectScenarios)
            {
                ScenarioProtectRecord srec = CreateScenarioProtect();
                srec.Protect           = (true);
                _scenarioProtectRecord = srec;
            }
        }
Esempio n. 2
0
        public async Task <IResponse <string> > GetToken(PasswordRecord record)
        {
            if (record.Claims == null)
            {
                record.Claims = new List <Claim>();
            }
            if (record.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name) == null)
            {
                record.Claims.Add(new Claim(ClaimTypes.Name, record.UserName));
            }

            var result = new MethodResponse <string>()
                         .AsSucces();

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
                _issuer,
                _issuer,
                record.Claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: credentials
                );

            result.Data = new JwtSecurityTokenHandler().WriteToken(token);

            return(result);
        }
Esempio n. 3
0
        public async Task <IResponse> SetupPassword(PasswordRequest request)
        {
            var existingRecord = await _passwordsRepository
                                 .First(x => x.UserName == request.UserName);

            if (existingRecord != null)
            {
                throw new Exception($"User {request.UserName} is already registered.");
            }

            var(passwordHash, salt) = GenerateHash(request.Password, SaltLength, HashLength, Iterations);

            var record = new PasswordRecord()
            {
                PasswordHash = passwordHash,
                Salt         = salt,
                Iterations   = Iterations,
                UserName     = request.UserName,
                HashLength   = HashLength
            };


            await _passwordsRepository.Create(record);

            return(new MethodResponse()
            {
                Sucess = true,
                Errors = new List <ErrorResponse>()
            });
        }
Esempio n. 4
0
        private void setNewCurrentRecord(string mainTag)
        {
            currentRecord      = records[mainTag];
            RecordNameBox.Text = currentRecord.mainTag;

            foreach (var tag in tags)
            {
                tagList.Items.Add(tag);
            }

            for (int j = 0; j < currentRecord.tags.Count; j++)
            {
                var tag = currentRecord.tags[j];
                for (int i = 0; i < tagList.Items.Count; i++)
                {
                    if ((tagList.Items[i] as string).CompareTo(tag) == 0)
                    {
                        tagList.SetItemChecked(i, true);
                        break;
                    }
                }
            }

            textBox.Text = decrypt(currentRecord.crypt);
        }
Esempio n. 5
0
        /// <summary>
        /// protect a spreadsheet with a password (not encrypted, just sets protect flags and the password.)
        /// </summary>
        /// <param name="password">password to set;Pass <code>null</code> to remove all protection</param>
        /// <param name="shouldProtectObjects">shouldProtectObjects are protected</param>
        /// <param name="shouldProtectScenarios">shouldProtectScenarios are protected</param>
        public void ProtectSheet(String password, bool shouldProtectObjects,
                                 bool shouldProtectScenarios)
        {
            if (password == null)
            {
                _passwordRecord        = null;
                _protectRecord         = null;
                _objectProtectRecord   = null;
                _scenarioProtectRecord = null;
                return;
            }

            ProtectRecord  prec = this.Protect;
            PasswordRecord pass = this.Password;

            prec.Protect  = true;
            pass.Password = (PasswordRecord.HashPassword(password));
            if (_objectProtectRecord == null && shouldProtectObjects)
            {
                ObjectProtectRecord rec = CreateObjectProtect();
                rec.Protect          = (true);
                _objectProtectRecord = rec;
            }
            if (_scenarioProtectRecord == null && shouldProtectScenarios)
            {
                ScenarioProtectRecord srec = CreateScenarioProtect();
                srec.Protect           = (true);
                _scenarioProtectRecord = srec;
            }
        }
Esempio n. 6
0
        private bool ReadARecord(RecordStream rs)
        {
            switch (rs.PeekNextSid())
            {
            case ProtectRecord.sid:
                CheckNotPresent(_protectRecord);
                _protectRecord = rs.GetNext() as ProtectRecord;
                break;

            case ObjectProtectRecord.sid:
                CheckNotPresent(_objectProtectRecord);
                _objectProtectRecord = rs.GetNext() as ObjectProtectRecord;
                break;

            case ScenarioProtectRecord.sid:
                CheckNotPresent(_scenarioProtectRecord);
                _scenarioProtectRecord = rs.GetNext() as ScenarioProtectRecord;
                break;

            case PasswordRecord.sid:
                CheckNotPresent(_passwordRecord);
                _passwordRecord = rs.GetNext() as PasswordRecord;
                break;

            default:
                // all other record types are not part of the PageSettingsBlock
                return(false);
            }
            return(true);
        }
Esempio n. 7
0
 public bool IsValid(PasswordRecord record)
 {
     return(record.Password.Length >= record.Policy.Max &&
            ((record.Password[record.Policy.Min - 1] == record.Policy.Char &&
              record.Password[record.Policy.Max - 1] != record.Policy.Char) ||
             (record.Password[record.Policy.Min - 1] != record.Policy.Char &&
              record.Password[record.Policy.Max - 1] == record.Policy.Char)));
 }
Esempio n. 8
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            bool isApplySuccess = false;

            string strpwd         = pbPwd.Password;
            string strPrinterName = ((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter;
            string strDrvName     = "";

            if (false == common.GetPrinterDrvName(strPrinterName, ref strDrvName))
            {
                MessageBoxEx_Simple messageBox =
                    new MessageBoxEx_Simple((string)this.TryFindResource("ResStr_can_not_be_carried_out_due_to_software_has_error__please_try__again_after_reinstall_the_Driver_and_Virtual_Operation_Panel_"), (string)this.FindResource("ResStr_Error"));
                messageBox.Owner = App.Current.MainWindow;
                messageBox.ShowDialog();

                return;
            }

            if (strpwd.Length > 0)
            {
                PasswordRecord m_rec  = new PasswordRecord(strPrinterName, strpwd);
                AsyncWorker    worker = new AsyncWorker(this);

                if (worker.InvokeMethod <PasswordRecord>(strPrinterName, ref m_rec, DllMethodType.ConfirmPassword, this))
                {
                    if (null != m_rec && m_rec.CmdResult == EnumCmdResult._ACK)
                    {
                        ((MainWindow)App.Current.MainWindow).m_strPassword = strpwd;
                        isApplySuccess = true;
                    }
                }

                if (!isApplySuccess)
                {
                    ((MainWindow)App.Current.MainWindow).m_strPassword = "";
                    pbPwd.Focus();
                    pbPwd.SelectAll();
                    tbkErrorInfo.Foreground = new SolidColorBrush(Colors.Red);
                    tbkErrorInfo.Text       = (string)this.FindResource("ResStr_Authentication_error__please_enter_the_password_again_");
                }
                else
                {
                    this.DialogResult = true;
                    this.Close();
                }
            }
            else
            {
                tbkErrorInfo.Foreground = new SolidColorBrush(Colors.Red);
                tbkErrorInfo.Text       = (string)this.FindResource("ResStr_The_new_password_can_not_be_empty_");
            }
        }
        public async Task SavePassword()
        {
            if (appController.Busy)
            {
                return;
            }
            else
            {
                appController.EnableBusyState();
            }

            var vm = viewModelsController.GetViewModel <CreateViewModel>();

            if (string.IsNullOrEmpty(vm.Login) ||
                string.IsNullOrEmpty(vm.Name) ||
                string.IsNullOrEmpty(vm.Email) ||
                (string.IsNullOrEmpty(vm.Password) &&
                 string.IsNullOrEmpty(vm.CustomPassword)))
            {
                appController.DisableBusyState();
                return;
            }

            try
            {
                var modelToAdd = new PasswordRecord
                {
                    Email        = vm.Email,
                    Name         = vm.Name,
                    Password     = string.IsNullOrEmpty(vm.CustomPassword) ? vm.Password : vm.CustomPassword,
                    Lenght       = string.IsNullOrEmpty(vm.CustomPassword) ? vm.Password.Length : vm.CustomPassword.Length,
                    Login        = vm.Login,
                    LowerCases   = string.IsNullOrEmpty(vm.CustomPassword) ? passwordReviewer.CheckLowerCase(vm.Password) : passwordReviewer.CheckLowerCase(vm.CustomPassword),
                    UpperCases   = string.IsNullOrEmpty(vm.CustomPassword) ? passwordReviewer.CheckUpperCase(vm.Password) : passwordReviewer.CheckUpperCase(vm.CustomPassword),
                    NumbersCases = string.IsNullOrEmpty(vm.CustomPassword) ? passwordReviewer.CheckNumericCase(vm.Password) : passwordReviewer.CheckNumericCase(vm.CustomPassword),
                    SpecialCases = string.IsNullOrEmpty(vm.CustomPassword) ? passwordReviewer.CheckSpecialCase(vm.Password) : passwordReviewer.CheckSpecialCase(vm.CustomPassword),
                    PolishCases  = string.IsNullOrEmpty(vm.CustomPassword) ? passwordReviewer.CheckPolishCase(vm.Password) : passwordReviewer.CheckPolishCase(vm.CustomPassword),
                };

                await appRepository.CreatePassword(modelToAdd);

                appController.RefreshViewModels();
                appController.DisableBusyState();
                appController.ShowInfoPage("Hasło zapisane!", "Sprawdź Panel by zobaczyć wszystkie dane.");
            }
            catch (Exception)
            {
                appController.DisableBusyState();
                appController.ShowInfoPage("Hasło nie zostało zapisane!", "Spróbuj jeszcze raz.");
            }
        }
Esempio n. 10
0
        public bool apply()
        {
            bool isApplySuccess = false;

            string strPWD   = pbnewPWD.Password;
            string strCfPWD = pbConfirmPWD.Password;

            if (strPWD.Length > 0 && strPWD == strCfPWD)
            {
                if (strPWD.Length > 0)
                {
                    string         strPrinterName = ((MainWindow)App.Current.MainWindow).statusPanelPage.m_selectedPrinter;
                    PasswordRecord m_rec          = new PasswordRecord(strPrinterName, strPWD);
                    AsyncWorker    worker         = new AsyncWorker(Application.Current.MainWindow);

                    if (worker.InvokeMethod <PasswordRecord>(strPrinterName, ref m_rec, DllMethodType.SetPassword, this))
                    {
                        if (null != m_rec && m_rec.CmdResult == EnumCmdResult._ACK)
                        {
                            ((MainWindow)App.Current.MainWindow).m_strPassword = strCfPWD;
                            isApplySuccess = true;
                        }
                    }
                }

                if (isApplySuccess)
                {
                    ((MainWindow)App.Current.MainWindow).statusPanelPage.ShowMessage((string)this.FindResource("ResStr_Setting_Successfully_"), Brushes.Black);
                }
                else
                {
                    ((MainWindow)App.Current.MainWindow).statusPanelPage.ShowMessage((string)this.FindResource("ResStr_Setting_Fail"), Brushes.Red);
                }
            }
            else
            {
                if (strPWD.Length == 0)
                {
                    pbnewPWD.Focus();
                    VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, Application.Current.MainWindow, (string)this.FindResource("ResStr_The_new_password_can_not_be_empty_"), (string)this.FindResource("ResStr_Error"));
                }
                else if (strPWD != strCfPWD)
                {
                    pbnewPWD.Focus();
                    pbnewPWD.SelectAll();
                    VOP.Controls.MessageBoxEx.Show(VOP.Controls.MessageBoxExStyle.Simple, Application.Current.MainWindow, (string)this.FindResource("ResStr_The_passwords_you_entered__are_different__please_try_again_"), (string)this.FindResource("ResStr_Error"));
                }
            }

            return(isApplySuccess);
        }
        private Tuple <SyncDownRecord, SyncDownRecordMetaData> GenerateRecord(PasswordRecord record,
                                                                              KeyType keyType,
                                                                              long revision)
        {
            var sdr = new SyncDownRecord
            {
                RecordUid          = record.Uid,
                Version            = 2,
                Revision           = revision,
                ClientModifiedTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
                Shared             = keyType == KeyType.DataKey
            };
            var data = record.ExtractRecordData();

            using (var ms = new MemoryStream())
            {
                _dataSerializer.WriteObject(ms, data);
                sdr.Data = CryptoUtils.EncryptAesV1(ms.ToArray(), record.RecordKey).Base64UrlEncode();
            }

            if (record.Attachments.Count > 0)
            {
                var extra = record.ExtractRecordExtra();
                using (var ms = new MemoryStream())
                {
                    _extraSerializer.WriteObject(ms, extra);
                    sdr.Extra = CryptoUtils.EncryptAesV1(ms.ToArray(), record.RecordKey).Base64UrlEncode();
                }
            }

            SyncDownRecordMetaData sdrmd = null;

            if (keyType == KeyType.DataKey || keyType == KeyType.PrivateKey)
            {
                sdrmd = new SyncDownRecordMetaData
                {
                    RecordUid     = record.Uid,
                    Owner         = keyType == KeyType.DataKey,
                    CanShare      = keyType == KeyType.DataKey,
                    CanEdit       = keyType == KeyType.DataKey,
                    RecordKeyType = (int)keyType
                };
                sdrmd.RecordKey =
                    (keyType == KeyType.DataKey
                        ? CryptoUtils.EncryptAesV1(record.RecordKey, DataKey)
                        : CryptoUtils.EncryptRsa(record.RecordKey, PublicKey)).Base64UrlEncode();
            }

            return(new Tuple <SyncDownRecord, SyncDownRecordMetaData>(sdr, sdrmd));
        }
Esempio n. 12
0
        private void GetRecordsFromFile(string str)
        {
            using (var sr = new StringReader(str))
            {
                int            counter   = 0;
                var            line      = sr.ReadLine();
                string         pwdLine   = null;
                string         MainTag   = null;
                string         cryptLine = null;
                PasswordRecord current   = null;

                while (line != null)
                {
                    line = line.Trim();

                    if (line == "" && counter > 2)
                    {
                        counter = 0;
                        line    = sr.ReadLine();
                        continue;
                    }

                    switch (counter)
                    {
                    case 0:
                        MainTag = line;
                        break;

                    case 1:
                        cryptLine = line;
                        break;

                    case 2:
                        pwdLine = line;
                        current = new PasswordRecord(pwdLine, cryptLine, MainTag);
                        records.Add(MainTag, current);
                        break;

                    default:
                        current.tags.Add(line);
                        break;
                    }

                    counter++;
                    line = sr.ReadLine();
                }
            }
        }
Esempio n. 13
0
        public void TestProtectSheet()
        {
            short        expected = unchecked ((short)0xfef1);
            HSSFWorkbook wb       = new HSSFWorkbook();
            HSSFSheet    s        = (HSSFSheet)wb.CreateSheet();

            s.ProtectSheet("abcdefghij");
            NPOI.HSSF.Model.Sheet sheet   = s.Sheet;
            ProtectRecord         Protect = sheet.Protect;
            PasswordRecord        pass    = sheet.Password;

            Assert.IsTrue(Protect.Protect, "Protection should be on");
            Assert.IsTrue(sheet.IsProtected[1], "object Protection should be on");
            Assert.IsTrue(sheet.IsProtected[2], "scenario Protection should be on");
            Assert.AreEqual(expected, pass.Password, "well known value for top secret hash should be " + NPOI.Util.StringUtil.ToHexString(expected).Substring(4));
        }
Esempio n. 14
0
        private void save()
        {
            if (currentRecord == null)
            {
                if (RecordNameBox.Text.Length > 0)
                {
                    currentRecord = new PasswordRecord(crypt(""), crypt(textBox.Text), RecordNameBox.Text);
                    records.Add(currentRecord.mainTag, currentRecord);
                }
                else
                {
                    MessageBox.Show("Извините, необходимо ввести имя записи, по которой вы будете искать её в дальнейшем");
                }
            }
            else
            {
                var newMainTag = RecordNameBox.Text.Trim();

                if (newMainTag.Length == 0)
                {
                    if (MessageBox.Show("Вы ввели пустое имя записи.\r\nВы уверены, что хотите удалить запись?", "Удаление записи", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != System.Windows.Forms.DialogResult.Yes)
                    {
                        return;
                    }
                }

                if (newMainTag != currentRecord.mainTag)
                {
                    var oldCR = currentRecord;
                    records.Remove(oldCR.mainTag);

                    if (newMainTag.Length > 0)
                    {
                        currentRecord      = new PasswordRecord(oldCR.pwd, crypt(textBox.Text), newMainTag);
                        currentRecord.tags = oldCR.tags;
                        records.Add(currentRecord.mainTag, currentRecord);
                        setNewCurrentRecord(currentRecord.mainTag);
                    }
                }
                else
                {
                    currentRecord.crypt = crypt(textBox.Text);
                }
            }

            recordsToFile();
        }
Esempio n. 15
0
        public void PasswordRecord_Should_Be_Invalid_When_Official_Toboggan_Policy_Is_Not_Respected()
        {
            var record = new PasswordRecord
            {
                Policy = new PasswordPolicy
                {
                    Min  = 1,
                    Max  = 3,
                    Char = 'b'
                },
                Password = "******"
            };
            var sut = new OfficialTobogganCorporatePolicyValidator();

            var result = sut.IsValid(record);

            result.Should().BeFalse();
        }
Esempio n. 16
0
        public void PasswordRecord_Should_Be_Invalid_When_Sled_Rental_Policy_Is_Not_Respected()
        {
            var record = new PasswordRecord
            {
                Policy = new PasswordPolicy
                {
                    Min  = 1,
                    Max  = 3,
                    Char = 'b'
                },
                Password = "******"
            };
            var sut = new SledRentalPasswordValidator();

            var result = sut.IsValid(record);

            result.Should().BeFalse();
        }
Esempio n. 17
0
        private async Task AddRecordCommand(AddRecordOptions options)
        {
            if (!TryResolvePath(options.Folder, out FolderNode node))
            {
                Console.WriteLine(string.Format("Cannot resolve folder {0}", options.Folder));
                return;
            }

            var record = new PasswordRecord
            {
                Title    = options.Title,
                Login    = options.Login,
                Password = options.Password,
                Link     = options.Url,
                Notes    = options.Notes
            };

            if (string.IsNullOrEmpty(record.Password) && options.Generate)
            {
                record.Password = CryptoUtils.GenerateUid();
            }
            if (!options.Force)
            {
                if (string.IsNullOrEmpty(record.Login))
                {
                    Console.Write("..." + "Login: "******"..." + "Password: "******"..." + "Login URL: ".PadRight(16));
                    record.Link = Console.ReadLine();
                }
            }

            await _vault.AddRecord(record, node.FolderUid);
        }
Esempio n. 18
0
        public void Should_EncodeToBase64StringAndDecode_When_RecordWithGivenParametersAreSpecified()
        {
            int v  = 1;
            var nS = Bytes.FromString("7+t+vbhC1M1+TzgGJ1n4ZBWCyzuUXcz61nxTvDIWN7A=", StringEncoding.BASE64);
            var nC = Bytes.FromString("FB/nl1UbJwBI3hM80+N53vSljZGu0ZJ/y6PhOvcnd8U=", StringEncoding.BASE64);
            var t0 = Bytes.FromString("BFVFSh2DlZkRQRjl9kLZWRqAA6dSFXU1TVymEqcM06fIorhK0SeDVSbA1390FDp9btM0RgztQAeYvZuH3/2SEvw=", StringEncoding.BASE64);
            var t1 = Bytes.FromString("BEUyxTjawlSTQnms5yuJwvIgNJDlpC7X71S+x8aOIHmruHxNIk+8bW85Wk9Dh/5XidFgL5AB266k9tjs5dApm6w=", StringEncoding.BASE64);

            var record = new PasswordRecord(nS, nC, t0, t1, v);

            var str = record.EncodeToBase64();

            var decodedRecord = PasswordRecord.DecodeFromBase64(str);

            Assert.Equal(decodedRecord.Version, v);
            Assert.Equal(decodedRecord.ServerNonce, nS);
            Assert.Equal(decodedRecord.ClientNonce, nC);
            Assert.Equal(decodedRecord.RecordT0, t0);
            Assert.Equal(decodedRecord.RecordT1, t1);
        }
Esempio n. 19
0
        public Task <int> CreatePassword(PasswordRecord record)
        {
            pmContext.Passwords.Add(new PasswordRecord
            {
                Name         = cipherService.Encrypt(record.Name),
                Password     = cipherService.Encrypt(record.Password),
                Lenght       = record.Lenght,
                Login        = cipherService.Encrypt(record.Login),
                LowerCases   = record.LowerCases,
                UpperCases   = record.UpperCases,
                NumbersCases = record.NumbersCases,
                PolishCases  = record.PolishCases,
                SpecialCases = record.SpecialCases,
                Email        = cipherService.Encrypt(record.Email),
                Created      = DateTime.Now,
                CreatedBy    = Environment.UserName
            });

            return(pmContext.SaveChangesAsync());
        }
Esempio n. 20
0
        public void Should_DecodeFromGivenBase64String()
        {
            var str = "MIHNAgEBBCBflyzZDaDN0ww2fTrLO+THRSgAc3G+lq7dtFe/GNQaYAQ" +
                      "gQjHih3UMR3exo3rL7WqZ0bqKT+InhzNCcobfZQvpSq0EQQRkcIpfJlCpOn3A" +
                      "f/9gSup3/eb2Dvy8B4zLsIE3MHQH71Kw0B4AaTU19LJexnjub9KKhNSQGeYHR" +
                      "KIFUBYviMktBEEETpeGtp1awNv9OaE73fqi73Iy4EcG9RVK7xI1XOAMJZpait" +
                      "qRO/FEYbx05lrEtRN3E5HtOGt1cyD1mJX1q/8Prw==";

            var decodedRecord = PasswordRecord.DecodeFromBase64(str);

            var nS = Bytes.FromString("5f972cd90da0cdd30c367d3acb3be4c74528007371be96aeddb457bf18d41a60", StringEncoding.HEX);
            var nC = Bytes.FromString("4231e287750c4777b1a37acbed6a99d1ba8a4fe2278733427286df650be94aad", StringEncoding.HEX);
            var t0 = Bytes.FromString("0464708a5f2650a93a7dc07fff604aea77fde6f60efcbc078ccbb08137307407ef52b0d01e00693535f4b25ec678ee6fd28a84d49019e60744a20550162f88c92d", StringEncoding.HEX);
            var t1 = Bytes.FromString("044e9786b69d5ac0dbfd39a13bddfaa2ef7232e04706f5154aef12355ce00c259a5a8ada913bf14461bc74e65ac4b513771391ed386b757320f59895f5abff0faf", StringEncoding.HEX);

            Assert.Equal(1, decodedRecord.Version);
            Assert.Equal(nS, decodedRecord.ServerNonce);
            Assert.Equal(nC, decodedRecord.ClientNonce);
            Assert.Equal(t0, decodedRecord.RecordT0);
            Assert.Equal(t1, decodedRecord.RecordT1);
        }
Esempio n. 21
0
        private async Task UpdateRecordCommand(UpdateRecordOptions options)
        {
            PasswordRecord record = null;

            if (_vault.TryGetRecord(options.RecordId, out record))
            {
            }
            else if (TryResolvePath(options.RecordId, out FolderNode node, out string title))
            {
                foreach (var uid in node.Records)
                {
                    if (_vault.TryGetRecord(uid, out PasswordRecord r))
                    {
                        if (string.Compare(title, r.Title) == 0)
                        {
                            record = r;
                            break;
                        }
                    }
                }
            }
Esempio n. 22
0
 protected bool Equals(PasswordRecord other)
 {
     return(string.Equals(Name, other.Name) && string.Equals(Value, other.Value));
 }
 /// <summary>
 /// Set password data for update
 /// </summary>
 /// <param name="record"></param>
 public void SetPasswordData(PasswordRecord record)
 {
     this.Password = record;
     this.SetCaption(record.GetCaption());
     this.SetID(record.GetID());
     this.SetPassword(record.GetPassword());
     this.SetDescription(record.GetDescription());
 }
 /// <summary>
 /// If OK button is clicked, try to make 
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void button_NewPassword_OK_Click(object sender, EventArgs e)
 {
     // If password is being newly created
     if (this.Password == null)
     {
         this.Password = new PasswordRecord();
         this.Password.SetHeaderData(this.textBox_NewPassword_Caption.Text, DateTime.UtcNow, DateTime.UtcNow);
     }
     // If password is being updated
     else
     {
         this.Password.SetHeaderData(this.textBox_NewPassword_Caption.Text, this.Password.GetCreateDate(), DateTime.UtcNow);
     }
     this.Password.SetPrivateData(this.textBox_NewPassword_ID.Text, this.textBox_NewPassword_Password.Text, this.textBox_NewPassword_Memo.Text);
     this.DialogResult = DialogResult.OK;
     this.Close();
 }
        public SyncDownResponse GetSyncDownResponse()
        {
            var record1 = new PasswordRecord
            {
                Uid       = CryptoUtils.GenerateUid(),
                RecordKey = CryptoUtils.GenerateEncryptionKey(),
                Title     = "Record 1",
                Login     = "******",
                Password  = "******",
                Link      = "https://google.com",
                Notes     = "note1"
            };

            record1.Custom.Add(new CustomField {
                Name = "name1", Value = "value1"
            });
            record1.Attachments.Add(new AttachmentFile
            {
                Id   = "ABCDEFGH",
                Name = "Attachment 1",
                Key  = CryptoUtils.GenerateEncryptionKey().Base64UrlEncode(),
                Size = 1000
            });

            var record2 = new PasswordRecord
            {
                Uid       = CryptoUtils.GenerateUid(),
                RecordKey = CryptoUtils.GenerateEncryptionKey(),
                Title     = "Record 2",
                Login     = "******",
                Password  = "******",
                Link      = "https://google.com",
                Notes     = "note2"
            };
            var record3 = new PasswordRecord
            {
                Uid       = CryptoUtils.GenerateUid(),
                RecordKey = CryptoUtils.GenerateEncryptionKey(),
                Title     = "Record 3",
                Login     = "******",
                Password  = "******",
                Link      = "https://google.com",
            };

            var sharedFolder1 = new SharedFolder
            {
                Uid                  = CryptoUtils.GenerateUid(),
                SharedFolderKey      = CryptoUtils.GenerateEncryptionKey(),
                DefaultManageRecords = false,
                DefaultManageUsers   = false,
                DefaultCanEdit       = false,
                DefaultCanShare      = false,
                Name                 = "Shared Folder 1",
            };

            var sharedFolder2 = new SharedFolder
            {
                Uid                  = CryptoUtils.GenerateUid(),
                SharedFolderKey      = CryptoUtils.GenerateEncryptionKey(),
                DefaultManageRecords = true,
                DefaultManageUsers   = true,
                DefaultCanEdit       = false,
                DefaultCanShare      = false,
                Name                 = "Shared Folder 2",
            };

            var team1 = new Team
            {
                TeamUid       = CryptoUtils.GenerateUid(),
                TeamKey       = CryptoUtils.GenerateEncryptionKey(),
                Name          = "Team 1",
                RestrictEdit  = true,
                RestrictShare = true,
                RestrictView  = false,
            };

            var userFolder1 = new FolderNode
            {
                FolderUid  = CryptoUtils.GenerateUid(),
                Name       = "User Folder 1",
                FolderType = FolderType.UserFolder,
            };

            var(r1, md1) = GenerateRecord(record1, KeyType.DataKey, 10);
            var(r2, md2) = GenerateRecord(record2, KeyType.PrivateKey, 11);
            var(r3, _)   = GenerateRecord(record3, KeyType.NoKey, 12);
            var sf1 = GenerateSharedFolder(sharedFolder1, 12, new[] { record1 }, new[] { team1 }, true);
            var sf2 = GenerateSharedFolder(sharedFolder2, 12, new[] { record3 }, new[] { team1 }, false);
            var t1  = GenerateTeam(team1, KeyType.DataKey, new[] { sharedFolder1, sharedFolder2 });
            var uf1 = GenerateUserFolder(userFolder1, 14);

            var sdr = new SyncDownResponse
            {
                result                  = "success",
                fullSync                = true,
                revision                = Revision,
                records                 = new[] { r1, r2, r3 },
                recordMetaData          = new[] { md1, md2 },
                sharedFolders           = new[] { sf1, sf2 },
                teams                   = new[] { t1 },
                userFolders             = new[] { uf1 },
                userFolderSharedFolders = new[]
                {
                    new SyncDownUserFolderSharedFolder {
                        SharedFolderUid = sharedFolder1.Uid
                    }
                },
                userFolderRecords = new[]
                {
                    new SyncDownFolderRecord {
                        RecordUid = r1.RecordUid
                    },
                    new SyncDownFolderRecord {
                        RecordUid = r2.RecordUid, FolderUid = userFolder1.FolderUid
                    },
                    new SyncDownFolderRecord {
                        RecordUid = r1.RecordUid, FolderUid = sharedFolder1.Uid
                    },
                    new SyncDownFolderRecord {
                        RecordUid = r3.RecordUid, FolderUid = sharedFolder1.Uid
                    },
                }
            };


            return(sdr);
        }
Esempio n. 26
0
 bool ValidatePasswordRecordV2(PasswordRecord record)
 {
     // xor - char can only be in 1 position
     return((record.Password[record.Minimum - 1] == record.Character) ^ (record.Password[record.Maximum - 1] == record.Character));
 }
Esempio n. 27
0
        private static async Task Main()
        {
            Console.CancelKeyPress += (s, e) => { Environment.Exit(-1); };

            // Keeper SDK needs a storage to save configuration
            // such as: last login name, device token, etc
            var configuration = new JsonConfigurationStorage("test.json");


            var prompt = "Enter Email Address: ";

            if (!string.IsNullOrEmpty(configuration.LastLogin))
            {
                Console.WriteLine($"Default Email Address: {configuration.LastLogin}");
            }

            Console.Write(prompt);
            var username = Console.ReadLine();

            if (string.IsNullOrEmpty(username))
            {
                if (string.IsNullOrEmpty(configuration.LastLogin))
                {
                    Console.WriteLine("Bye.");
                    return;
                }

                username = configuration.LastLogin;
            }

            var inReadLine = false;

            var authFlow = new AuthSync(configuration);

            authFlow.UiCallback = new AuthSyncCallback(() =>
            {
                if (!inReadLine)
                {
                    return;
                }
                if (authFlow.Step.State == AuthState.Connected || authFlow.Step.State == AuthState.Error)
                {
                    Console.WriteLine("Press <Enter>");
                }
                else
                {
                    PrintStepHelp(authFlow.Step);
                    PrintStepPrompt(authFlow.Step);
                }
            },
                                                       Console.WriteLine);

            // Login to Keeper
            Console.WriteLine("Logging in...");

            var lastState = authFlow.Step.State;
            await authFlow.Login(username);

            while (!authFlow.IsCompleted)
            {
                if (authFlow.Step.State != lastState)
                {
                    PrintStepHelp(authFlow.Step);
                }

                lastState = authFlow.Step.State;
                PrintStepPrompt(authFlow.Step);
                inReadLine = true;
                var cmd = ReadInput();
                inReadLine = false;
                if (string.IsNullOrEmpty(cmd))
                {
                    continue;
                }

                try
                {
                    await ProcessCommand(authFlow, cmd);
                }
                catch (KeeperAuthFailed)
                {
                    Console.WriteLine("Invalid username or password");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            if (authFlow.Step is ErrorStep es)
            {
                Console.WriteLine(es.Message);
            }
            if (!authFlow.IsAuthenticated())
            {
                return;
            }

            var auth  = authFlow;
            var vault = new VaultOnline(auth);

            Console.WriteLine("\nRetrieving records...");
            await vault.SyncDown();

            Console.WriteLine($"Hello {username}!");
            Console.WriteLine($"Vault has {vault.RecordCount} records.");

            // Find record with title "Google"
            var search = vault.Records.FirstOrDefault(x => string.Compare(x.Title, "Google", StringComparison.InvariantCultureIgnoreCase) == 0);

            // Create a record if it does not exist.
            if (search == null)
            {
                search = new PasswordRecord
                {
                    Title    = "Google",
                    Login    = "******",
                    Password = "******",
                    Link     = "https://google.com",
                    Notes    = "Stores google credentials"
                };
                search = await vault.CreateRecord(search);
            }

            var nsd3 = vault.LoadNonSharedData <NonSharedData3>(search.Uid);

            nsd3.Data1 = "1";
            nsd3.Data3 = "3";
            await vault.StoreNonSharedData(search.Uid, nsd3);

            var nsd2 = vault.LoadNonSharedData <NonSharedData2>(search.Uid);

            nsd2.Data2 = "2";
            await vault.StoreNonSharedData(search.Uid, nsd2);

            // Update record.
            search.SetCustomField("Security Token", "11111111");
            search = await vault.UpdateRecord(search);

            // find file attachment.
            var attachment = search.Attachments
                             .FirstOrDefault(x => string.Compare(x.Title, "google", StringComparison.InvariantCultureIgnoreCase) == 0);

            if (attachment == null)
            {
                // Upload local file "google.txt".
                // var uploadTask = new FileAttachmentUploadTask("google.txt")
                var fileContent = Encoding.UTF8.GetBytes("Google");
                using (var stream = new MemoryStream(fileContent))
                {
                    var uploadTask = new AttachmentUploadTask(stream)
                    {
                        Title    = "Google",
                        Name     = "google.txt",
                        MimeType = "text/plain"
                    };
                    await vault.UploadAttachment(search, uploadTask);

                    await vault.UpdateRecord(search, false);
                }
            }
            else
            {
                // Download attachment into the stream
                // The stream could be a local file "google.txt"
                // using (var stream = File.OpenWrite("google.txt"))
                using (var stream = new MemoryStream())
                {
                    await vault.DownloadAttachment(search, attachment.Id, stream);
                }

                // Delete attachment. Remove it from the record
                search.Attachments.Remove(attachment);
                await vault.UpdateRecord(search, false);
            }

            // Find shared folder with name "Google".
            var sharedFolder = vault.SharedFolders
                               .FirstOrDefault(x => string.Compare(x.Name, "Google", StringComparison.InvariantCultureIgnoreCase) == 0);

            if (sharedFolder == null)
            {
                // Create shared folder.
                var folder = await vault.CreateFolder("Google",
                                                      null,
                                                      new SharedFolderOptions
                {
                    ManageRecords = true,
                    ManageUsers   = false,
                    CanEdit       = false,
                    CanShare      = false,
                });

                vault.TryGetSharedFolder(folder.FolderUid, out sharedFolder);
            }

            // Add user to shared folder.
            try
            {
                await vault.PutUserToSharedFolder(sharedFolder.Uid,
                                                  "*****@*****.**",
                                                  UserType.User,
                                                  new SharedFolderUserOptions
                {
                    ManageRecords = false,
                    ManageUsers   = false,
                });
            }
            catch (Exception e)
            {
                Console.WriteLine($"Add user to Shared Folder error: {e.Message}");
            }


            // Add record to shared folder.
            await vault.MoveRecords(new[] { new RecordPath {
                                                RecordUid = search.Uid
                                            } }, sharedFolder.Uid, true);

            if (auth.AuthContext.IsEnterpriseAdmin)
            {
                // Load enterprise data.
                var enterprise = new EnterpriseData(auth);
                await enterprise.GetEnterpriseData();

                // Find team with name "Google".
                var team = enterprise.Teams
                           .FirstOrDefault(x => string.Compare(x.Name, "Google", StringComparison.InvariantCultureIgnoreCase) == 0);
                if (team == null)
                {
                    // Create team.
                    team = await enterprise.CreateTeam(new EnterpriseTeam
                    {
                        Name            = "Google",
                        RestrictEdit    = false,
                        RestrictSharing = true,
                        RestrictView    = false,
                    });
                }

                if (team != null)
                {
                    // Add users to the "Google" team.
                    await enterprise.AddUsersToTeams(
                        new[] { "*****@*****.**", "*****@*****.**" },
                        new[] { team.Uid },
                        Console.WriteLine);
                }
            }

            Console.WriteLine("Press any key to quit");
            Console.ReadKey();
        }
Esempio n. 28
0
        public bool IsValid(PasswordRecord record)
        {
            var count = record.Password.Count(x => x == record.Policy.Char);

            return(count >= record.Policy.Min && count <= record.Policy.Max);
        }
Esempio n. 29
0
        bool ValidatePasswordRecordV1(PasswordRecord record)
        {
            var characterCount = record.Password.Count(c => c == record.Character);

            return(characterCount > 0 && record.Minimum <= characterCount && characterCount <= record.Maximum);
        }