Ejemplo n.º 1
0
 public static void ExecuteEdit(IWin32Window owner, PasswordTypes passwordTypes)
 {
     using (var form = new ViewTypesForm())
     {
         form.Init(passwordTypes, true);
         form.ShowDialog(owner);
     }
 }
Ejemplo n.º 2
0
        public PasswordDocument()
        {
            IsLoaded = false;
            _fileName = string.Empty;
            DocumentPassword = string.Empty;

            _passwordFields = new Fields(this);
            _passwordTypes = new PasswordTypes(this);
            _passwords = new Passwords(this);
        }
Ejemplo n.º 3
0
        public static PasswordType Execute(IWin32Window owner, PasswordTypes passwordTypes, PasswordType passwordType)
        {
            using (var form = new EditPasswordTypeForm())
            {
                form.Init(passwordTypes, passwordType);

                if (form.ShowDialog(owner) == DialogResult.OK)
                    return form.SelectedPasswordType;

                return null;
            }
        }
Ejemplo n.º 4
0
        public static PasswordType ExecuteSelect(IWin32Window owner, PasswordTypes passwordTypes)
        {
            using (var form = new ViewTypesForm())
            {
                form.Init(passwordTypes, false);

                if (form.ShowDialog(owner) == DialogResult.OK)
                    return form.GetSelectedPasswordType();

                return null;
            }
        }
Ejemplo n.º 5
0
        private void Init(PasswordTypes passwordTypes, PasswordType passwordType)
        {
            _passwordTypes = passwordTypes;
            _passwordType = passwordType;

            if (_passwordType == null)
                Text = "Добавление";
            else
            {
                Text = "Редактирование";

                tbName.Text = _passwordType.Name;
                Fill();
            }

            RefreshUI();
        }
Ejemplo n.º 6
0
		/// <summary>
		/// Decrypt a string sequence using the selected encryption types
		/// </summary>
		/// <param name="data">hex coded string sequence to decrypt</param>
		/// <param name="encryptedTypes">Encryption types</param>
		/// <param name="password">optional password</param>
		/// <param name="yubidata">optional yubi data</param>
		/// <param name="decode"></param>
		/// <returns>decrypted string sequence</returns>
		private static string DecryptSequenceNoHash(string data, PasswordTypes encryptedTypes, string password, YubiKey yubi, bool decode = false)
		{
			try
			{
				// reverse order they were encrypted
				if ((encryptedTypes & PasswordTypes.Machine) != 0)
				{
					// we are going to decrypt with the Windows local machine key
					byte[] cipher = Authenticator.StringToByteArray(data);
					byte[] plain = ProtectedData.Unprotect(cipher, null, DataProtectionScope.LocalMachine);
					if (decode == true)
					{
						data = Encoding.UTF8.GetString(plain, 0, plain.Length);
					}
					else
					{
						data = ByteArrayToString(plain);
					}
				}
				if ((encryptedTypes & PasswordTypes.User) != 0)
				{
					// we are going to decrypt with the Windows User account key
					byte[] cipher = StringToByteArray(data);
					byte[] plain = ProtectedData.Unprotect(cipher, null, DataProtectionScope.CurrentUser);
					if (decode == true)
					{
						data = Encoding.UTF8.GetString(plain, 0, plain.Length);
					}
					else
					{
						data = ByteArrayToString(plain);
					}
				}
				if ((encryptedTypes & PasswordTypes.Explicit) != 0)
				{
					// we use an explicit password to encrypt data
					if (string.IsNullOrEmpty(password) == true)
					{
						throw new EncrpytedSecretDataException();
					}
					data = Authenticator.Decrypt(data, password, true);
					if (decode == true)
					{
						byte[] plain = Authenticator.StringToByteArray(data);
						data = Encoding.UTF8.GetString(plain, 0, plain.Length);
					}
				}
				if ((encryptedTypes & PasswordTypes.YubiKeySlot1) != 0 || (encryptedTypes & PasswordTypes.YubiKeySlot2) != 0)
				{
					if (string.IsNullOrEmpty(yubi.Info.Error) == false)
					{
						throw new BadYubiKeyException("Unable to detect YubiKey");
					}
					if (yubi.Info.Status.VersionMajor == 0)
					{
						throw new BadYubiKeyException("Please insert your YubiKey");
					}
					int slot = ((encryptedTypes & PasswordTypes.YubiKeySlot1) != 0 ? 1 : 2);

					string seed = data.Substring(0, SALT_LENGTH * 2);
					data = data.Substring(seed.Length);
					byte[] key = yubi.ChallengeResponse(slot, StringToByteArray(seed));

					data = Authenticator.Decrypt(data, key);
					if (decode == true)
					{
						byte[] plain = Authenticator.StringToByteArray(data);
						data = Encoding.UTF8.GetString(plain, 0, plain.Length);
					}

					yubi.YubiData.Seed = seed;
					yubi.YubiData.Data = key;
				}
			}
			catch (EncrpytedSecretDataException)
			{
				throw;
			}
			catch (BadYubiKeyException )
			{
				throw;
			}
			catch (ChallengeResponseException ex)
			{
				throw new BadYubiKeyException("Please check your YubiKey or touch the flashing button", ex);
			}
			catch (Exception ex)
			{
				throw new BadPasswordException(ex.Message, ex);
			}

			return data;
		}
Ejemplo n.º 7
0
		/// <summary>
		/// Decrypt a string sequence using the selected encryption types
		/// </summary>
		/// <param name="data">hex coded string sequence to decrypt</param>
		/// <param name="encryptedTypes">Encryption types</param>
		/// <param name="password">optional password</param>
		/// <param name="yubidata">optional yubi data</param>
		/// <param name="decode"></param>
		/// <returns>decrypted string sequence</returns>
		public static string DecryptSequence(string data, PasswordTypes encryptedTypes, string password, YubiKey yubi, bool decode = false)
    {
			// check for encrpytion header
			if (data.Length < ENCRYPTION_HEADER.Length || data.IndexOf(ENCRYPTION_HEADER) != 0)
			{
				return DecryptSequenceNoHash(data, encryptedTypes, password, yubi, decode);
			}

			// extract salt and hash
			using (var sha = new SHA256Managed())
			{
				// jump header
				int datastart = ENCRYPTION_HEADER.Length;
				string salt = data.Substring(datastart, Math.Min(SALT_LENGTH * 2, data.Length - datastart));
				datastart += salt.Length;
				string hash = data.Substring(datastart, Math.Min(sha.HashSize / 8 * 2, data.Length - datastart));
				datastart += hash.Length;
				data = data.Substring(datastart);

				data = DecryptSequenceNoHash(data, encryptedTypes, password, yubi);

				// check the hash
				byte[] compareplain = StringToByteArray(salt + data);
				string comparehash = ByteArrayToString(sha.ComputeHash(compareplain));
				if (string.Compare(comparehash, hash) != 0)
				{
					throw new BadPasswordException();
				}
			}

      return data;
    }
Ejemplo n.º 8
0
		public void SetEncryption(PasswordTypes passwordType, string password = null)
		{
			// check if still encrpyted
			if (this.RequiresPassword == true)
			{
				// have to decrypt to be able to re-encrypt
				throw new EncrpytedSecretDataException();
			}

			if (passwordType == PasswordTypes.None)
			{
				this.RequiresPassword = false;
				this.EncryptedData = null;
				this.PasswordType = passwordType;
			}
			else
			{
				using (MemoryStream ms = new MemoryStream())
				{
					// get the plain version
					XmlWriterSettings settings = new XmlWriterSettings();
					settings.Indent = true;
					settings.Encoding = Encoding.UTF8;
					using (XmlWriter encryptedwriter = XmlWriter.Create(ms, settings))
					{
						string encrpytedData = this.EncryptedData;
						Authenticator.PasswordTypes savedpasswordType = PasswordType;
						try
						{
							PasswordType = Authenticator.PasswordTypes.None;
							EncryptedData = null;
							WriteToWriter(encryptedwriter);
						}
						finally
						{
							this.PasswordType = savedpasswordType;
							this.EncryptedData = encrpytedData;
						}
					}
					string data = Authenticator.ByteArrayToString(ms.ToArray());

					// update secret hash
					using (SHA1 sha1 = SHA1.Create())
					{
						this.SecretHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(this.SecretData));
					}

					// encrypt
					this.EncryptedData = Authenticator.EncryptSequence(data, passwordType, password, null);
					this.PasswordType = passwordType;
					if (this.PasswordType == PasswordTypes.Explicit)
					{
						this.SecretData = null;
						this.RequiresPassword = true;
					}
				}
			}
		}
Ejemplo n.º 9
0
		/// <summary>
		/// Encode the PasswordTypes type into a string for storing in config
		/// </summary>
		/// <param name="passwordType">PasswordTypes value</param>
		/// <returns>string version</returns>
		public static string EncodePasswordTypes(PasswordTypes passwordType)
		{
			StringBuilder encryptedTypes = new StringBuilder();
			if ((passwordType & PasswordTypes.Explicit) != 0)
			{
				encryptedTypes.Append("y");
			}
			if ((passwordType & PasswordTypes.User) != 0)
			{
				encryptedTypes.Append("u");
			}
			if ((passwordType & PasswordTypes.Machine) != 0)
			{
				encryptedTypes.Append("m");
			}

			return encryptedTypes.ToString();
		}
Ejemplo n.º 10
0
		public static string EncryptSequence(string data, PasswordTypes passwordType, string password, YubiKey yubi)
    {
			// get hash of original
			var random = new RNGCryptoServiceProvider();
			byte[] saltbytes = new byte[SALT_LENGTH];
			random.GetBytes(saltbytes);
			string salt = ByteArrayToString(saltbytes);

			string hash;
			using (var sha = new SHA256Managed())
			{
        byte[] plain = StringToByteArray(salt + data);
				hash = ByteArrayToString(sha.ComputeHash(plain));
			}

			if ((passwordType & PasswordTypes.YubiKeySlot1) != 0 || (passwordType & PasswordTypes.YubiKeySlot2) != 0)
			{
				if (yubi.YubiData.Length == 0)
				{
					byte[] seed = new byte[SALT_LENGTH];
					random = new RNGCryptoServiceProvider();
					random.GetBytes(seed);

					// we encrypt the data using the hash of a random string from the YubiKey
					int slot = ((passwordType & PasswordTypes.YubiKeySlot1) != 0 ? 1 : 2);
					yubi.YubiData.Data = yubi.ChallengeResponse(slot, seed);
					yubi.YubiData.Seed = Authenticator.ByteArrayToString(seed);
				}

				byte[] key = yubi.YubiData.Data;
				string encrypted = Encrypt(data, key);

				// test the encryption
				string decrypted = Decrypt(encrypted, key);
				if (string.Compare(data, decrypted) != 0)
				{
					throw new InvalidEncryptionException(data, password, encrypted, decrypted);
				}
				data = yubi.YubiData.Seed + encrypted;
			}
			if ((passwordType & PasswordTypes.Explicit) != 0)
      {
        string encrypted = Encrypt(data, password);

        // test the encryption
        string decrypted = Decrypt(encrypted, password, true);
        if (string.Compare(data, decrypted) != 0)
        {
          throw new InvalidEncryptionException(data, password, encrypted, decrypted);
        }
        data = encrypted;
      }
      if ((passwordType & PasswordTypes.User) != 0)
      {
        // we encrypt the data using the Windows User account key
        byte[] plain = StringToByteArray(data);
        byte[] cipher = ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser);
        data = ByteArrayToString(cipher);
      }
      if ((passwordType & PasswordTypes.Machine) != 0)
      {
        // we encrypt the data using the Local Machine account key
        byte[] plain = StringToByteArray(data);
        byte[] cipher = ProtectedData.Protect(plain, null, DataProtectionScope.LocalMachine);
        data = ByteArrayToString(cipher);
      }

			// prepend the salt + hash
			return ENCRYPTION_HEADER + salt + hash + data;
    }
        /// <summary>
        /// Load an authenticator from a Stream with an explicit password for this current version
        /// </summary>
        /// <param name="stream">Stream to read</param>
        /// <param name="password">explicit password if requried</param>
        /// <param name="version">expected version of authenticator</param>
        /// <returns>loaded Authenticator</returns>
        public static Authenticator ReadFromStream(Stream stream, string password, decimal version)
        {
            using (XmlReader xr = XmlReader.Create(stream))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xr);
                XmlNode rootnode = doc.DocumentElement;
                XmlNode node;

                Authenticator authenticator = null;

                // get the type is we have it, else use the default
                XmlAttribute authenticatorType = rootnode.Attributes["type"];
                if (authenticatorType != null)
                {
                    Type type = System.Reflection.Assembly.GetExecutingAssembly().GetType(authenticatorType.Value, false, true);
                    authenticator = Activator.CreateInstance(type) as Authenticator;
                }
                if (authenticator == null)
                {
                    authenticator = new BattleNetAuthenticator();
                }

                // is the Mobile Authenticator file? <xml.../><map>...</map>
                node = rootnode.SelectSingleNode("/map/string[@name='" + BMA_HASH_NAME + "']");
                if (node != null)
                {
                    string data = node.InnerText;

                    // extract the secret key and serial
                    byte[] bytes = StringToByteArray(data);
                    // decrpyt with the fixed key
                    for (int i = bytes.Length - 1; i >= 0; i--)
                    {
                        bytes[i] ^= MOBILE_AUTHENTICATOR_KEY[i];
                    }
                    // decode and set members
                    string full = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    authenticator.SecretData = full;

                    // get offset value
                    long offset = 0;
                    node = rootnode.SelectSingleNode("/map/long[@name='" + BMA_OFFSET_NAME + "']");
                    if (node != null && LongTryParse(node.Attributes["value"].InnerText, out offset) /* long.TryParse(node.Attributes["value"].InnerText, out offset) == true */)
                    {
                        authenticator.ServerTimeDiff = offset;
                    }

                    return(authenticator);
                }

                // read <= 1.6 config
                if (version <= (decimal)1.6 && (node = rootnode.SelectSingleNode("secretdata")) != null)
                {
                    // save off the processed decryptions so we can send bug report
                    List <string> datas = new List <string>();
                    string        data  = node.InnerText;
                    datas.Add(data);

                    XmlAttribute attr = node.Attributes["encrypted"];
                    if (attr != null && attr.InnerText.Length != 0)
                    {
                        string encryptedType = attr.InnerText;
                        if (encryptedType == "u")
                        {
                            // we are going to decrypt with the Windows User account key
                            authenticator.PasswordType = PasswordTypes.User;
                            byte[] cipher = StringToByteArray(data);
                            byte[] plain  = ProtectedData.Unprotect(cipher, null, DataProtectionScope.CurrentUser);
                            data = ByteArrayToString(plain);
                            datas.Add(data);
                        }
                        else if (encryptedType == "m")
                        {
                            // we are going to decrypt with the Windows local machine key
                            authenticator.PasswordType = PasswordTypes.Machine;
                            byte[] cipher = StringToByteArray(data);
                            byte[] plain  = ProtectedData.Unprotect(cipher, null, DataProtectionScope.LocalMachine);
                            data = ByteArrayToString(plain);
                            datas.Add(data);
                        }
                        else if (encryptedType == "y")
                        {
                            // we use an explicit password to encrypt data
                            if (string.IsNullOrEmpty(password) == true)
                            {
                                throw new EncrpytedSecretDataException();
                            }
                            authenticator.PasswordType = PasswordTypes.Explicit;
                            authenticator.Password     = password;
                            data = Decrypt(data, password, false);
                            datas.Add(data);
                        }
                    }
                    try
                    {
                        authenticator.SecretData = ConvertAndriodSecretData(data);
                    }
                    catch (Exception ex)
                    {
                        // we get a decode error if the data decrypted but isn't valid
                        throw new InvalidSecretDataException(ex, password, (attr != null ? attr.InnerText : null), datas);
                    }

                    long offset = 0;
                    node = rootnode.SelectSingleNode("servertimediff");
                    if (node != null && LongTryParse(node.InnerText, out offset) == true /* long.TryParse(node.InnerText, out offset) == true */)
                    {
                        authenticator.ServerTimeDiff = offset;
                    }

                    node = rootnode.SelectSingleNode("restorecodeverified");
                    if (node != null && string.Compare(node.InnerText, bool.TrueString.ToLower(), true) == 0)
                    {
                        authenticator.RestoreCodeVerified = true;
                    }

                    return(authenticator);
                }

                // read current config
                if ((node = rootnode.SelectSingleNode("secretdata")) != null)
                {
                    // save off the processed decryptions so we can send bug report
                    string        data  = node.InnerText;
                    XmlAttribute  attr  = node.Attributes["encrypted"];
                    List <string> datas = new List <string>();
                    datas.Add(data);
                    PasswordTypes passwordType = PasswordTypes.None;
                    if (attr != null && attr.InnerText.Length != 0)
                    {
                        char[] encTypes = attr.InnerText.ToCharArray();
                        // we read the string in reverse order (the order they were encrypted)
                        for (int i = encTypes.Length - 1; i >= 0; i--)
                        {
                            char encryptedType = encTypes[i];
                            switch (encryptedType)
                            {
                            case 'u':
                            {
                                // we are going to decrypt with the Windows User account key
                                try
                                {
                                    passwordType |= PasswordTypes.User;
                                    byte[] cipher = StringToByteArray(data);
                                    byte[] plain  = ProtectedData.Unprotect(cipher, null, DataProtectionScope.CurrentUser);
                                    data = ByteArrayToString(plain);
                                    datas.Add(data);
                                }
                                catch (System.Security.Cryptography.CryptographicException)
                                {
                                    throw new InvalidUserDecryptionException();
                                }
                                break;
                            }

                            case 'm':
                            {
                                // we are going to decrypt with the Windows local machine key
                                try
                                {
                                    passwordType |= PasswordTypes.Machine;
                                    byte[] cipher = StringToByteArray(data);
                                    byte[] plain  = ProtectedData.Unprotect(cipher, null, DataProtectionScope.LocalMachine);
                                    data = ByteArrayToString(plain);
                                    datas.Add(data);
                                }
                                catch (System.Security.Cryptography.CryptographicException)
                                {
                                    throw new InvalidMachineDecryptionException();
                                }
                                break;
                            }

                            case 'y':
                            {
                                // we use an explicit password to encrypt data
                                if (string.IsNullOrEmpty(password) == true)
                                {
                                    throw new EncrpytedSecretDataException();
                                }
                                passwordType          |= PasswordTypes.Explicit;
                                authenticator.Password = password;
                                data = Decrypt(data, password, true);
                                datas.Add(data);
                                break;
                            }

                            default:
                                break;
                            }
                        }
                        authenticator.PasswordType = passwordType;
                    }
                    try
                    {
                        // pre-version 2 we kept compatability with the Android file
                        if (version < (decimal)2)
                        {
                            data = ConvertAndriodSecretData(data);
                        }
                        authenticator.SecretData = data;
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidSecretDataException(ex, password, (attr != null ? attr.InnerText : null), datas);
                    }

                    long offset = 0;
                    node = rootnode.SelectSingleNode("servertimediff");
                    if (node != null && LongTryParse(node.InnerText, out offset) == true /* long.TryParse(node.InnerText, out offset) == true */)
                    {
                        authenticator.ServerTimeDiff = offset;
                    }

                    node = rootnode.SelectSingleNode("restorecodeverified");
                    if (node != null && string.Compare(node.InnerText, bool.TrueString.ToLower(), true) == 0)
                    {
                        authenticator.RestoreCodeVerified = true;
                    }

                    return(authenticator);
                }

                throw new InvalidOperationException();
            }
        }
        /// <summary>
        /// Decrypt a string sequence using the selected encryption types
        /// </summary>
        /// <param name="data">hex coded string sequence to decrypt</param>
        /// <param name="encryptedTypes">Encryption types</param>
        /// <param name="password">optional password</param>
        /// <param name="decode"></param>
        /// <returns>decrypted string sequence</returns>
        private static string DecryptSequenceNoHash(string data, PasswordTypes encryptedTypes, string?password, bool decode = false)
        {
            try
            {
                // reverse order they were encrypted
                if ((encryptedTypes & PasswordTypes.Machine) != 0)
                {
                    // we are going to decrypt with the Windows local machine key
                    var cipher = StringToByteArray(data);
                    var plain  = IProtectedData.Instance.Unprotect(cipher, null, IProtectedData.DataProtectionScope.LocalMachine);
                    if (decode == true)
                    {
                        data = Encoding.UTF8.GetString(plain, 0, plain.Length);
                    }
                    else
                    {
                        data = ByteArrayToString(plain);
                    }
                }
                if ((encryptedTypes & PasswordTypes.User) != 0)
                {
                    // we are going to decrypt with the Windows User account key
                    var cipher = StringToByteArray(data);
                    var plain  = IProtectedData.Instance.Unprotect(cipher, null, IProtectedData.DataProtectionScope.CurrentUser);
                    if (decode == true)
                    {
                        data = Encoding.UTF8.GetString(plain, 0, plain.Length);
                    }
                    else
                    {
                        data = ByteArrayToString(plain);
                    }
                }
                if ((encryptedTypes & PasswordTypes.Explicit) != 0)
                {
                    // we use an explicit password to encrypt data
                    if (string.IsNullOrEmpty(password) == true)
                    {
                        throw new WinAuthEncryptedSecretDataException();
                    }
                    data = Decrypt(data, password, true);
                    if (decode == true)
                    {
                        var plain = StringToByteArray(data);
                        data = Encoding.UTF8.GetString(plain, 0, plain.Length);
                    }
                }
                if ((encryptedTypes & PasswordTypes.YubiKeySlot1) != 0 || (encryptedTypes & PasswordTypes.YubiKeySlot2) != 0)
                {
                    throw new NotSupportedException();
                }
            }
            catch (WinAuthEncryptedSecretDataException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new WinAuthBadPasswordException(ex.Message, ex);
            }

            return(data);
        }
Ejemplo n.º 13
0
        private void Init(PasswordTypes passwordTypes, bool isEdit)
        {
            _passwordTypes = passwordTypes;

            if (isEdit)
            {
                Text = "Редактировать тип";

                btnSelect.Visible = false;
                btnClose.Text = "Закрыть";
            }
            else
            {
                Text = "Выбрать тип";

                dgvItems.DoubleClick -= BtnEditClick;
                dgvItems.DoubleClick += BtnSelectClick;
            }

            Fill();
            RefreshUI();
        }
Ejemplo n.º 14
0
		public static string EncryptSequence(string data, PasswordTypes passwordType, string password)
		{
			// get hash of original
			string salt;
			using (var random = new RNGCryptoServiceProvider())
			{
				byte[] saltbytes = new byte[SALT_LENGTH];
				random.GetBytes(saltbytes);
				salt = ByteArrayToString(saltbytes);
			}
			string hash;
			using (var sha = new SHA256Managed())
			{
				byte[] plain = StringToByteArray(salt + data);
				hash = ByteArrayToString(sha.ComputeHash(plain));
			}

			if ((passwordType & PasswordTypes.Explicit) != 0)
			{
				string encrypted = Encrypt(data, password);

				// test the encryption
				string decrypted = Decrypt(encrypted, password, true);
				if (string.Compare(data, decrypted) != 0)
				{
					throw new InvalidEncryptionException(data, password, encrypted, decrypted);
				}
				data = encrypted;
			}
			if ((passwordType & PasswordTypes.User) != 0)
			{
				// we encrypt the data using the Windows User account key
				byte[] plain = StringToByteArray(data);
				byte[] cipher = ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser);
				data = ByteArrayToString(cipher);
			}
			if ((passwordType & PasswordTypes.Machine) != 0)
			{
				// we encrypt the data using the Local Machine account key
				byte[] plain = StringToByteArray(data);
				byte[] cipher = ProtectedData.Protect(plain, null, DataProtectionScope.LocalMachine);
				data = ByteArrayToString(cipher);
			}

			// prepend the salt + hash
			return ENCRYPTION_HEADER + salt + hash + data;
		}
Ejemplo n.º 15
0
		//public static void Log(string message)
		//{
		//	try
		//	{
		//		string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
		//		File.AppendAllText(Path.Combine(dir, "winauth.log"), message);
		//	}
		//	catch (Exception) { }
		//}

		private static string DecryptSequenceNoHash(
			string data,
			PasswordTypes encryptedTypes,
			string password,
			bool decode = false)
		{
			try
			{
				// reverse order they were encrypted
				if ((encryptedTypes & PasswordTypes.Machine) != 0)
				{
					// we are going to decrypt with the Windows local machine key
					byte[] cipher = StringToByteArray(data);
					//Log("Decrypt Machine: " + data + Environment.NewLine);
					byte[] plain = ProtectedData.Unprotect(cipher, null, DataProtectionScope.LocalMachine);
					if (decode == true)
					{
						//Log("Decode Machine: " + ByteArrayToString(plain) + Environment.NewLine);
						data = Encoding.UTF8.GetString(plain, 0, plain.Length);
					}
					else
					{
						data = ByteArrayToString(plain);
					}
					//Log("Decrypted Machine: " + data + Environment.NewLine);
				}
				if ((encryptedTypes & PasswordTypes.User) != 0)
				{
					// we are going to decrypt with the Windows User account key
					byte[] cipher = StringToByteArray(data);
					//Log("Decrypt User: "******"Decode User: "******"Decrypted User: "******"Decrypt Explicit: " + password + " " + data + Environment.NewLine);
					data = Decrypt(data, password, true);
					//Log("Decrypted Explicit: " + data + Environment.NewLine);
					if (decode == true)
					{
						byte[] plain = StringToByteArray(data);
						data = Encoding.UTF8.GetString(plain, 0, plain.Length);
						//Log("Decode Explicit: " + data + Environment.NewLine);
					}
				}
			}
			catch (EncrpytedSecretDataException)
			{
				throw;
			}
			catch (Exception ex)
			{
				throw new BadPasswordException(ex.Message, ex);
			}

			return data;
		}
Ejemplo n.º 16
0
        public bool ReadXml(XmlReader reader, string password = null)
        {
            // decode the password type
            string        encrypted    = reader.GetAttribute("encrypted");
            PasswordTypes passwordType = DecodePasswordTypes(encrypted);

            PasswordType = passwordType;

            if (passwordType != PasswordTypes.None)
            {
                // read the encrypted text from the node
                EncryptedData = reader.ReadElementContentAsString();
                return(Unprotect(password));

                //// decrypt
                //try
                //{
                //	string data = Authenticator.DecryptSequence(this.EncryptedData, passwordType, password);
                //	using (MemoryStream ms = new MemoryStream(Authenticator.StringToByteArray(data)))
                //	{
                //		reader = XmlReader.Create(ms);
                //		this.ReadXml(reader, password);
                //	}
                //}
                //catch (EncrpytedSecretDataException)
                //{
                //	this.RequiresPassword = true;
                //	throw;
                //}
                //finally
                //{
                //	this.PasswordType = passwordType;
                //}
            }

            reader.MoveToContent();
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return(false);
            }

            reader.Read();
            while (reader.EOF == false)
            {
                if (reader.IsStartElement())
                {
                    switch (reader.Name)
                    {
                    case "lastservertime":
                        LastServerTime = reader.ReadElementContentAsLong();
                        break;

                    case "servertimediff":
                        ServerTimeDiff = reader.ReadElementContentAsLong();
                        break;

                    case "secretdata":
                        SecretData = reader.ReadElementContentAsString();
                        break;

                    default:
                        if (ReadExtraXml(reader, reader.Name) == false)
                        {
                            reader.Skip();
                        }
                        break;
                    }
                }
                else
                {
                    reader.Read();
                    break;
                }
            }

            // check if we need to sync, or if it's been a day
            if (ServerTimeDiff == 0 || LastServerTime == 0 || LastServerTime < DateTime.Now.AddHours(-24).Ticks)
            {
                Sync();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 17
0
        public bool Unprotect(string password)
        {
            PasswordTypes passwordType = PasswordType;

            if (passwordType == PasswordTypes.None)
            {
                throw new InvalidOperationException("Cannot Unprotect a non-encrypted authenticator");
            }

            // decrypt
            bool changed = false;

            try
            {
                string data = DecryptSequence(EncryptedData, PasswordType, password);
                using (MemoryStream ms = new MemoryStream(StringToByteArray(data)))
                {
                    XmlReader reader = XmlReader.Create(ms);
                    changed = ReadXml(reader, password) || changed;
                }
                RequiresPassword = false;
                // calculate hash of current secretdata
                using (SHA1 sha1 = SHA1.Create())
                {
                    SecretHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(SecretData));
                }
                // keep the password until we reprotect in case data changes
                Password = password;

                if (changed == true)
                {
                    // we need to encrypt changed secret data
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // get the plain version
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.Indent   = true;
                        settings.Encoding = Encoding.UTF8;
                        using (XmlWriter encryptedwriter = XmlWriter.Create(ms, settings))
                        {
                            WriteToWriter(encryptedwriter);
                        }
                        string encrypteddata = ByteArrayToString(ms.ToArray());

                        // update secret hash
                        using (SHA1 sha1 = SHA1.Create())
                        {
                            SecretHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(SecretData));
                        }

                        // encrypt
                        EncryptedData = EncryptSequence(encrypteddata, passwordType, password);
                    }
                }

                return(changed);
            }
            catch (EncrpytedSecretDataException)
            {
                RequiresPassword = true;
                throw;
            }
            finally
            {
                PasswordType = passwordType;
            }
        }
Ejemplo n.º 18
0
        public static Authenticator ReadXmlv2(XmlReader reader, string password = null)
        {
            Authenticator authenticator     = null;
            string        authenticatorType = reader.GetAttribute("type");

            if (string.IsNullOrEmpty(authenticatorType) == false)
            {
                authenticatorType = authenticatorType.Replace("WindowsAuthenticator.", "WinAuth.");
                Type type = Assembly.GetExecutingAssembly().GetType(authenticatorType, false, true);
                authenticator = Activator.CreateInstance(type) as Authenticator;
            }
            if (authenticator == null)
            {
                authenticator = new BattleNetAuthenticator();
            }

            reader.MoveToContent();
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return(null);
            }

            reader.Read();
            while (reader.EOF == false)
            {
                if (reader.IsStartElement())
                {
                    switch (reader.Name)
                    {
                    case "servertimediff":
                        authenticator.ServerTimeDiff = reader.ReadElementContentAsLong();
                        break;

                    //case "restorecodeverified":
                    //	authenticator.RestoreCodeVerified = reader.ReadElementContentAsBoolean();
                    //	break;

                    case "secretdata":
                        string encrypted = reader.GetAttribute("encrypted");
                        string data      = reader.ReadElementContentAsString();

                        PasswordTypes passwordType = DecodePasswordTypes(encrypted);

                        if (passwordType != PasswordTypes.None)
                        {
                            // this is an old version so there is no hash
                            data = DecryptSequence(data, passwordType, password);
                        }

                        authenticator.PasswordType = PasswordTypes.None;
                        authenticator.SecretData   = data;

                        break;

                    default:
                        if (authenticator.ReadExtraXml(reader, reader.Name) == false)
                        {
                            reader.Skip();
                        }
                        break;
                    }
                }
                else
                {
                    reader.Read();
                    break;
                }
            }

            return(authenticator);
        }
Ejemplo n.º 19
0
 public MsgShowConfirmPassword(System.Security.SecureString password, PasswordTypes type)
 {
     this.OriginalPassword = password;
     this.PasswordType     = type;
 }
Ejemplo n.º 20
0
 public void SetUsernameToken(string username, string password, PasswordTypes type = PasswordTypes.PasswordText)
 {
     _usernameToken = new UsernameToken {
         Username = username, Password = password, Type = type
     };
 }