/// <summary> /// Is the code authorised. /// </summary> /// <returns>True if authorised; else false.</returns> private bool IsAuthorised() { if (!String.IsNullOrEmpty(_authorisationCode)) { string authorisationKey = ""; try { // Convert the HEX string to bytes. byte[] bytes = Nequeo.Conversion.Context.HexStringToByteArray(_authorisationCode); // Decrypt the data byte[] decryptedData = new Nequeo.Cryptography.AdvancedAES().DecryptFromMemory(bytes, KeyContainer._authorisationCryptoKey); authorisationKey = Encoding.Default.GetString(decryptedData).Replace("\0", ""); } catch { } // If the keys match then authorise. if (_authorisationKey.Equals(authorisationKey)) { return(true); } else { return(false); } } else { return(false); } }
/// <summary> /// Set the password if it exists else create new entry. /// </summary> /// <param name="storeName">The name of the password loaded from the store.</param> /// <param name="storePassword">The password to store for the name.</param> public void SetPassword(string storeName, string storePassword) { // Make sure data exists. if (KeyContainer._passwords != null) { // Find all. IEnumerable <Nequeo.Model.NameValue> pass = KeyContainer._passwords.Where(u => u.Name.Equals(storeName)); if (pass != null && pass.Count() > 0) { // Update the password. byte[] data = Encoding.Unicode.GetBytes(storePassword); byte[] password = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, KeyContainer._passwordKey); pass.First().Value = Convert.ToBase64String(password); } else { // Create a new password. byte[] data = Encoding.Unicode.GetBytes(storePassword); byte[] password = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, KeyContainer._passwordKey); string value = Convert.ToBase64String(password); // Add the password. KeyContainer._passwords.Add(new Model.NameValue() { Name = storeName, Value = value }); } } else { throw new Exception("Load the password store data first."); } }
/// <summary> /// Get the password for the specified name from the store. /// </summary> /// <param name="storeName">The name of the password loaded from the store.</param> /// <returns>The password; else null.</returns> public string GetPassword(string storeName) { // If authorised. if (IsAuthorised()) { // Make sure data exists. if (KeyContainer._passwords != null) { // Find all. IEnumerable <Nequeo.Model.NameValue> pass = KeyContainer._passwords.Where(u => u.Name.Equals(storeName)); if (pass != null && pass.Count() > 0) { // Decrypt the stored password. byte[] data = Encoding.Unicode.GetBytes(pass.First().Value); byte[] password = new Nequeo.Cryptography.AdvancedAES().DecryptFromMemory(data, KeyContainer._passwordKey); return(Encoding.Unicode.GetString(password)); } else { return(null); } } else { throw new Exception("Load the password store data first."); } } else { throw new Exception("Authorisation Failed."); } }
/// <summary> /// Get the encrypted authorisation code. /// </summary> /// <returns>The encrypted base64 authorisation code used for access.</returns> public string GetAuthorisationCode() { byte[] data = Encoding.Default.GetBytes(_authorisationKey); byte[] encryptedData = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, KeyContainer._authorisationCryptoKey); string encryptedBase64AuthorisationCode = Nequeo.Conversion.Context.ByteArrayToHexString(encryptedData); // Current encrypted Base64 authorisation code. return(encryptedBase64AuthorisationCode); }
/// <summary> /// Decode the password. /// </summary> /// <param name="password">The password to decode.</param> /// <param name="passwordFormat">The password format type to decode with.</param> /// <param name="originalPassword">The original password (used when format is Hashed).</param> /// <param name="hashcodeType">The the hash code type (used when format is Hashed).</param> /// <returns>The decoded password (if format is Hashed and the hash has been verified to be /// the same then the original password is returned; else the password is returned).</returns> public string Decode(string password, Cryptography.PasswordFormat passwordFormat, string originalPassword = "", Nequeo.Cryptography.HashcodeType hashcodeType = Cryptography.HashcodeType.SHA512) { // If authorised. if (IsAuthorised()) { // Select the format. switch (passwordFormat) { case Cryptography.PasswordFormat.Encrypted: // Convert the HEX string to bytes. byte[] bytes = Nequeo.Conversion.Context.HexStringToByteArray(password); // Decrypt the data byte[] decryptedData = new Nequeo.Cryptography.AdvancedAES().DecryptFromMemory(bytes, KeyContainer._passwordKey); return(Encoding.Default.GetString(decryptedData).Replace("\0", "")); case Cryptography.PasswordFormat.Hashed: // Get the salt. string saltBase = password.Substring(0, KeyContainer._saltLength * 2); byte[] saltBaseBytes = Nequeo.Conversion.Context.HexStringToByteArray(saltBase); string salt = Encoding.Default.GetString(saltBaseBytes); // Return the salt for the hash. string hash = Nequeo.Cryptography.Hashcode.GetHashcode(originalPassword + _authorisationKey + salt, hashcodeType); // Get the hex salt. byte[] saltBase64 = Encoding.Default.GetBytes(salt); string hashed = Nequeo.Conversion.Context.ByteArrayToHexString(saltBase64) + hash; // If the hash is the password. if (hashed.Equals(password)) { return(originalPassword); } else { return(password); } case Cryptography.PasswordFormat.Clear: default: return(password); } } else { if (passwordFormat == Cryptography.PasswordFormat.Clear) { return(password); } else { throw new Exception("Authorisation Failed."); } } }
/// <summary> /// Get the encrypted authorisation code. /// </summary> /// <returns>The encrypted base64 authorisation code used for access.</returns> public string EncryptedAuthorisationCode() { byte[] data = Encoding.Default.GetBytes(_authorisationKey); byte[] encryptedData = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, KeyContainer._authorisationCryptoKey); string encryptedBase64AuthorisationCode = Nequeo.Conversion.Context.ByteArrayToHexString(encryptedData); // Current encrypted Base64 authorisation code. return(encryptedBase64AuthorisationCode); // 46638A1D3B7F9502B8460824FB75841E1DF38537EBAACA5163DB7529D38063AE }
/// <summary> /// Encrypt the password. /// </summary> /// <param name="password">The password to encrypt.</param> /// <param name="key">The key used to encrypt the password.</param> /// <returns>The encrypted password.</returns> public string Encrypt(string password, string key) { // If authorised. if (IsAuthorised()) { // Encrypt the data. byte[] data = Encoding.Default.GetBytes(password); byte[] encryptedData = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, key); return(Nequeo.Conversion.Context.ByteArrayToHexString(encryptedData)); } else { throw new Exception("Authorisation Failed."); } }
/// <summary> /// Decrypt the password. /// </summary> /// <param name="password">The encrypted password.</param> /// <param name="key">The key used to decrypt the password.</param> /// <returns>The decrypted password.</returns> public string Decrypt(string password, string key) { // If authorised. if (IsAuthorised()) { // Decrypt the data. byte[] bytes = Nequeo.Conversion.Context.HexStringToByteArray(password); byte[] decryptedData = new Nequeo.Cryptography.AdvancedAES().DecryptFromMemory(bytes, key); return(Encoding.Default.GetString(decryptedData).Replace("\0", "")); } else { throw new Exception("Authorisation Failed."); } }
/// <summary> /// Encode the password. /// </summary> /// <param name="password">The password to encode.</param> /// <param name="passwordFormat">The password format type to encode with.</param> /// <param name="hashcodeType">The hash code type (used when format is Hashed).</param> /// <returns>The encode password (includes at the start of the password the encoded salt).</returns> public string Encode(string password, Cryptography.PasswordFormat passwordFormat, Nequeo.Cryptography.HashcodeType hashcodeType = Cryptography.HashcodeType.SHA512) { // If authorised. if (IsAuthorised()) { // Select the format. switch (passwordFormat) { case Cryptography.PasswordFormat.Encrypted: // Encrypt the data. byte[] data = Encoding.Default.GetBytes(password); byte[] encryptedData = new Nequeo.Cryptography.AdvancedAES().EncryptToMemory(data, KeyContainer._passwordKey); return(Nequeo.Conversion.Context.ByteArrayToHexString(encryptedData)); case Cryptography.PasswordFormat.Hashed: // Encode the password to a hash. string salt = Nequeo.Cryptography.Hashcode.GenerateSalt(KeyContainer._saltLength, KeyContainer._saltLength); byte[] saltBase = Encoding.Default.GetBytes(salt); // Password - based Key Derivation Functions. Rfc2898DeriveBytes rfcDerive = new Rfc2898DeriveBytes(password, saltBase, KeyContainer._numberOfIterations); string derivedPassword = Encoding.Default.GetString(rfcDerive.GetBytes(KeyContainer._saltLength * 2)); // Get the hex salt. string hash = Nequeo.Cryptography.Hashcode.GetHashcode(derivedPassword + _authorisationKey + salt, hashcodeType); _encodedSalt = Nequeo.Conversion.Context.ByteArrayToHexString(saltBase); return(_encodedSalt + hash); case Cryptography.PasswordFormat.Clear: default: return(password); } } else { if (passwordFormat == Cryptography.PasswordFormat.Clear) { return(password); } else { throw new Exception("Authorisation Failed."); } } }
/// <summary> /// Load the passwords from the stream. /// </summary> /// <param name="store">The stream where the password store is read from.</param> public void LoadPasswordStore(Stream store) { // If authorised. if (IsAuthorised()) { // If the store contains data. if (store != null && store.Length > 0) { // Go to the start of the stream. store.Position = 0; // Decrypt the password store. byte[] passwordStore = new Nequeo.Cryptography.AdvancedAES().DecryptStream(store, KeyContainer._authorisationCryptoKey); // Load the password data. string passwordData = Encoding.Unicode.GetString(passwordStore); string[] names = passwordData.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); // Load into the name value collection. KeyContainer._passwords = new List <Model.NameValue>(names.Length); for (int i = 0; i < names.Length; i++) { // Get the name and value. string[] nameValue = names[i].Split(new char[] { ':' }, StringSplitOptions.None); string name = nameValue[0].Trim(); string value = nameValue[1].Trim(); // Add the name and password. KeyContainer._passwords.Add(new Model.NameValue() { Name = name, Value = value }); } } else { // Create an empty password store. KeyContainer._passwords = new List <Model.NameValue>(); } } else { throw new Exception("Authorisation Failed."); } }
/// <summary> /// Save the password store data to the stream. /// </summary> /// <param name="store">The stream where the password store is written to.</param> public void SavePasswordStore(Stream store) { // If authorised. if (IsAuthorised()) { // If the stream is null. if (store == null) { throw new ArgumentNullException("store"); } // Make sure data exists. if (KeyContainer._passwords == null) { // Create an empty password store. KeyContainer._passwords = new List <Model.NameValue>(); } MemoryStream memoryStream = null; try { // Create a new MemoryStream using the passed // array of encrypted data. using (memoryStream = new MemoryStream()) { // For each password. for (int i = 0; i < KeyContainer._passwords.Count; i++) { // Assing the values. string name = KeyContainer._passwords[i].Name; string value = KeyContainer._passwords[i].Value; string end = (i == KeyContainer._passwords.Count - 1 ? "" : "\r\n"); // Create the buffer. byte[] buffer = Encoding.Unicode.GetBytes(name + ":" + value + end); memoryStream.Write(buffer, 0, buffer.Length); } // Reset the position of the memory stream. memoryStream.Position = 0; // Encrypt the password store and write // the data to the user stream. byte[] passwordStore = new Nequeo.Cryptography.AdvancedAES().EncryptStream(memoryStream, KeyContainer._authorisationCryptoKey); store.Write(passwordStore, 0, passwordStore.Length); } } catch { } finally { // Release all resources. if (memoryStream != null) { memoryStream.Close(); } } } else { throw new Exception("Authorisation Failed."); } }