Represents an in-memory encrypted string.
        internal static PwgError Generate(out ProtectedString psOut,
			PwProfile pwProfile, CryptoRandomStream crsRandomSource)
        {
            psOut = ProtectedString.Empty;
            if(pwProfile.Length == 0) return PwgError.Success;

            PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString());
            char[] vGenerated = new char[pwProfile.Length];

            PwGenerator.PrepareCharSet(pcs, pwProfile);

            for(int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex)
            {
                char ch = PwGenerator.GenerateCharacter(pwProfile, pcs,
                    crsRandomSource);

                if(ch == char.MinValue)
                {
                    Array.Clear(vGenerated, 0, vGenerated.Length);
                    return PwgError.TooFewCharacters;
                }

                vGenerated[nIndex] = ch;
            }

            byte[] pbUtf8 = StrUtil.Utf8.GetBytes(vGenerated);
            psOut = new ProtectedString(true, pbUtf8);
            MemUtil.ZeroByteArray(pbUtf8);
            Array.Clear(vGenerated, 0, vGenerated.Length);

            return PwgError.Success;
        }
Example #2
0
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			Debug.Assert(psToCopy != null);
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");

			if(bIsEntryInfo && !AppPolicy.Try(AppPolicyId.CopyToClipboard))
				return false;

			string strData = SprEngine.Compile(psToCopy.ReadString(), false,
				peEntryInfo, pwReferenceSource, false, false);

			try
			{
				ClipboardUtil.Clear();

				DataObject doData = CreateProtectedDataObject(strData);
				Clipboard.SetDataObject(doData);

				m_pbDataHash32 = HashClipboard();
				m_strFormat = null;

				RaiseCopyEvent(bIsEntryInfo, strData);
			}
			catch(Exception) { Debug.Assert(false); return false; }

			if(peEntryInfo != null) peEntryInfo.Touch(false);

			// SprEngine.Compile might have modified the database
			Program.MainForm.UpdateUI(false, null, false, null, false, null, false);

			return true;
		}
		internal static string ShowAndRestore(ProtectedString psWord,
			bool bCenterScreen, bool bSetForeground, uint uCharCount, bool? bInitHide)
		{
			IntPtr h = IntPtr.Zero;
			try { h = NativeMethods.GetForegroundWindowHandle(); }
			catch(Exception) { Debug.Assert(false); }

			CharPickerForm dlg = new CharPickerForm();
			dlg.InitEx(psWord, bCenterScreen, bSetForeground, uCharCount, bInitHide);

			DialogResult dr = dlg.ShowDialog();

			ProtectedString ps = dlg.SelectedCharacters;
			string strRet = null;
			if((dr == DialogResult.OK) && (ps != null)) strRet = ps.ReadString();

			UIUtil.DestroyForm(dlg);

			try
			{
				if(h != IntPtr.Zero)
					NativeMethods.EnsureForegroundWindow(h);
			}
			catch(Exception) { Debug.Assert(false); }

			return strRet;
		}
Example #4
0
		public static PwgError Generate(out ProtectedString psOut,
			PwProfile pwProfile, byte[] pbUserEntropy,
			CustomPwGeneratorPool pwAlgorithmPool)
		{
			Debug.Assert(pwProfile != null);
			if(pwProfile == null) throw new ArgumentNullException("pwProfile");

			PwgError e = PwgError.Unknown;
			CryptoRandomStream crs = null;
			byte[] pbKey = null;
			try
			{
				crs = CreateRandomStream(pbUserEntropy, out pbKey);

				if(pwProfile.GeneratorType == PasswordGeneratorType.CharSet)
					e = CharSetBasedGenerator.Generate(out psOut, pwProfile, crs);
				else if(pwProfile.GeneratorType == PasswordGeneratorType.Pattern)
					e = PatternBasedGenerator.Generate(out psOut, pwProfile, crs);
				else if(pwProfile.GeneratorType == PasswordGeneratorType.Custom)
					e = GenerateCustom(out psOut, pwProfile, crs, pwAlgorithmPool);
				else { Debug.Assert(false); psOut = ProtectedString.Empty; }
			}
			finally
			{
				if(crs != null) crs.Dispose();
				if(pbKey != null) MemUtil.ZeroByteArray(pbKey);
			}

			return e;
		}
		public static PwgError Generate(ProtectedString psOutBuffer,
			PwProfile pwProfile, CryptoRandomStream crsRandomSource)
		{
			if(pwProfile.Length == 0) return PwgError.Success;

			PwCharSet pcs = new PwCharSet(pwProfile.CharSet.ToString());
			char[] vGenerated = new char[pwProfile.Length];

			PwGenerator.PrepareCharSet(pcs, pwProfile);

			for(int nIndex = 0; nIndex < (int)pwProfile.Length; ++nIndex)
			{
				char ch = PwGenerator.GenerateCharacter(pwProfile, pcs,
					crsRandomSource);

				if(ch == char.MinValue)
				{
					Array.Clear(vGenerated, 0, vGenerated.Length);
					return PwgError.TooFewCharacters;
				}

				vGenerated[nIndex] = ch;
			}

			byte[] pbUTF8 = Encoding.UTF8.GetBytes(vGenerated);
			psOutBuffer.SetString(Encoding.UTF8.GetString(pbUTF8, 0, pbUTF8.Length));
			Array.Clear(pbUTF8, 0, pbUTF8.Length);
			Array.Clear(vGenerated, 0, vGenerated.Length);

			return PwgError.Success;
		}
Example #6
0
		public static bool Copy(ProtectedString psToCopy, bool bIsEntryInfo,
			PwEntry peEntryInfo, PwDatabase pwReferenceSource)
		{
			if(psToCopy == null) throw new ArgumentNullException("psToCopy");
			return Copy(psToCopy.ReadString(), true, bIsEntryInfo, peEntryInfo,
				pwReferenceSource, IntPtr.Zero);
		}
Example #7
0
        public void InitEx(ProtectedString psWord, bool bCenterScreen, bool bSetForeground)
        {
            m_psWord = psWord;

            if(bCenterScreen) this.StartPosition = FormStartPosition.CenterScreen;

            m_bSetForeground = bSetForeground;
        }
Example #8
0
		private void SetKey(byte[] pbPasswordUtf8)
		{
			Debug.Assert(pbPasswordUtf8 != null);
			if(pbPasswordUtf8 == null) throw new ArgumentNullException("pbPasswordUtf8");

			SHA256Managed sha256 = new SHA256Managed();
			byte[] pbRaw = sha256.ComputeHash(pbPasswordUtf8);

			m_psPassword = new ProtectedString(true, pbPasswordUtf8);
			m_pbKeyData = new ProtectedBinary(true, pbRaw);
		}
Example #9
0
        /// <summary>
        /// Initialize the dialog. Needs to be called before the dialog is shown.
        /// </summary>
        /// <param name="vStringDict">String container. Must not be <c>null</c>.</param>
        /// <param name="strStringName">Initial name of the string. May be <c>null</c>.</param>
        /// <param name="psStringValue">Initial value. May be <c>null</c>.</param>
        public void InitEx(ProtectedStringDictionary vStringDict, string strStringName,
            ProtectedString psStringValue, PwDatabase pwContext)
        {
            Debug.Assert(vStringDict != null); if(vStringDict == null) throw new ArgumentNullException("vStringDict");
            m_vStringDict = vStringDict;

            m_strStringName = strStringName;
            m_psStringValue = psStringValue;

            m_pwContext = pwContext;
        }
		internal static ProtectedString GetKeyParts(byte[] pbPasswordUtf8, out ProtectedBinary pbKeyData)
		{
			Debug.Assert(pbPasswordUtf8 != null);
			if(pbPasswordUtf8 == null) throw new ArgumentNullException("pbPasswordUtf8");

			SHA256Managed sha256 = new SHA256Managed();
			byte[] pbRaw = sha256.ComputeHash(pbPasswordUtf8);

			var psPassword = new ProtectedString(true, pbPasswordUtf8);
			pbKeyData = new ProtectedBinary(true, pbRaw);
			return psPassword;
		}
Example #11
0
		/// <summary>
		/// Clear the key and securely erase all security-critical information.
		/// </summary>
		public void Clear()
		{
			if(m_psPassword != null)
			{
				m_psPassword.Clear();
				m_psPassword = null;
			}

			if(m_pbKeyData != null)
			{
				m_pbKeyData.Clear();
				m_pbKeyData = null;
			}
		}
Example #12
0
		private void SetKey(byte[] pbPasswordUtf8)
		{
			Debug.Assert(pbPasswordUtf8 != null);
			if(pbPasswordUtf8 == null) throw new ArgumentNullException("pbPasswordUtf8");

#if (DEBUG && !KeePassLibSD)
			Debug.Assert(ValidatePassword(pbPasswordUtf8));
#endif

			byte[] pbRaw = CryptoUtil.HashSha256(pbPasswordUtf8);

			m_psPassword = new ProtectedString(true, pbPasswordUtf8);
			m_pbKeyData = new ProtectedBinary(true, pbRaw);
		}
public void ExpandPattern()
{
    // arrange
    var psOutBuffer = new ProtectedString();
    var pwProfile = new PwProfile();
    pwProfile.Pattern = "g{5}";
    var pbKey = new byte[] { 0x00 };
    var crsRandomSource = new CryptoRandomStream(CrsAlgorithm.Salsa20, pbKey);
    var error = PatternBasedGenerator.Generate(psOutBuffer, pwProfile, crsRandomSource);

    // act
    // nothing to do as ExpandPattern() would have been called by calling Generate()

    // assert
    Assert.AreEqual(PwgError.Success, error);
    var actual = psOutBuffer.ReadString();
    Assert.AreEqual("ggggg", actual);
}
		public static PwgError Generate(ProtectedString psOutBuffer,
			PwProfile pwProfile, byte[] pbUserEntropy,
			CustomPwGeneratorPool pwAlgorithmPool)
		{
			Debug.Assert(psOutBuffer != null);
			if(psOutBuffer == null) throw new ArgumentNullException("psOutBuffer");
			Debug.Assert(pwProfile != null);
			if(pwProfile == null) throw new ArgumentNullException("pwProfile");

			psOutBuffer.Clear();

			CryptoRandomStream crs = CreateCryptoStream(pbUserEntropy);
			PwgError e = PwgError.Unknown;

			if(pwProfile.GeneratorType == PasswordGeneratorType.CharSet)
				e = CharSetBasedGenerator.Generate(psOutBuffer, pwProfile, crs);
			else if(pwProfile.GeneratorType == PasswordGeneratorType.Pattern)
				e = PatternBasedGenerator.Generate(psOutBuffer, pwProfile, crs);
			else if(pwProfile.GeneratorType == PasswordGeneratorType.Custom)
				e = GenerateCustom(psOutBuffer, pwProfile, crs, pwAlgorithmPool);
			else { Debug.Assert(false); }

			return e;
		}
Example #15
0
        public ProtectedString Insert(int iStart, string strInsert)
        {
            if (iStart < 0)
            {
                throw new ArgumentOutOfRangeException("iStart");
            }
            if (strInsert == null)
            {
                throw new ArgumentNullException("strInsert");
            }
            if (strInsert.Length == 0)
            {
                return(this);
            }

            if (!m_bIsProtected)
            {
                return(new ProtectedString(false, ReadString().Insert(
                                               iStart, strInsert)));
            }

            UTF8Encoding utf8 = StrUtil.Utf8;

            char[]          v     = ReadChars(), vNew = null;
            byte[]          pbNew = null;
            ProtectedString ps;

            try
            {
                if (iStart > v.Length)
                {
                    throw new ArgumentOutOfRangeException("iStart");
                }

                char[] vIns = strInsert.ToCharArray();

                vNew = new char[v.Length + vIns.Length];
                Array.Copy(v, 0, vNew, 0, iStart);
                Array.Copy(vIns, 0, vNew, iStart, vIns.Length);
                Array.Copy(v, iStart, vNew, iStart + vIns.Length,
                           v.Length - iStart);

                pbNew = utf8.GetBytes(vNew);
                ps    = new ProtectedString(true, pbNew);

                Debug.Assert(utf8.GetString(pbNew, 0, pbNew.Length) ==
                             ReadString().Insert(iStart, strInsert));
            }
            finally
            {
                MemUtil.ZeroArray <char>(v);
                if (vNew != null)
                {
                    MemUtil.ZeroArray <char>(vNew);
                }
                if (pbNew != null)
                {
                    MemUtil.ZeroByteArray(pbNew);
                }
            }

            return(ps);
        }
Example #16
0
		public ProtectedString Remove(int iStart, int nCount)
		{
			if(iStart < 0) throw new ArgumentOutOfRangeException("iStart");
			if(nCount < 0) throw new ArgumentOutOfRangeException("nCount");
			if(nCount == 0) return this;

			// Only operate directly with strings when m_bIsProtected is
			// false, not in the case of non-null m_strPlainText, because
			// the operation creates a new sequence in memory
			if(!m_bIsProtected)
				return new ProtectedString(false, ReadString().Remove(
					iStart, nCount));

			UTF8Encoding utf8 = StrUtil.Utf8;

			byte[] pb = ReadUtf8();
			char[] v = utf8.GetChars(pb);
			char[] vNew;

			try
			{
				if((iStart + nCount) > v.Length)
					throw new ArgumentException("iStart + nCount");

				vNew = new char[v.Length - nCount];
				Array.Copy(v, 0, vNew, 0, iStart);
				Array.Copy(v, iStart + nCount, vNew, iStart, v.Length -
					(iStart + nCount));
			}
			finally
			{
				Array.Clear(v, 0, v.Length);
				MemUtil.ZeroByteArray(pb);
			}

			byte[] pbNew = utf8.GetBytes(vNew);
			ProtectedString ps = new ProtectedString(m_bIsProtected, pbNew);

			Debug.Assert(utf8.GetString(pbNew, 0, pbNew.Length) ==
				ReadString().Remove(iStart, nCount));

			Array.Clear(vNew, 0, vNew.Length);
			MemUtil.ZeroByteArray(pbNew);
			return ps;
		}
Example #17
0
		public ProtectedString WithProtection(bool bProtect)
		{
			if(bProtect == m_bIsProtected) return this;

			byte[] pb = ReadUtf8();
			ProtectedString ps = new ProtectedString(bProtect, pb);

			if(bProtect) MemUtil.ZeroByteArray(pb);
			return ps;
		}
Example #18
0
 private static void UpdateValue(PwEntry entry, string key, string value)
 {
     var old = entry.Strings.ReadSafe(key);
     if(value != old)
     {
         var proectedValue = new ProtectedString(true, value);
         entry.Strings.Set(key, proectedValue);
     }
 }
Example #19
0
		private static void TestProtectedObjects()
		{
#if DEBUG
			Encoding enc = StrUtil.Utf8;

			byte[] pbData = enc.GetBytes("Test Test Test Test");
			ProtectedBinary pb = new ProtectedBinary(true, pbData);
			if(!pb.IsProtected) throw new SecurityException("ProtectedBinary-1");

			byte[] pbDec = pb.ReadData();
			if(!MemUtil.ArraysEqual(pbData, pbDec))
				throw new SecurityException("ProtectedBinary-2");
			if(!pb.IsProtected) throw new SecurityException("ProtectedBinary-3");

			byte[] pbData2 = enc.GetBytes("Test Test Test Test");
			byte[] pbData3 = enc.GetBytes("Test Test Test Test Test");
			ProtectedBinary pb2 = new ProtectedBinary(true, pbData2);
			ProtectedBinary pb3 = new ProtectedBinary(true, pbData3);
			if(!pb.Equals(pb2)) throw new SecurityException("ProtectedBinary-4");
			if(pb.Equals(pb3)) throw new SecurityException("ProtectedBinary-5");
			if(pb2.Equals(pb3)) throw new SecurityException("ProtectedBinary-6");

			if(pb.GetHashCode() != pb2.GetHashCode())
				throw new SecurityException("ProtectedBinary-7");
			if(!((object)pb).Equals((object)pb2))
				throw new SecurityException("ProtectedBinary-8");
			if(((object)pb).Equals((object)pb3))
				throw new SecurityException("ProtectedBinary-9");
			if(((object)pb2).Equals((object)pb3))
				throw new SecurityException("ProtectedBinary-10");

			ProtectedString ps = new ProtectedString();
			if(ps.Length != 0) throw new SecurityException("ProtectedString-1");
			if(!ps.IsEmpty) throw new SecurityException("ProtectedString-2");
			if(ps.ReadString().Length != 0)
				throw new SecurityException("ProtectedString-3");

			ps = new ProtectedString(true, "Test");
			ProtectedString ps2 = new ProtectedString(true, enc.GetBytes("Test"));
			if(ps.IsEmpty) throw new SecurityException("ProtectedString-4");
			pbData = ps.ReadUtf8();
			pbData2 = ps2.ReadUtf8();
			if(!MemUtil.ArraysEqual(pbData, pbData2))
				throw new SecurityException("ProtectedString-5");
			if(pbData.Length != 4)
				throw new SecurityException("ProtectedString-6");
			if(ps.ReadString() != ps2.ReadString())
				throw new SecurityException("ProtectedString-7");
			pbData = ps.ReadUtf8();
			pbData2 = ps2.ReadUtf8();
			if(!MemUtil.ArraysEqual(pbData, pbData2))
				throw new SecurityException("ProtectedString-8");
			if(!ps.IsProtected) throw new SecurityException("ProtectedString-9");
			if(!ps2.IsProtected) throw new SecurityException("ProtectedString-10");

			Random r = new Random();
			string str = string.Empty;
			ps = new ProtectedString();
			for(int i = 0; i < 100; ++i)
			{
				bool bProt = ((r.Next() % 4) != 0);
				ps = ps.WithProtection(bProt);

				int x = r.Next(str.Length + 1);
				int c = r.Next(20);
				char ch = (char)r.Next(1, 256);

				string strIns = new string(ch, c);
				str = str.Insert(x, strIns);
				ps = ps.Insert(x, strIns);

				if(ps.IsProtected != bProt)
					throw new SecurityException("ProtectedString-11");
				if(ps.ReadString() != str)
					throw new SecurityException("ProtectedString-12");

				ps = ps.WithProtection(bProt);

				x = r.Next(str.Length);
				c = r.Next(str.Length - x + 1);

				str = str.Remove(x, c);
				ps = ps.Remove(x, c);

				if(ps.IsProtected != bProt)
					throw new SecurityException("ProtectedString-13");
				if(ps.ReadString() != str)
					throw new SecurityException("ProtectedString-14");
			}
#endif
		}
Example #20
0
 private void OnBtnOK(object sender, EventArgs e)
 {
     byte[] pbUtf8 = m_secWord.ToUtf8();
     m_psSelected = new ProtectedString(true, pbUtf8);
     Array.Clear(pbUtf8, 0, pbUtf8.Length);
 }
		/// <summary>
		/// Construct a new protected string. The string is initialized
		/// to the value passed in the <c>pbTemplate</c> protected string.
		/// </summary>
		/// <param name="psTemplate">The initial string value. This
		/// parameter won't be modified. Must not be <c>null</c>.</param>
		/// <exception cref="System.ArgumentNullException">Thrown if the input
		/// parameter is <c>null</c>.</exception>
		public ProtectedString(ProtectedString psTemplate)
		{
			Debug.Assert(psTemplate != null);
			if(psTemplate == null) throw new ArgumentNullException("psTemplate");

			try { m_secString = new SecureString(); }
			catch(NotSupportedException) { } // Windows 98 / ME

			m_bIsProtected = psTemplate.m_bIsProtected;
			SetString(psTemplate.ReadString());
		}
Example #22
0
        /// <summary>
        /// Initialize the dialog.
        /// </summary>
        /// <param name="psWord">Password to pick characters from.</param>
        /// <param name="bCenterScreen">Specifies whether to center the form
        /// on the screen or not.</param>
        /// <param name="bSetForeground">If <c>true</c>, the window will be
        /// brought to the foreground when showing it.</param>
        /// <param name="uCharCount">Number of characters to pick. Specify
        /// 0 to allow picking a variable amount of characters.</param>
        public void InitEx(ProtectedString psWord, bool bCenterScreen,
            bool bSetForeground, uint uCharCount, bool? bInitHide)
        {
            m_psWord = psWord;

            if(bCenterScreen) this.StartPosition = FormStartPosition.CenterScreen;

            m_bSetForeground = bSetForeground;
            m_uCharCount = uCharCount;
            m_bInitHide = bInitHide;
        }
Example #23
0
        private static string FillIfExists(string strData, string strPlaceholder,
            ProtectedString psParsable, PwEntry pwEntry, PwDatabase pwDatabase,
            SprContentFlags cf, uint uRecursionLevel, SprRefsCache vRefsCache)
        {
            // The UrlRemoveSchemeOnce property of cf must be cleared
            // before this method returns and before any recursive call
            bool bRemoveScheme = false;
            if(cf != null)
            {
                bRemoveScheme = cf.UrlRemoveSchemeOnce;
                cf.UrlRemoveSchemeOnce = false;
            }

            if(strData == null) { Debug.Assert(false); return string.Empty; }
            if(strPlaceholder == null) { Debug.Assert(false); return strData; }
            if(strPlaceholder.Length == 0) { Debug.Assert(false); return strData; }
            if(psParsable == null) { Debug.Assert(false); return strData; }

            if(strData.IndexOf(strPlaceholder, SprEngine.ScMethod) >= 0)
            {
                string strReplacement = SprEngine.CompileInternal(
                    psParsable.ReadString(), pwEntry, pwDatabase, null,
                    uRecursionLevel + 1, vRefsCache);

                if(bRemoveScheme) strReplacement = UrlUtil.RemoveScheme(strReplacement);

                return SprEngine.FillPlaceholder(strData, strPlaceholder,
                    strReplacement, cf);
            }

            return strData;
        }
Example #24
0
        public static ProtectedString operator +(ProtectedString a, string b)
        {
            ProtectedString psB = new ProtectedString(false, b);

            return(a + psB);
        }
Example #25
0
        public ProtectedString Insert(int iStart, string strInsert)
        {
            if (iStart < 0)
            {
                throw new ArgumentOutOfRangeException("iStart");
            }
            if (strInsert == null)
            {
                throw new ArgumentNullException("strInsert");
            }
            if (strInsert.Length == 0)
            {
                return(this);
            }

            // Only operate directly with strings when m_bIsProtected is
            // false, not in the case of non-null m_strPlainText, because
            // the operation creates a new sequence in memory
            if (!m_bIsProtected)
            {
                return(new ProtectedString(false, ReadString().Insert(
                                               iStart, strInsert)));
            }

            UTF8Encoding utf8 = StrUtil.Utf8;

            byte[] pb = ReadUtf8();
            char[] v  = utf8.GetChars(pb);
            char[] vNew;

            try
            {
                if (iStart > v.Length)
                {
                    throw new ArgumentOutOfRangeException("iStart");
                }

                char[] vIns = strInsert.ToCharArray();

                vNew = new char[v.Length + vIns.Length];
                Array.Copy(v, 0, vNew, 0, iStart);
                Array.Copy(vIns, 0, vNew, iStart, vIns.Length);
                Array.Copy(v, iStart, vNew, iStart + vIns.Length,
                           v.Length - iStart);
            }
            finally
            {
                MemUtil.ZeroArray <char>(v);
                MemUtil.ZeroByteArray(pb);
            }

            byte[]          pbNew = utf8.GetBytes(vNew);
            ProtectedString ps    = new ProtectedString(m_bIsProtected, pbNew);

            Debug.Assert(utf8.GetString(pbNew, 0, pbNew.Length) ==
                         ReadString().Insert(iStart, strInsert));

            MemUtil.ZeroArray <char>(vNew);
            MemUtil.ZeroByteArray(pbNew);
            return(ps);
        }
Example #26
0
        private static string ReplaceNewPasswordPlaceholder(string strText,
            SprContext ctx, uint uRecursionLevel)
        {
            PwEntry pe = ctx.Entry;
            PwDatabase pd = ctx.Database;
            if((pe == null) || (pd == null)) return strText;

            string str = strText;

            const string strNewPwStart = @"{NEWPASSWORD";
            if(str.IndexOf(strNewPwStart, StrUtil.CaseIgnoreCmp) < 0) return str;

            string strGen = null;

            int iStart;
            List<string> lParams;
            while(SprEngine.ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                strNewPwStart + ":", out iStart, out lParams, true))
            {
                if(strGen == null)
                    strGen = GeneratePassword((((lParams != null) &&
                        (lParams.Count > 0)) ? lParams[0] : string.Empty), ctx);

                str = str.Insert(iStart, strGen);
            }

            const string strNewPwPlh = strNewPwStart + @"}";
            if(str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
            {
                if(strGen == null) strGen = GeneratePassword(null, ctx);

                str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strGen);
            }

            if(strGen != null)
            {
                pe.CreateBackup(pd);

                ProtectedString psGen = new ProtectedString(
                    pd.MemoryProtection.ProtectPassword, strGen);
                pe.Strings.Set(PwDefs.PasswordField, psGen);

                pe.Touch(true, false);
                pd.Modified = true;
            }
            else { Debug.Assert(false); }

            return str;
        }
Example #27
0
        private static string ShowCharPickDlg(string strWord, uint uCharCount,
			bool? bInitHide, SprContext ctx, uint uRecursionLevel)
        {
            string strPick = SprEngine.CompileInternal(strWord,
                ctx.WithoutContentTransformations(), uRecursionLevel + 1);

            // No need to show the dialog when there's nothing to pick from
            // (this also prevents the dialog from showing up MaxRecursionDepth
            // times in case of a cyclic {PICKCHARS})
            if(string.IsNullOrEmpty(strPick)) return string.Empty;

            ProtectedString psWord = new ProtectedString(false, strPick);
            string strPicked = CharPickerForm.ShowAndRestore(psWord,
                true, true, uCharCount, bInitHide);
            return (strPicked ?? string.Empty); // Don't transform here
        }
Example #28
0
		private void OnBtnOK(object sender, EventArgs e)
		{
			string strName = m_cmbStringName.Text;

			if(!ValidateStringNameUI())
			{
				this.DialogResult = DialogResult.None;
				return;
			}

			if(m_strStringName == null) // Add string field
			{
				Debug.Assert(!m_vStringDict.Exists(strName));
			}
			else // Edit string field
			{
				if(!m_strStringName.Equals(strName))
					m_vStringDict.Remove(m_strStringName);
			}

			ProtectedString ps = new ProtectedString(m_cbProtect.Checked,
				m_richStringValue.Text);
			m_vStringDict.Set(strName, ps);
		}
Example #29
0
        private void OnToolsGeneratePasswordList(object sender, EventArgs e)
        {
            PwDatabase pwDb = m_docMgr.ActiveDatabase;
            if(!pwDb.IsOpen) return;

            PwGeneratorForm pgf = new PwGeneratorForm();

            pgf.InitEx(null, true, IsTrayed());
            if(pgf.ShowDialog() == DialogResult.OK)
            {
                PwGroup pg = GetSelectedGroup();
                if(pg == null) pg = pwDb.RootGroup;

                SingleLineEditForm dlgCount = new SingleLineEditForm();
                dlgCount.InitEx(KPRes.GenerateCount, KPRes.GenerateCountDesc,
                    KPRes.GenerateCountLongDesc, Properties.Resources.B48x48_KGPG_Gen,
                    string.Empty, null);
                if(dlgCount.ShowDialog() == DialogResult.OK)
                {
                    uint uCount;
                    if(!uint.TryParse(dlgCount.ResultString, out uCount))
                        uCount = 1;

                    byte[] pbAdditionalEntropy = EntropyForm.CollectEntropyIfEnabled(
                        pgf.SelectedProfile);

                    for(uint i = 0; i < uCount; ++i)
                    {
                        PwEntry pe = new PwEntry(true, true);
                        pg.AddEntry(pe, true);

                        ProtectedString psNew = new ProtectedString(pwDb.MemoryProtection.ProtectPassword);
                        PwGenerator.Generate(psNew, pgf.SelectedProfile,
                            pbAdditionalEntropy, Program.PwGeneratorPool);
                        pe.Strings.Set(PwDefs.PasswordField, psNew);
                    }

                    UpdateUI(false, null, false, null, true, null, true);
                }
                UIUtil.DestroyForm(dlgCount);
            }
            UIUtil.DestroyForm(pgf);
        }
Example #30
0
        private void OnBtnOK(object sender, EventArgs e)
        {
            string strName = m_cmbStringName.Text;

            if(!ValidateStringName())
            {
                this.DialogResult = DialogResult.None;
                return;
            }

            if(m_strStringName == null) // Add string field
            {
                Debug.Assert(m_vStringDict.Exists(strName) == false);

                ProtectedString ps = new ProtectedString(m_cbProtect.Checked, m_richStringValue.Text);
                    m_vStringDict.Set(strName, ps);
            }
            else // Edit string field
            {
                if(m_strStringName.Equals(strName))
                {
                    if(m_psStringValue != null)
                    {
                        m_psStringValue.SetString(m_richStringValue.Text);
                        m_psStringValue.EnableProtection(m_cbProtect.Checked);
                    }
                    else
                    {
                        ProtectedString ps = new ProtectedString(m_cbProtect.Checked, m_richStringValue.Text);
                        m_vStringDict.Set(strName, ps);
                    }
                }
                else
                {
                    m_vStringDict.Remove(m_strStringName);

                    ProtectedString ps = new ProtectedString(m_cbProtect.Checked, m_richStringValue.Text);
                    m_vStringDict.Set(strName, ps);
                }
            }

            CleanUpEx();
        }
Example #31
0
        private void OnToolsPwGenerator(object sender, EventArgs e)
        {
            PwDatabase pwDb = m_docMgr.ActiveDatabase;
            PwGeneratorForm pgf = new PwGeneratorForm();

            pgf.InitEx(null, pwDb.IsOpen, IsTrayed());
            if(pgf.ShowDialog() == DialogResult.OK)
            {
                if(pwDb.IsOpen)
                {
                    PwGroup pg = GetSelectedGroup();
                    if(pg == null) pg = pwDb.RootGroup;

                    PwEntry pe = new PwEntry(true, true);
                    pg.AddEntry(pe, true);

                    byte[] pbAdditionalEntropy = EntropyForm.CollectEntropyIfEnabled(
                        pgf.SelectedProfile);
                    ProtectedString psNew = new ProtectedString(pwDb.MemoryProtection.ProtectPassword);
                    PwGenerator.Generate(psNew, pgf.SelectedProfile, pbAdditionalEntropy,
                        Program.PwGeneratorPool);
                    pe.Strings.Set(PwDefs.PasswordField, psNew);

                    UpdateUI(false, null, false, null, true, null, true);

                    if(m_lvEntries.Items.Count > 0) // Select new entry
                    {
                        m_lvEntries.EnsureVisible(m_lvEntries.Items.Count - 1);
                        for(int i = 0; i < (m_lvEntries.Items.Count - 1); ++i)
                            m_lvEntries.Items[i].Selected = false; // Deselect
                        m_lvEntries.Items[m_lvEntries.Items.Count - 1].Selected = true;
                    }
                }
            }
            UIUtil.DestroyForm(pgf);
        }
Example #32
0
		private static string FillIfExists(string strData, string strPlaceholder,
			ProtectedString psParsable, SprContext ctx, uint uRecursionLevel)
		{
			// // The UrlRemoveSchemeOnce property of ctx must be cleared
			// // before this method returns and before any recursive call
			// bool bRemoveScheme = false;
			// if(ctx != null)
			// {
			//	bRemoveScheme = ctx.UrlRemoveSchemeOnce;
			//	ctx.UrlRemoveSchemeOnce = false;
			// }

			if(strData == null) { Debug.Assert(false); return string.Empty; }
			if(strPlaceholder == null) { Debug.Assert(false); return strData; }
			if(strPlaceholder.Length == 0) { Debug.Assert(false); return strData; }
			if(psParsable == null) { Debug.Assert(false); return strData; }

			if(strData.IndexOf(strPlaceholder, SprEngine.ScMethod) >= 0)
			{
				string strReplacement = SprEngine.CompileInternal(
					psParsable.ReadString(), ctx.WithoutContentTransformations(),
					uRecursionLevel + 1);

				// if(bRemoveScheme)
				//	strReplacement = UrlUtil.RemoveScheme(strReplacement);

				return SprEngine.FillPlaceholder(strData, strPlaceholder,
					strReplacement, ctx);
			}

			return strData;
		}
Example #33
0
        private void OnEntryAdd(object sender, EventArgs e)
        {
            PwGroup pg = GetSelectedGroup();
            Debug.Assert(pg != null); if(pg == null) return;

            if(pg.IsVirtual)
            {
                MessageService.ShowWarning(KPRes.GroupCannotStoreEntries,
                    KPRes.SelectDifferentGroup);
                return;
            }

            PwDatabase pwDb = m_docMgr.ActiveDatabase;
            PwEntry pwe = new PwEntry(true, true);
            pwe.Strings.Set(PwDefs.UserNameField, new ProtectedString(
                pwDb.MemoryProtection.ProtectUserName,
                pwDb.DefaultUserName));

            ProtectedString psAutoGen = new ProtectedString(
                pwDb.MemoryProtection.ProtectPassword);
            PwGenerator.Generate(psAutoGen, Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile,
                null, Program.PwGeneratorPool);
            pwe.Strings.Set(PwDefs.PasswordField, psAutoGen);

            int nExpireDays = Program.Config.Defaults.NewEntryExpiresInDays;
            if(nExpireDays >= 0)
            {
                pwe.Expires = true;
                pwe.ExpiryTime = DateTime.Now.AddDays(nExpireDays);
            }

            if((pg.IconId != PwIcon.Folder) && (pg.IconId != PwIcon.FolderOpen) &&
                (pg.IconId != PwIcon.FolderPackage))
            {
                pwe.IconId = pg.IconId; // Inherit icon from group
            }
            pwe.CustomIconUuid = pg.CustomIconUuid;

            // Temporarily assume that the entry is in pg; required for retrieving
            // the default auto-type sequence
            pwe.ParentGroup = pg;

            PwEntryForm pForm = new PwEntryForm();
            pForm.InitEx(pwe, PwEditMode.AddNewEntry, pwDb, m_ilCurrentIcons,
                false, false);
            if(UIUtil.ShowDialogAndDestroy(pForm) == DialogResult.OK)
            {
                pg.AddEntry(pwe, true);
                UpdateUI(false, null, pwDb.UINeedsIconUpdate, null, true,
                    null, true, m_lvEntries);

                PwObjectList<PwEntry> vSelect = new PwObjectList<PwEntry>();
                vSelect.Add(pwe);
                SelectEntries(vSelect, true, true);

                EnsureVisibleEntry(pwe.Uuid);
            }
            else UpdateUI(false, null, pwDb.UINeedsIconUpdate, null,
                pwDb.UINeedsIconUpdate, null, false);
        }