/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText">Plaintext value to be hashed. The function does not check whether this parameter is null.</param> /// <param name="mode">Password encryption mode.</param> /// <returns> /// Password hash and salt. /// </returns> public static PasswordHash Encrypt(String plainText, PasswordMode mode) { PasswordHash result; if (hashAlgorithmMapping.ContainsKey(mode)) { HashAlgorithm algorithm = hashAlgorithmMapping[mode]; var saltBytes = new byte[SaltLength]; RandomNumberGenerator.Create().GetBytes(saltBytes); var passwordBytes = Encoding.UTF8.GetBytes(plainText); var hashBytes = Encrypt(passwordBytes, saltBytes, algorithm); result = new PasswordHash { Salt = Convert.ToBase64String(saltBytes), Hash = Convert.ToBase64String(hashBytes) }; } else { result = new PasswordHash { Salt = String.Empty, Hash = plainText }; } return(result); }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText">Plaintext value to be hashed. The function does not check whether this parameter is null.</param> /// <param name="mode">Password encryption mode.</param> /// <param name="salt">Random bits that are used as one of the inputs to a key derivation function (formatted as a base64-encoded string).</param> /// <returns>Password hash and salt.</returns> public static PasswordHash Encrypt(String plainText, PasswordMode mode, String salt) { PasswordHash result; if (hashAlgorithmMapping.ContainsKey(mode)) { HashAlgorithm algorithm = hashAlgorithmMapping[mode]; var saltBytes = Convert.FromBase64String(salt); var passwordBytes = Encoding.UTF8.GetBytes(plainText); var hashBytes = Encrypt(passwordBytes, saltBytes, algorithm); result = new PasswordHash { Salt = salt, Hash = Convert.ToBase64String(hashBytes) }; } else { result = new PasswordHash { Salt = String.Empty, Hash = plainText }; } return(result); }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText">Plaintext value to be hashed. The function does not check whether this parameter is null.</param> /// <param name="mode">Password encryption mode.</param> /// <returns> /// Password hash and salt. /// </returns> public static PasswordHash Encrypt(String plainText, PasswordMode mode) { PasswordHash result; if (hashAlgorithmMapping.ContainsKey(mode)) { HashAlgorithm algorithm = hashAlgorithmMapping[mode]; var saltBytes = new byte[SaltLength]; RandomNumberGenerator.Create().GetBytes(saltBytes); var passwordBytes = Encoding.UTF8.GetBytes(plainText); var hashBytes = Encrypt(passwordBytes, saltBytes, algorithm); result = new PasswordHash { Salt = Convert.ToBase64String(saltBytes), Hash = Convert.ToBase64String(hashBytes) }; } else { result = new PasswordHash { Salt = String.Empty, Hash = plainText }; } return result; }
public PasswordOption GenerateDecompressPasswordOption(PasswordMode passwordMode, string keysFolder) { switch (passwordMode) { case PasswordMode.None: return(NoPasswordOption.Nop); case PasswordMode.InlinePassword: return(new InlinePasswordOption { Password = _pass.ToString("N") }); case PasswordMode.PasswordFile: return(new PasswordFileOption { PasswordFile = Path.Combine(keysFolder, "password.txt") }); case PasswordMode.PublicKey: return(new PrivateKeyPasswordOption { PrivateKeyFile = Path.Combine(keysFolder, "private.pem") }); default: throw new ArgumentOutOfRangeException(nameof(passwordMode), passwordMode, null); } }
/// <summary> /// Generates a hash for the given plain text value and returns a /// base64-encoded result. Before the hash is computed, a random salt /// is generated and appended to the plain text. This salt is stored at /// the end of the hash value, so it can be used later for hash /// verification. /// </summary> /// <param name="plainText">Plaintext value to be hashed. The function does not check whether this parameter is null.</param> /// <param name="mode">Password encryption mode.</param> /// <param name="salt">Random bits that are used as one of the inputs to a key derivation function (formatted as a base64-encoded string).</param> /// <returns>Password hash and salt.</returns> public static PasswordHash Encrypt(String plainText, PasswordMode mode, String salt) { PasswordHash result; if (hashAlgorithmMapping.ContainsKey(mode)) { HashAlgorithm algorithm = hashAlgorithmMapping[mode]; var saltBytes = Convert.FromBase64String(salt); var passwordBytes = Encoding.UTF8.GetBytes(plainText); var hashBytes = Encrypt(passwordBytes, saltBytes, algorithm); result = new PasswordHash { Salt = salt, Hash = Convert.ToBase64String(hashBytes) }; } else { result = new PasswordHash { Salt = String.Empty, Hash = plainText }; } return result; }
/// <summary> /// Creates a new password from the display version of a password /// </summary> /// <param name="password">The password display version</param> /// <param name="mode">The password mode</param> public Rayman1PS1Password(string password, PasswordMode mode) { if (mode == PasswordMode.PAL) { throw new NotImplementedException(); } Password = password.ToLower().Select(b => (byte)Array.FindIndex(PasswordDisplayTable[mode], x => (char)x == b)).ToArray(); Mode = mode; }
/* * * A PS1 password always consist of 10 bytes. These bytes can be in several forms: * * Indexed -> Each byte is an index 0-31 * Encrypted -> Use PasswordIndexTranslateTable[] on each indexed byte to get the encrypted data * Decrypted -> Use VerifyAndDecrypt() on an encrypted password, this is the data we need to get the data from the password * * Display -> Use PasswordDisplayTable[] on each encrypted byte, this will give the character representation of each byte to display * */ #region Constructors /// <summary> /// Creates a new password from the encrypted password data /// </summary> /// <param name="encryptedPassword">The encrypted password</param> /// <param name="mode">The password mode</param> public Rayman1PS1Password(byte[] encryptedPassword, PasswordMode mode) { if (mode == PasswordMode.PAL) { throw new NotImplementedException(); } Password = encryptedPassword; Mode = mode; }
private async Task <OperationSummary> Decompress(PasswordMode passwordMode, string decompressedFolder, string keysFolder, TestData decomp) { var decompOption = decomp.GetTccDecompressOption(decompressedFolder); decompOption.PasswordOption = _benchmarkOptionHelper.GenerateDecompressPasswordOption(passwordMode, keysFolder); var resultDecompress = await _tarCompressCrypt.Decompress(decompOption); return(resultDecompress); }
private async Task <OperationSummary> Compress(PasswordMode passwordMode, CompressionAlgo algo, string compressedFolder, string keysFolder, TestData data) { CompressOption compressOption = data.GetTccCompressOption(compressedFolder, algo); compressOption.PasswordOption = await _benchmarkOptionHelper.GenerateCompressPasswordOption(passwordMode, keysFolder); var resultCompress = await _tarCompressCrypt.Compress(compressOption); return(resultCompress); }
public virtual void SetPassword(PasswordMode mode, string text) { switch (mode) { case PasswordMode.KKMAdministrator: _pkkmadm = text; break; case PasswordMode.SystemAdministrator: _psysadm = text; break; case PasswordMode.Kassir: _pkass = text; break; case PasswordMode.Tehnik: _ptech = text; break; } }
public async Task EcryptionCommands(string command, string passchain, PasswordMode mode) { var commandBlocks = command.Split(" ", StringSplitOptions.RemoveEmptyEntries); if (passchain != null && passchain.Contains(".")) { passchain.CreateEmptyFile(); // we create fake pass files } var parsed = commandBlocks.ParseCommandLine(); Assert.Equal(mode, parsed.Option.PasswordOption.PasswordMode); string passfound = null; switch (parsed.Option.PasswordOption) { case InlinePasswordOption po: passfound = po.Password; break; case PasswordFileOption pf: passfound = pf.PasswordFile; break; case PublicKeyPasswordOption puk: passfound = puk.PublicKeyFile; break; case PrivateKeyPasswordOption pik: passfound = pik.PrivateKeyFile; break; case NoPasswordOption _: break; default: throw new NotImplementedException(); } Assert.Equal(passchain, passfound); Assert.Equal(0, parsed.ReturnCode); if (passchain != null && passchain.Contains(".")) { await passchain.TryDeleteFileWithRetryAsync(); } }
/// <summary> /// Creates a new password from save data /// </summary> /// <param name="save">The save</param> /// <param name="mode">The password mode</param> public Rayman1PS1Password(SaveData save, PasswordMode mode) { if (mode == PasswordMode.PAL) { throw new NotImplementedException(); } // Set the mode Mode = mode; // Create a decrypted password Password = new byte[10]; // Encode the password save.Process(Password, false); // Encrypt the password EncryptPassword(Password); }
/// <summary> /// Constructor. /// </summary> /// <param name="options"></param> /// <param name="passwordMode"></param> /// <param name="osdBackgroundDir"></param> public FormTools(Options options, PasswordMode passwordMode, string osdBackgroundDir) { _options = options; _passwordMode = passwordMode; _osdBackgroundDir = osdBackgroundDir; InitializeComponent(); // Our readonly row style for the grid view _rowStyleReadOnly = new DataGridViewCellStyle { Font = new Font(dgvTaskSequenceVariables.Font, FontStyle.Italic) }; // Enable quit button if debugging #if DEBUG buttonCloseApp.Visible = true; #endif }
public async Task <PasswordOption> GenerateCompressPasswordOption(PasswordMode passwordMode, string keysFolder) { switch (passwordMode) { case PasswordMode.None: return(NoPasswordOption.Nop); case PasswordMode.InlinePassword: return(new InlinePasswordOption { Password = _pass.ToString("N") }); case PasswordMode.PasswordFile: string passwordFile = Path.Combine(keysFolder, "password.txt"); TestFileHelper.FillFile(passwordFile, "123456"); return(new PasswordFileOption { PasswordFile = passwordFile }); case PasswordMode.PublicKey: { var e = _externalDependencies; var keyPair = await CreateKeyPairCommand(e.OpenSsl(), "keypair.pem", KeySize.Key4096).Run(keysFolder, _cancellationTokenSource.Token); var publicKey = await CreatePublicKeyCommand(e.OpenSsl(), "keypair.pem", "public.pem").Run(keysFolder, _cancellationTokenSource.Token); var privateKey = await CreatePrivateKeyCommand(e.OpenSsl(), "keypair.pem", "private.pem").Run(keysFolder, _cancellationTokenSource.Token); keyPair.ThrowOnError(); publicKey.ThrowOnError(); privateKey.ThrowOnError(); return(new PublicKeyPasswordOption { PublicKeyFile = Path.Combine(keysFolder, "public.pem") }); } default: throw new ArgumentOutOfRangeException(nameof(passwordMode), passwordMode, null); } }
private void buttonPasswordOK_Click(object sender, EventArgs e) { // If admin password blank then return in admin mode if (string.IsNullOrEmpty(_options.PasswordAdmin)) { DialogResult = DialogResult.OK; PasswordMode = PasswordMode.Admin; return; } // Check for admin password if (_options.PasswordAdmin == textBoxPassword.Text) { DialogResult = DialogResult.OK; PasswordMode = PasswordMode.Admin; return; } // If user password blank then return in user mode if (string.IsNullOrEmpty(_options.PasswordUser)) { DialogResult = DialogResult.OK; PasswordMode = PasswordMode.User; return; } // Check for user password if (_options.PasswordUser == textBoxPassword.Text) { DialogResult = DialogResult.OK; PasswordMode = PasswordMode.User; return; } // Error PasswordMode = PasswordMode.None; DialogResult = DialogResult.None; MessageBox.Show(Resources.InvalidPassword, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); textBoxPassword.Clear(); }
public async Task CompressDecompress(PasswordMode mode, CompressionAlgo algo) { await _externalDependencies.EnsureAllDependenciesPresent(); string toCompressFolder = TestFileHelper.NewFolder(); string compressedFolder = TestFileHelper.NewFolder(); string decompressedFolder = TestFileHelper.NewFolder(); string keysFolder = TestFileHelper.NewFolder(); var data = await TestData.CreateFiles(1, 1024, toCompressFolder); OperationSummary resultCompress = await Compress(mode, algo, compressedFolder, keysFolder, data); resultCompress.ThrowOnError(); Assert.True(resultCompress.IsSuccess); Assert.NotEmpty(resultCompress.OperationBlocks.Select(i => i.Block)); Assert.NotEmpty(resultCompress.OperationBlocks.Select(i => i.CommandResult)); var decomp = new TestData { Directories = new List <DirectoryInfo> { new DirectoryInfo(compressedFolder) } }; OperationSummary resultDecompress = await Decompress(mode, decompressedFolder, keysFolder, decomp); resultDecompress.ThrowOnError(); Assert.True(resultDecompress.IsSuccess); Assert.NotEmpty(resultDecompress.OperationBlocks.Select(i => i.Block)); Assert.NotEmpty(resultDecompress.OperationBlocks.Select(i => i.CommandResult)); FileInfo src = new DirectoryInfo(toCompressFolder).EnumerateFiles().FirstOrDefault(); FileInfo dst = new DirectoryInfo(decompressedFolder).EnumerateFiles().FirstOrDefault(); Assert.True(TestFileHelper.FilesAreEqual(src, dst)); }
public static Boolean ChangePassword(string uname, string password, PasswordMode mode) { SqlConnection conn = new SqlConnection(CnnString); String Pass = ""; switch (mode) { case PasswordMode.PlainText: { Pass = CryptographyHelper.CalculateHash(password, CryptographyHelper.HashMode.SHA1); break; } case PasswordMode.Hashed: { Pass = password; break; } } try { conn.Open(); SqlCommand cmd = new SqlCommand("", conn) { CommandType = CommandType.StoredProcedure, CommandText = "ChangePassword" }; cmd.Parameters.AddWithValue("PersonalNo", uname); cmd.Parameters.AddWithValue("Password", Pass); cmd.ExecuteNonQuery(); return true; } finally { conn.Close(); } }
private void buttonPasswordCancel_Click(object sender, EventArgs e) { PasswordMode = PasswordMode.None; DialogResult = DialogResult.Cancel; }
/// <summary> /// Compares a hash of the specified plain text value to a given hash /// value. Plain text is hashed with the same salt value as the original /// hash. /// </summary> /// <param name="plainText">Plain text to be verified against the specified hash. The function does not check whether this parameter is null.</param> /// <param name="expected">Password expected hash.</param> /// <param name="mode">Password encryption mode.</param> /// <returns> /// <c>true</c> if computed hash mathes the specified hash the function; otherwise <c>false</c>. /// </returns> public static bool Verify(String plainText, PasswordHash expected, PasswordMode mode) { var hash = Encrypt(plainText, mode, expected.Salt); return expected.Equals(hash); }
public async Task <OperationSummary> RunBenchmark(BenchmarkOption benchmarkOption) { var operationSummaries = new List <OperationSummary>(); var keysFolder = TestFileHelper.NewFolder(); var iterations = await _iterationGenerator.PrepareIteration(benchmarkOption); var threads = benchmarkOption.Threads == 0 ? Environment.ProcessorCount : benchmarkOption.Threads; foreach (var iteration in iterations) { PasswordMode pm = iteration.Encryption ? PasswordMode.PublicKey : PasswordMode.None; var compressedFolder = TestFileHelper.NewFolder(benchmarkOption.OutputCompressed); var outputFolder = TestFileHelper.NewFolder(benchmarkOption.OutputDecompressed); // compress var compressOption = new CompressOption { Algo = iteration.Algo, CompressionRatio = iteration.CompressionRatio, BlockMode = BlockMode.Individual, SourceDirOrFile = iteration.Content.Source, DestinationDir = compressedFolder, Threads = threads, PasswordOption = await _benchmarkOptionHelper.GenerateCompressPasswordOption(pm, keysFolder) }; OperationSummary resultCompress = await _tarCompressCrypt.Compress(compressOption); if (_cancellationTokenSource.IsCancellationRequested) { await Cleanup(); return(null); } operationSummaries.Add(resultCompress); resultCompress.ThrowOnError(); // decompress var decompressOption = new DecompressOption { SourceDirOrFile = compressedFolder, DestinationDir = outputFolder, Threads = threads, PasswordOption = _benchmarkOptionHelper.GenerateDecompressPasswordOption(pm, keysFolder) }; OperationSummary resultDecompress = await _tarCompressCrypt.Decompress(decompressOption); if (_cancellationTokenSource.IsCancellationRequested) { await Cleanup(); return(null); } operationSummaries.Add(resultDecompress); resultDecompress.ThrowOnError(); StringBuilder sb = FormatResultSummary(iteration, resultCompress, resultDecompress); Console.Out.WriteLine(sb.ToString()); async Task Cleanup() { if (benchmarkOption.Cleanup) { await "del /f /s /q * > NUL".Run(compressedFolder, CancellationToken.None); Directory.Delete(compressedFolder, true); await "del /f /s /q * > NUL".Run(outputFolder, CancellationToken.None); Directory.Delete(outputFolder, true); } } await Cleanup(); } return(new OperationSummary(operationSummaries.SelectMany(i => i.OperationBlocks), 0, default)); }
private bool ValidateUser() { bool IsAuthenticated = false; DataCommandService dataCommandDB = DataCommandService.GetInstance(); PageDB pageDB = new PageDB(); DataTable data = null; string password = String.Empty; List <ScreenDataCommandParameter> parameters = pageDB.GetPopulatedCommandParameters(Me.ProfileCommand, Page); foreach (ScreenDataCommandParameter p in parameters) { if (p.Name.ToLower() == Me.UserNameParameter.ToLower()) { LoginName = Page.GetEntityIDValue(Page.Screen, p.InputKey, p.InputType); break; } } password = Page.GetEntityIDValue(Page.Screen, Me.PasswordEntityID, Me.PasswordEntityInputType); data = dataCommandDB.GetDataForDataCommand(Me.ProfileCommand, parameters); if (data.Rows.Count == 1) { profile = data.Rows[0]; string dbPassword = profile[Me.PasswordField].ToString(); PasswordMode mode = Me.PasswordMode; if (!String.IsNullOrEmpty(dbPassword)) { switch (mode) { case PasswordMode.Hash: if (Cryptographer.CompareHash(Me.PasswordAlgorithm, password, dbPassword)) { IsAuthenticated = true; } break; case PasswordMode.Encrypted: string decryptedPassword = Cryptographer.DecryptSymmetric(Me.PasswordAlgorithm, dbPassword); if (decryptedPassword == password) { IsAuthenticated = true; } break; case PasswordMode.PlainText: if (dbPassword == password) { IsAuthenticated = true; } break; } } } return(IsAuthenticated); }
/// <summary> /// Compares a hash of the specified plain text value to a given hash /// value. Plain text is hashed with the same salt value as the original /// hash. /// </summary> /// <param name="plainText">Plain text to be verified against the specified hash. The function does not check whether this parameter is null.</param> /// <param name="expected">Password expected hash.</param> /// <param name="mode">Password encryption mode.</param> /// <returns> /// <c>true</c> if computed hash mathes the specified hash the function; otherwise <c>false</c>. /// </returns> public static bool Verify(String plainText, PasswordHash expected, PasswordMode mode) { var hash = Encrypt(plainText, mode, expected.Salt); return(expected.Equals(hash)); }