ReadString() public method

Convert the protected string to a normal string object. Be careful with this function, the returned string object isn't protected anymore and stored in plain-text in the process memory.
public ReadString ( ) : string
return string
Esempio n. 1
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);
		}
Esempio n. 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;
		}
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);
}
Esempio n. 4
0
        public bool Equals(ProtectedString ps, bool bCheckProtEqual)
        {
            if (ps == null)
            {
                throw new ArgumentNullException("ps");
            }
            if (object.ReferenceEquals(this, ps))
            {
                return(true);                                             // Perf. opt.
            }
            bool bPA = m_bIsProtected, bPB = ps.m_bIsProtected;

            if (bCheckProtEqual && (bPA != bPB))
            {
                return(false);
            }
            if (!bPA && !bPB)
            {
                return(ReadString() == ps.ReadString());
            }

            byte[] pbA = ReadUtf8(), pbB = null;
            bool   bEq;

            try
            {
                pbB = ps.ReadUtf8();
                bEq = MemUtil.ArraysEqual(pbA, pbB);
            }
            finally
            {
                if (bPA)
                {
                    MemUtil.ZeroByteArray(pbA);
                }
                if (bPB && (pbB != null))
                {
                    MemUtil.ZeroByteArray(pbB);
                }
            }

            return(bEq);
        }
Esempio n. 5
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;
        }
		/// <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());
		}
Esempio n. 7
0
        public static bool CopyAndMinimize(ProtectedString psToCopy, bool bIsEntryInfo,
			Form formContext, PwEntry peEntryInfo, PwDatabase pwReferenceSource)
        {
            if(psToCopy == null) throw new ArgumentNullException("psToCopy");

            IntPtr hOwner = ((formContext != null) ? formContext.Handle : IntPtr.Zero);

            if(Copy(psToCopy.ReadString(), true, bIsEntryInfo, peEntryInfo,
                pwReferenceSource, hOwner))
            {
                if(formContext != null)
                {
                    if(Program.Config.MainWindow.DropToBackAfterClipboardCopy)
                        NativeMethods.LoseFocus(formContext);

                    if(Program.Config.MainWindow.MinimizeAfterClipboardCopy)
                        UIUtil.SetWindowState(formContext, FormWindowState.Minimized);
                }

                return true;
            }

            return false;
        }
Esempio n. 8
0
        public string GeneratePassword(string profileName)
        {
            PwProfile profile = null;

            if (string.IsNullOrEmpty(profileName))
                profile = KeePass.Program.Config.PasswordGenerator.LastUsedProfile;
            else
            {
                foreach (PwProfile pp in KeePass.Program.Config.PasswordGenerator.UserProfiles)
                {
                    if (pp.Name == profileName)
                    {
                        profile = pp;
                        break;
                    }
                }
            }

            if (profile == null)
                return "";

            ProtectedString newPassword = new ProtectedString();
            PwgError result = PwGenerator.Generate(newPassword, profile, null, null);

            if (result == PwgError.Success)
                return newPassword.ReadString();
            else
                return "";

            //KeePass.Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile.Name

            ////KeePassLib.Cryptography.PasswordGenerator.PwProfile profile = new KeePassLib.Cryptography.PasswordGenerator.PwProfile();//host.PwGeneratorPool.Find(
            ////KeePass.Program.PwGeneratorPool
            // //KeePass.Util.PwGeneratorUtil.
            //profile.
            //KeePassLib.Security
            //KeePassLib.Cryptography.PasswordGenerator.PwGenerator.Generate(null, KeePassLib.Cryptography.PasswordGenerator.PwProfile
            //foreach (PwProfile pwgo in host.PwGeneratorPool.Config.PasswordGenerator.UserProfiles)
            //{
            //    if (pwgo.Name == strProfile)
            //    {
            //        SetGenerationOptions(pwgo);
            //        break;
            //    }
            //}
            //return "password";
        }
Esempio n. 9
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");
            #endif
        }
Esempio n. 10
0
        public string GeneratePassword(string profileName, string url)
        {
            PwProfile profile = null;
            
            if (string.IsNullOrEmpty(profileName))
                profile = KeePass.Program.Config.PasswordGenerator.LastUsedProfile;
            else
            {
                foreach (PwProfile pp in KeePass.Util.PwGeneratorUtil.GetAllProfiles(false))
                {
                    if (pp.Name == profileName)
                    {
                        profile = pp;
                        KeePass.Program.Config.PasswordGenerator.LastUsedProfile = pp;
                        break;
                    }
                }
            }

            if (profile == null)
                return "";

            ProtectedString newPassword = new ProtectedString();
            PwgError result = PwgError.Unknown; // PwGenerator.Generate(out newPassword, profile, null, null);

            MethodInfo mi;

            // Generate method signature changed in KP 2.18 so we use
            // reflection to enable support for both 2.18 and earlier versions
            //TODO:1.6: drop support for 2.18
            Type[] mitypes218 = new Type[] { typeof(ProtectedString).MakeByRefType(), typeof(PwProfile), typeof(byte[]), typeof(CustomPwGeneratorPool) };

            try
            {
                mi = typeof(PwGenerator).GetMethod(
                    "Generate",
                    BindingFlags.Public | BindingFlags.Static,
                    Type.DefaultBinder,
                    mitypes218,
                    null
                );

                object[] inputParameters = new object[] { null, profile, null, this.host.PwGeneratorPool };
                result = (PwgError)mi.Invoke(null, inputParameters);
                newPassword = (ProtectedString)inputParameters[0];
            }
            catch (Exception)
            {
                Type[] mitypes217 = new Type[] { typeof(ProtectedString), typeof(PwProfile), typeof(byte[]), typeof(CustomPwGeneratorPool) };
                // can't find the 2.18 method definition so try for an earlier version
                mi = typeof(PwGenerator).GetMethod(
                    "Generate",
                    BindingFlags.Public | BindingFlags.Static,
                    Type.DefaultBinder,
                    mitypes217,
                    null
                );

                object[] inputParameters = new object[] { newPassword, profile, null, this.host.PwGeneratorPool };
                result = (PwgError)mi.Invoke(null, inputParameters);

                // If an exception is thrown here it would be unexpected and
                // require a new version of the application to be released
            }

            var password = newPassword.ReadString();
            if (host.CustomConfig.GetBool("KeePassRPC.KeeFox.backupNewPasswords", true))
                AddPasswordBackupLogin(password, url);

            if (result == PwgError.Success)
                return password;
            else
                return "";
        }
Esempio n. 11
0
        private void WriteObject(string name, ProtectedString value, bool bIsEntryString)
        {
            Debug.Assert(name != null);
            Debug.Assert(value != null); if(value == null) throw new ArgumentNullException("value");

            m_xmlWriter.WriteStartElement(ElemString);
            m_xmlWriter.WriteStartElement(ElemKey);
            m_xmlWriter.WriteString(StrUtil.SafeXmlString(name));
            m_xmlWriter.WriteEndElement();
            m_xmlWriter.WriteStartElement(ElemValue);

            bool bProtected = value.IsProtected;
            if(bIsEntryString)
            {
                // Adjust memory protection setting (which might be different
                // from the database default, e.g. due to an import which
                // didn't specify the correct setting)
                if(name == PwDefs.TitleField)
                    bProtected = m_pwDatabase.MemoryProtection.ProtectTitle;
                else if(name == PwDefs.UserNameField)
                    bProtected = m_pwDatabase.MemoryProtection.ProtectUserName;
                else if(name == PwDefs.PasswordField)
                    bProtected = m_pwDatabase.MemoryProtection.ProtectPassword;
                else if(name == PwDefs.UrlField)
                    bProtected = m_pwDatabase.MemoryProtection.ProtectUrl;
                else if(name == PwDefs.NotesField)
                    bProtected = m_pwDatabase.MemoryProtection.ProtectNotes;
            }

            if(bProtected && (m_format != KdbxFormat.PlainXml))
            {
                m_xmlWriter.WriteAttributeString(AttrProtected, ValTrue);

                byte[] pbEncoded = value.ReadXorredString(m_randomStream);
                if(pbEncoded.Length > 0)
                    m_xmlWriter.WriteBase64(pbEncoded, 0, pbEncoded.Length);
            }
            else
            {
                string strValue = value.ReadString();

                // If names should be localized, we need to apply the language-dependent
                // string transformation here. By default, language-dependent conversions
                // should be applied, otherwise characters could be rendered incorrectly
                // (code page problems).
                if(m_bLocalizedNames)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach(char ch in strValue)
                    {
                        char chMapped = ch;

                        // Symbols and surrogates must be moved into the correct code
                        // page area
                        if(char.IsSymbol(ch) || char.IsSurrogate(ch))
                        {
                            System.Globalization.UnicodeCategory cat =
                                CharUnicodeInfo.GetUnicodeCategory(ch);
                            // Map character to correct position in code page
                            chMapped = (char)((int)cat * 32 + ch);
                        }
                        else if(char.IsControl(ch))
                        {
                            if(ch >= 256) // Control character in high ANSI code page
                            {
                                // Some of the control characters map to corresponding ones
                                // in the low ANSI range (up to 255) when calling
                                // ToLower on them with invariant culture (see
                                // http://lists.ximian.com/pipermail/mono-patches/2002-February/086106.html )
            #if !KeePassLibSD
                                chMapped = char.ToLowerInvariant(ch);
            #else
                                chMapped = char.ToLower(ch);
            #endif
                            }
                        }

                        sb.Append(chMapped);
                    }

                    strValue = sb.ToString(); // Correct string for current code page
                }

                if((m_format == KdbxFormat.PlainXml) && bProtected)
                    m_xmlWriter.WriteAttributeString(AttrProtectedInMemPlainXml, ValTrue);

                m_xmlWriter.WriteString(StrUtil.SafeXmlString(strValue));
            }

            m_xmlWriter.WriteEndElement(); // ElemValue
            m_xmlWriter.WriteEndElement(); // ElemString
        }
Esempio n. 12
0
		private static string ReplaceNewPasswordPlaceholder(string strText,
			PwEntry pe, PwDatabase pd, SprContentFlags cf)
		{
			if((pe == null) || (pd == null)) return strText;

			string str = strText;

			const string strNewPwPlh = @"{NEWPASSWORD}";
			if(str.IndexOf(strNewPwPlh, StrUtil.CaseIgnoreCmp) >= 0)
			{
				ProtectedString psAutoGen = new ProtectedString(
					pd.MemoryProtection.ProtectPassword);
				PwgError e = PwGenerator.Generate(psAutoGen,
					Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile,
					null, Program.PwGeneratorPool);

				if(e == PwgError.Success)
				{
					pe.CreateBackup();
					pe.Strings.Set(PwDefs.PasswordField, psAutoGen);
					pd.Modified = true;

					string strIns = SprEngine.TransformContent(psAutoGen.ReadString(), cf);
					str = StrUtil.ReplaceCaseInsensitive(str, strNewPwPlh, strIns);
				}
			}

			return str;
		}
Esempio n. 13
0
 public WriteBase(ProtectedString masterkey, PwDatabase database)
 {
     _dataConnections.UserPass = masterkey.ReadString();
     this._kpDatabase = database;
     InitializeComponent();
 }
Esempio n. 14
0
        private void GeneratePreviewPasswords()
        {
            m_pbPreview.Value = 0;
            m_tbPreview.Text = string.Empty;

            PwProfile pwOpt = GetGenerationOptions();
            StringBuilder sbList = new StringBuilder();

            Cursor cNormalCursor = this.Cursor;
            this.Cursor = Cursors.WaitCursor;

            for(uint i = 0; i < MaxPreviewPasswords; ++i)
            {
                Application.DoEvents();

                ProtectedString psNew = new ProtectedString(false);
                PwGenerator.Generate(psNew, pwOpt, null, Program.PwGeneratorPool);
                sbList.AppendLine(psNew.ReadString());
                m_pbPreview.Value = (int)((100 * i) / MaxPreviewPasswords);
            }

            m_pbPreview.Value = 100;
            m_tbPreview.Text = sbList.ToString();

            this.Cursor = cNormalCursor;
        }
Esempio n. 15
0
        private static string FillIfExists(string strData, string strPlaceholder,
            ProtectedString psParsable, PwEntry pwEntry, PwDatabase pwDatabase,
            SprContentFlags cf, uint uRecursionLevel, SprRefsCache vRefsCache)
        {
            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)
                return SprEngine.FillPlaceholder(strData, strPlaceholder,
                    SprEngine.CompileInternal(psParsable.ReadString(), pwEntry,
                    pwDatabase, null, uRecursionLevel + 1, vRefsCache), cf);

            return strData;
        }
Esempio n. 16
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
		}
Esempio n. 17
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;
		}
Esempio n. 18
0
        public string GeneratePassword(string profileName)
        {
            PwProfile profile = null;

            if (string.IsNullOrEmpty(profileName))
                profile = KeePass.Program.Config.PasswordGenerator.LastUsedProfile;
            else
            {
                foreach (PwProfile pp in KeePass.Util.PwGeneratorUtil.GetAllProfiles(false))
                {
                    if (pp.Name == profileName)
                    {
                        profile = pp;
                        KeePass.Program.Config.PasswordGenerator.LastUsedProfile = pp;
                        break;
                    }
                }
            }

            if (profile == null)
                return "";

            ProtectedString newPassword = new ProtectedString();
            PwgError result = PwgError.Unknown; // PwGenerator.Generate(out newPassword, profile, null, null);

            MethodInfo mi;

            // Generate method signature changed in KP 2.18 so we use
            // reflection to enable support for both 2.18 and earlier versions
            Type[] mitypes218 = new Type[] { typeof(ProtectedString).MakeByRefType(), typeof(PwProfile), typeof(byte[]), typeof(CustomPwGeneratorPool) };

            try
            {
                mi = typeof(PwGenerator).GetMethod(
                    "Generate",
                    BindingFlags.Public | BindingFlags.Static,
                    Type.DefaultBinder,
                    mitypes218,
                    null
                );

                object[] inputParameters = new object[] { null, profile, null, this.host.PwGeneratorPool };
                result = (PwgError)mi.Invoke(null, inputParameters);
                newPassword = (ProtectedString)inputParameters[0];
            }
            catch (Exception)
            {
                Type[] mitypes217 = new Type[] { typeof(ProtectedString), typeof(PwProfile), typeof(byte[]), typeof(CustomPwGeneratorPool) };
                // can't find the 2.18 method definition so try for an earlier version
                mi = typeof(PwGenerator).GetMethod(
                    "Generate",
                    BindingFlags.Public | BindingFlags.Static,
                    Type.DefaultBinder,
                    mitypes217,
                    null
                );

                object[] inputParameters = new object[] { newPassword, profile, null, this.host.PwGeneratorPool };
                result = (PwgError)mi.Invoke(null, inputParameters);

                // If an exception is thrown here it would be unexpected and
                // require a new version of the application to be released
            }

            if (result == PwgError.Success)
                return newPassword.ReadString();
            else
                return "";

            //KeePass.Program.Config.PasswordGenerator.AutoGeneratedPasswordsProfile.Name

            ////KeePassLib.Cryptography.PasswordGenerator.PwProfile profile = new KeePassLib.Cryptography.PasswordGenerator.PwProfile();//host.PwGeneratorPool.Find(
            ////KeePass.Program.PwGeneratorPool
            // //KeePass.Util.PwGeneratorUtil.
            //profile.
            //KeePassLib.Security
            //KeePassLib.Cryptography.PasswordGenerator.PwGenerator.Generate(null, KeePassLib.Cryptography.PasswordGenerator.PwProfile
            //foreach (PwProfile pwgo in host.PwGeneratorPool.Config.PasswordGenerator.UserProfiles)
            //{
            //    if (pwgo.Name == strProfile)
            //    {
            //        SetGenerationOptions(pwgo);
            //        break;
            //    }
            //}
            //return "password";
        }