/// <summary> /// Compute a cryptographic hash of 'value' and 'hashKeyHash' together. /// Used to map values in the Sanitizer. /// </summary> /// <param name="value">Source value to hash</param> /// <param name="hashKeyHash">HashKey for this hash</param> /// <returns>uint of hash result</returns> public static uint Hash(String8 value, uint hashKeyHash) { if (hasher == null) { hasher = SHA256Managed.Create(); } if (buffer == null || buffer.Length < value.Length + 4) { buffer = new byte[value.Length + 4]; } buffer[0] = (byte)(hashKeyHash & 0xFF); buffer[1] = (byte)((hashKeyHash >> 8) & 0xFF); buffer[2] = (byte)((hashKeyHash >> 16) & 0xFF); buffer[3] = (byte)((hashKeyHash >> 24) & 0xFF); value.WriteTo(buffer, 4); byte[] hash = hasher.ComputeHash(buffer, 0, value.Length + 4); uint result = (uint)((hash[0] << 24) + (hash[1] << 16) + (hash[2] << 8) + hash[3]); return(result); }
/// <summary> /// Implementation of slot. /// </summary> /// <param name="signaler">Signaler invoking slot.</param> /// <param name="input">Arguments to slot.</param> public void Signal(ISignaler signaler, Node input) { var contentRaw = input.GetEx <object>(); var data = contentRaw is string strContent?Encoding.UTF8.GetBytes(strContent) : contentRaw as byte[]; var algorithm = input.Children.FirstOrDefault(x => x.Name == "algorithm")?.GetEx <string>() ?? "SHA256"; var format = input.Children.FirstOrDefault(x => x.Name == "format")?.GetEx <string>() ?? "text"; switch (algorithm) { case "SHA256": using (var algo = SHA256Managed.Create()) { input.Value = GenerateHash(algo, data, format); } break; case "SHA384": using (var algo = SHA384Managed.Create()) { input.Value = GenerateHash(algo, data, format); } break; case "SHA512": using (var algo = SHA512Managed.Create()) { input.Value = GenerateHash(algo, data, format); } break; default: throw new ArgumentException($"'{algorithm}' is an unknown hashing algorithm."); } // House cleaning. input.Clear(); }
/// <summary> /// A method for generating encrypted ChallengeInfo to be saved. For security, this method should /// be called every time you get a successful challenge-response pair from the Yubikey. Failure to /// do so will permit password re-use attacks. /// </summary> /// <param name="secret">The un-encrypted secret</param> /// <returns>A fully populated ChallengeInfo object ready to be saved</returns> public ChallengeInfo Encrypt(byte[] secret) { //generate a random challenge for use next time byte[] challenge = GenerateChallenge(); //generate the expected HMAC-SHA1 response for the challenge based on the secret byte[] resp = GenerateResponse(challenge, secret); //use the response to encrypt the secret SHA256 sha = SHA256Managed.Create(); byte[] key = sha.ComputeHash(resp); // get a 256 bit key from the 160 bit hmac response byte[] secretHash = sha.ComputeHash(secret); StandardAesEngine aes = new StandardAesEngine(); const uint aesIVLenBytes = 16; byte[] IV = CryptoRandom.Instance.GetRandomBytes(aesIVLenBytes); byte[] encrypted; using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = (CryptoStream)aes.EncryptStream(msEncrypt, key, IV)) { csEncrypt.Write(secret, 0, secret.Length); csEncrypt.Close(); } encrypted = msEncrypt.ToArray(); msEncrypt.Close(); } ChallengeInfo inf = new ChallengeInfo(encrypted, IV, challenge, secretHash, LT64); sha.Clear(); return(inf); }
public static Texture FromFile(string path, GraphicsDevice graphicsDevice, ResourceFactory resourceFactory) { var executablePath = System.Reflection.Assembly.GetEntryAssembly().Location; if (String.IsNullOrEmpty(executablePath)) { executablePath = AppDomain.CurrentDomain.BaseDirectory; } if (String.IsNullOrEmpty(executablePath)) { throw new Exception("Executable path cannot be null or empty"); } var executableDirectory = Path.GetDirectoryName(executablePath); path = Path.Combine(executableDirectory, path); Console.WriteLine($"Loading texture at {path}"); if (File.Exists(path)) { var texture = new ImageSharpTexture(path); var deviceTexture = texture.CreateDeviceTexture(graphicsDevice, resourceFactory); var textureView = resourceFactory.CreateTextureView(deviceTexture); var hash = 0l; using (var sha = SHA256Managed.Create()) { using (var stream = File.OpenRead(path)) { var rawHash = sha.ComputeHash(stream); hash = BitConverter.ToInt64(rawHash, 0); } } return(new Texture(texture, deviceTexture, textureView, hash)); } else { throw new Exception($"Texture {path} you are trying to load cannot be found"); } }
public ActionResult Save(SignUpViewModel user) { user.Users.userType = "Admin"; if (!ModelState.IsValid) { //var errors = ModelState.Values.All(modelState => modelState.Errors.Count == 0); return(View("Signup")); } var data = new User() { userType = "User Not Added!" }; if (user.Users.password == user.repassword) { SHA256 mySHA256 = SHA256Managed.Create(); byte[] hashvalue; if (user.Users.id == 0 || user.Users.id == null) //Adding User { byte [] byteArray = Encoding.ASCII.GetBytes((string)user.Users.password); hashvalue = mySHA256.ComputeHash(byteArray); user.Users.password = Encoding.ASCII.GetString(hashvalue); _context.Users.Add(user.Users); } else //Editing User { var userInDb = _context.Users.Single(c => c.id == user.Users.id); userInDb.username = user.Users.username; userInDb.password = user.Users.password; userInDb.userType = "Admin"; } _context.SaveChanges(); data.userType = "User has been Added!"; } return(RedirectToAction("Index", "Home", data)); }
public static String computeHash(String message, String algo) { byte[] sourceBytes = Encoding.Default.GetBytes(message); byte[] hashBytes = null; switch (algo.Trim().ToUpper()) { case "MD5": hashBytes = MD5CryptoServiceProvider.Create().ComputeHash(sourceBytes); break; case "SHA1": hashBytes = SHA1Managed.Create().ComputeHash(sourceBytes); break; case "SHA256": hashBytes = SHA256Managed.Create().ComputeHash(sourceBytes); break; case "SHA384": hashBytes = SHA384Managed.Create().ComputeHash(sourceBytes); break; case "SHA512": hashBytes = SHA512Managed.Create().ComputeHash(sourceBytes); break; default: break; } StringBuilder sb = new StringBuilder(); for (int i = 0; hashBytes != null & i < hashBytes.Length; i++) { sb.AppendFormat("{0:x2}", hashBytes[i]); } return(sb.ToString()); }
/// <summary> /// 根据指定的 hash 算法,加密字符串(比如密码) /// </summary> /// <param name="pwd">需要 hash 的字符串</param> /// <param name="ht">hash 算法类型</param> /// <returns></returns> public virtual String Get(String pwd, HashType ht) { HashAlgorithm algorithm; if (ht == HashType.MD5 || ht == HashType.MD5_16) { algorithm = MD5.Create(); } else if (ht == HashType.SHA1) { algorithm = SHA1CryptoServiceProvider.Create(); } else if (ht == HashType.SHA256) { algorithm = SHA256Managed.Create(); } else if (ht == HashType.SHA384) { algorithm = SHA384Managed.Create(); } else if (ht == HashType.SHA512) { algorithm = SHA512Managed.Create(); } else { algorithm = MD5.Create(); } byte[] buffer = Encoding.UTF8.GetBytes(pwd); String result = BitConverter.ToString(algorithm.ComputeHash(buffer)).Replace("-", ""); if (ht == HashType.MD5_16) { return(result.Substring(8, 16).ToLower()); } return(result); }
/// <summary> /// Salva il nuovo contenuto, calcola l'hash del file memorizzato e lo confronta con quello fornito /// dall'utente (se fornito). /// </summary> public void completaScrittura() { //Controllo se è la prima scrittura: allora lancio eccezione if (!cambioContenutoIniziato) { throw new DatabaseException("Non è stata chiamata la funzione cambiaContenuto();", DatabaseErrorCode.SnapshotInLettura); } SHA256 sha_obj = SHA256Managed.Create(); byte[] hash_val; this.__scrittura_contenuto.Position = 0; hash_val = sha_obj.ComputeHash(this.__scrittura_contenuto); this.__scrittura_contenuto.Close(); string tmp_nome = base_path + Path.DirectorySeparatorChar + this.__nome_locale + ".tmp"; //Elimino il vecchio contenuto File.Delete(tmp_nome); //Controllo hash StringBuilder hex = new StringBuilder(hash_val.Length * 2); foreach (byte b in hash_val) { hex.AppendFormat("{0:x2}", b); } string sha_reale = hex.ToString(); if (this.__sha_contenuto != "") { if (this.__sha_contenuto != sha_reale) { throw new DatabaseException("L'hash fornito è diverso dall'hash calcolato.", DatabaseErrorCode.HashInconsistente); } } this.__sha_contenuto = sha_reale; CaricaDatiNelDB(); this.__lettura_contenuto = new FileStream(base_path + Path.DirectorySeparatorChar + this.__nome_locale, FileMode.Open, FileAccess.Read); this.cambioContenutoIniziato = false; }
public static void DownloadOssObject2File(OssObject ossObject, string filePath, out string md5, out string sha256) { using (SHA256 sha256Hash = SHA256Managed.Create()) using (MD5 md5Hash = MD5.Create()) using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) using (Stream content = ossObject.Content) { byte[] buf = new byte[1024]; int length = 0; while ((length = content.Read(buf, 0, 1024)) != 0) { md5Hash.TransformBlock(buf, 0, length, null, 0); sha256Hash.TransformBlock(buf, 0, length, null, 0); fileStream.Write(buf, 0, length); } md5Hash.TransformFinalBlock(new byte[0], 0, 0); sha256Hash.TransformFinalBlock(new byte[0], 0, 0); md5 = Convert.ToBase64String(md5Hash.Hash); sha256 = BitConverter.ToString(sha256Hash.Hash).Replace("-", string.Empty).ToLower(); } }
public async Task <Administrator> GetAdminAsync(string username, string password) { var administrator = await this.context.Administrators.SingleOrDefaultAsync(u => u.Username == username); SHA256 sha256 = SHA256Managed.Create(); byte[] bytes = Encoding.UTF8.GetBytes(password); byte[] hash = sha256.ComputeHash(bytes); StringBuilder result = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { result.Append(hash[i].ToString("X2")); } if (administrator != null && administrator.Password == result.ToString()) { return(administrator); } throw new ArgumentException(); }
private string GetHash() { // Initialize a SHA256 hash object. SHA256 mySHA256 = SHA256Managed.Create(); FileInfo fInfo = new FileInfo(this.InitialPath); byte[] hashValue; // Compute and print the hash values for the file // Create a fileStream for the file. FileStream fileStream = fInfo.Open(FileMode.Open); // Be sure it's positioned to the beginning of the stream. fileStream.Position = 0; // Compute the hash of the fileStream. hashValue = mySHA256.ComputeHash(fileStream); // Close the file. fileStream.Close(); return(GetByteArray(hashValue)); }
/// <summary> /// Creates the user hash. The random salt is added to the password, the SHA256 procedure is to apply a logic XOR /// to the password and the salt. /// The HMAC procedure use hash function in combination with a SharedHMACPassword. The ouput is computed n times to /// make the HMAC function very slow /// </summary> /// <param name="salt">The random salt.</param> /// <param name="password">The password.</param> /// <returns></returns> public static UserKeyPair CreateUserHash(string password) { //Generate salt string salt = GenerateRandomSalt(new RNGCryptoServiceProvider(), 32); string shaInput = password + salt; SHA256 mySHA256 = SHA256Managed.Create(); byte[] shaFirstRound = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(shaInput)); HMACSHA256 myHMAC = new HMACSHA256(SharedHMACPassword); //Compute HMAC n times starting with shaFirstRound using a password for HMAC for (int i = 0; i < iteration; i++) { shaFirstRound = myHMAC.ComputeHash(shaFirstRound); } string pass = Convert.ToBase64String(shaFirstRound); return(new UserKeyPair(salt, pass)); }
/// <summary> /// Event that fires when the sha1 encrypt button is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> //private void btnSHA1Encrypt_Click(object sender, RoutedEventArgs e) //{ // byte[] byteHash = null; // byte[] byteValue = null; // byteValue = System.Text.Encoding.ASCII.GetBytes(this.txtSHA1PasswordToHash.Text); // // Compute SHA1 hashed bytes // SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); // byteHash = sha1.ComputeHash(byteValue); // sha1.Clear(); // string encryptedPassword = Convert.ToBase64String(byteHash); // this.txtSHA1EncryptedText.Text = encryptedPassword; //} private void btnSHA1Encrypt_Click(object sender, RoutedEventArgs e) { var byteValue = Encoding.ASCII.GetBytes(this.txtSHA1PasswordToHash.Text); // Compute SHA1 hashed bytes var sha256 = SHA256Managed.Create(); var byteHash = sha256.ComputeHash(byteValue); sha256.Clear(); string encryptedPassword = Convert.ToBase64String(byteHash); this.txtSHA1EncryptedText.Text = encryptedPassword; //string strToHash = (STR_CSI_TVR + token + secureKey.ToString()).ToUpper(Thread.CurrentThread.CurrentCulture); //var hex = new StringBuilder(hash.Length * 2); //foreach (var b in hash) //{ // hex.AppendFormat("{0:x2}", b); //} }
/// <summary> /// Converts a String to a Hash /// </summary> /// <param name="str">The string to convert</param> /// <param name="hashtype">The HashType (SHA256, SHA512)</param> /// <returns>A string of the hash</returns> internal static string GetHash(string str, HashType hashtype = HashType.SHA256) { byte[] hash; if (hashtype == HashType.SHA256) { SHA256 sha = SHA256Managed.Create(); byte[] bytes = Encoding.UTF8.GetBytes(str); hash = sha.ComputeHash(bytes); } else { SHA512 sha = SHA512Managed.Create(); byte[] bytes = Encoding.UTF8.GetBytes(str); hash = sha.ComputeHash(bytes); } StringBuilder result = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { result.Append(hash[i].ToString("X2")); } return(result.ToString()); }
/// <summary> /// Retorna um texto encriptografado /// </summary> /// <param name="Texto"> Texto que irá ser encriptografado</param> /// <returns></returns> Retorna o texto encriptografado public static string GerarHash(string Texto) { //Declaro uma variavel do tipo StrignBuider StringBuilder result = new StringBuilder(); // Declaro uma variavel do tipo SHA256 para encriptografia SHA256 sha256 = SHA256Managed.Create(); // Converto o texto recebido como paramentro em bytes byte[] bytes = Encoding.UTF8.GetBytes(Texto); // Gera um Hash de acordo com a variavel bytes byte[] hash = sha256.ComputeHash(bytes); // Percorre o hash e vai concatenando o texto for (int i = 0; i < hash.Length; i++) { result.Append(hash[i].ToString("X")); } // Retorna o texto encriptografado return(result.ToString()); }
/// <summary> /// 计算文件的 SHA256 值 /// </summary> /// <param name="fileStream">文件流</param> /// <returns>System.String.</returns> public static string SHA256File(FileStream fileStream) { SHA256 mySHA256 = SHA256Managed.Create(); byte[] hashValue; // Create a fileStream for the file. //FileStream fileStream = fInfo.Open(FileMode.Open); // Be sure it's positioned to the beginning of the stream. fileStream.Position = 0; // Compute the hash of the fileStream. hashValue = mySHA256.ComputeHash(fileStream); // Close the file. fileStream.Close(); // Write the hash value to the Console. StringBuilder sb = new StringBuilder(); int i; for (i = 0; i < hashValue.Length; i++) { sb.Append(string.Format("{0:X2}", hashValue[i])); } return(sb.ToString()); }
private AuthDetails genAuthDetails(string scopeId, long userId) { // Fill the simple fields AuthDetails authDetails = new AuthDetails(); authDetails.expires = // 5 minutes (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds + 300; authDetails.userId = userId; authDetails.salt = randomString(100); // Calculate and fill the signature string signatureBody = "" + APPLICATION_ID + scopeId + userId + authDetails.salt + authDetails.expires + APP_SHARED_SECRET; ASCIIEncoding enc = new ASCIIEncoding(); byte[] sigBodyBinary = enc.GetBytes(signatureBody); SHA256 hasher = SHA256Managed.Create(); byte[] sigBinary = hasher.ComputeHash(sigBodyBinary); authDetails.signature = BitConverter.ToString(sigBinary).Replace("-", ""); return(authDetails); }
public async Task <User> FindUserAsync(string username, string password) { var user = await this.context.Users.SingleOrDefaultAsync(u => u.Username == username); SHA256 sha256 = SHA256Managed.Create(); byte[] bytes = Encoding.UTF8.GetBytes(password); byte[] hash = sha256.ComputeHash(bytes); StringBuilder result = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { result.Append(hash[i].ToString("X2")); } if (user != null && user.Password == result.ToString()) { return(user); } return(null); }
public string CritpoHash(string text, HashType hashType) { byte[] sourceBytes = Encoding.Default.GetBytes(text); byte[] hashBytes = null; switch (hashType) { case HashType.MD5: hashBytes = MD5CryptoServiceProvider.Create().ComputeHash(sourceBytes); break; case HashType.Sha1: hashBytes = SHA1Managed.Create().ComputeHash(sourceBytes); break; case HashType.Sha256: hashBytes = SHA256Managed.Create().ComputeHash(sourceBytes); break; case HashType.Sha384: hashBytes = SHA384Managed.Create().ComputeHash(sourceBytes); break; case HashType.Sha512: hashBytes = SHA512Managed.Create().ComputeHash(sourceBytes); break; default: break; } var sb = new StringBuilder(); for (int i = 0; hashBytes.Length > i; i++) { sb.Append(hashBytes[i]); } return(sb.ToString()); }
public static string DecryptString(string text, string password, string salt) { if (text == null) { throw new ArgumentException("text"); } if (password == null) { throw new ArgumentException("password"); } if (salt == null) { throw new ArgumentException("salt"); } byte[] baPwd = Encoding.UTF8.GetBytes(password); // Hash the password with SHA256 byte[] baPwdHash = SHA256Managed.Create().ComputeHash(baPwd); byte[] baText = Convert.FromBase64String(text); byte[] baDecrypted = Decrypt(baText, baPwdHash); // Remove salt int saltLength = salt.Length; byte[] baResult = new byte[baDecrypted.Length - saltLength]; for (int i = 0; i < baResult.Length; i++) { baResult[i] = baDecrypted[i + saltLength]; } string result = Encoding.UTF8.GetString(baResult); return(result); }
void CreateAndAssignChecksums() { logger.Debug("Generating checksums"); using (var hasher = SHA256Managed.Create()) { bool hasErrors = false; foreach (var managedFile in record.Files.Where(x => x.Status != Data.FileStatus.Removed)) { try { string path = Path.Combine(ProcessingDirectory, record.Id.ToString(), managedFile.Name); using (var fileStream = new FileStream(path, FileMode.Open)) { byte[] hashValue = hasher.ComputeHash(fileStream); managedFile.Checksum = BitConverter.ToString(hashValue).Replace("-", String.Empty); managedFile.ChecksumMethod = "SHA256"; managedFile.ChecksumDate = DateTime.UtcNow; logger.Debug("Generated checksum: " + managedFile.Checksum); } } catch (Exception ex) { hasErrors = true; logger.Error("Problem while generating checksum", ex); this.messages.Add(ex.Message); } } if (!hasErrors) { LogEvent(EventTypes.GenerateChecksums, "Generated Checksums "); } } }
public ActionResult Index([Bind(Include = "currentPassword,newPassword,confirmedNewPassword")] PasswordChanger changePassword) { if (ModelState.IsValid) { try { Account accnt = db.Accounts.Find((Session["account"] as Account).personId); byte[] hash = SHA256Managed.Create().ComputeHash(Encoding.UTF8.GetBytes(changePassword.currentPassword)); StringBuilder currentPassword = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { currentPassword.Append(hash[i].ToString("X2")); } if (accnt.password == currentPassword.ToString()) { hash = SHA256Managed.Create().ComputeHash(Encoding.UTF8.GetBytes(changePassword.newPassword)); StringBuilder newPassword = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { newPassword.Append(hash[i].ToString("X2")); } accnt.password = newPassword.ToString(); db.Entry(accnt).State = EntityState.Modified; db.SaveChanges(); Session.Remove("account"); TempData["infoMsg"] = "Password successfully changed."; return(RedirectToAction("", "Login")); } } catch (Exception) { TempData["errMsg"] = "An unexpected error has occurred. Please try again later."; } } ModelState.AddModelError("currentPassword", "Current password is not valid."); return(View(changePassword)); }
/// <summary> /// Gets a valid viewkey for a given page /// </summary> /// <param name="id">Page id</param> /// <returns>Viewkey</returns> public string GetViewKey(int id) { var page = GetById(id); if (page == null) { return(null); } var seed = page.Id + page.CreatedBy + page.CreatedOn.ToString("O") + ApplicationSettings.ViewKeysSecret; if (!viewKeysCache.ContainsKey(seed)) { var sb = new StringBuilder(); using (var hash = SHA256Managed.Create()) foreach (var b in hash.ComputeHash(Encoding.UTF8.GetBytes(seed))) { sb.Append(b.ToString("x2")); } viewKeysCache[seed] = sb.ToString(); } return(viewKeysCache[seed]); }
public static string GetHash(Algorithms algo, string fileName) { FileInfo fi = new FileInfo(fileName); FileStream fs = fi.Open(FileMode.Open); fs.Position = 0; byte[] hashValue = new byte[] { }; switch (algo) { case Algorithms.SHA512: SHA512 mySHA512 = SHA512Managed.Create(); hashValue = mySHA512.ComputeHash(fs); break; case Algorithms.SHA256: SHA256 mySHA256 = SHA256Managed.Create(); hashValue = mySHA256.ComputeHash(fs); break; case Algorithms.SHA1: SHA1 mySHA1 = SHA1Managed.Create(); hashValue = mySHA1.ComputeHash(fs); break; case Algorithms.MD5: MD5 myMD5 = MD5.Create(); hashValue = myMD5.ComputeHash(fs); break; } string result = BitConverter.ToString(hashValue).Replace("-", String.Empty); fs.Close(); return(result); }
private void calculatePow(string blockData, int zeroCount) { int nonce = 0; byte[] goodHash = null; SHA256 sha256 = SHA256Managed.Create(); do { nonce++; var bytes = Encoding.UTF8.GetBytes(blockData + nonce.ToString()); goodHash = sha256.ComputeHash(bytes); for (int i = 0; i < zeroCount; i++) { if (goodHash[i] != 0) { goodHash = null; break; } } } while(goodHash == null); StringBuilder hashString = new StringBuilder(); foreach (byte x in goodHash) { hashString.Append(String.Format("{0:x2}", x)); } Pow = hashString.ToString(); LastNonce = nonce; }
private void btThucHienKy_RSA_Click(object sender, RoutedEventArgs e) { // thực hiên ký if (F_rsa_d_dau != 1) { MessageBox.Show("Bạn chưa tạo chữ ký", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error); } else { if (F_rsa_d_dau == 1) { byte mk = byte.Parse("111"); if (!File.Exists(txtDuongDanFileKy_RSA.Text)) { // MessageBox.Show("Phải nhập đủ 2 số ", "Thông Báo ", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Bạn chưa chọn file thực hiện ký!", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error); } if (File.Exists(txtDuongDanFileKy_RSA.Text)) { FileStream fsFileDauVao = new FileStream(txtDuongDanFileKy_RSA.Text, FileMode.Open); SHA256 mySHA256 = SHA256Managed.Create(); byte[] FileVBKy_temp1 = mySHA256.ComputeHash(fsFileDauVao); string FileVBKy = Convert.ToBase64String(FileVBKy_temp1); string VBKemChuKy = F_MaHoa_RSA(FileVBKy); txtTepKyDuocGuiDi_RSA.Text = VBKemChuKy; fsFileDauVao.Close(); fsFileDauVao.Dispose(); F_rsa_d_dau = 2; MessageBox.Show("Thực hiện ký thành công !", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Information); btThucHienKy_RSA.IsEnabled = false; } } } }
public static bool ValidateCertificate(byte[] issuingCertificate, byte[] certificateToValidate) { RSAParameters rsaParameters = CertificateHelper.GetRSAParameters(issuingCertificate); byte[] certificateSignature = ByteReader.ReadBytes(certificateToValidate, certificateToValidate.Length - 256, 256); byte[] decodedSignature = RSAHelper.DecryptSignature(certificateSignature, rsaParameters); byte[] tbsCertificate = CertificateHelper.ExtractTbsCertificate(certificateToValidate); if (StartsWith(decodedSignature, SHA_256_PKCS_ID)) { byte[] expectedHash = ByteReader.ReadBytes(decodedSignature, SHA_256_PKCS_ID.Length, 32); byte[] hash = SHA256Managed.Create().ComputeHash(tbsCertificate); return(ByteUtils.AreByteArraysEqual(hash, expectedHash)); } else if (StartsWith(decodedSignature, SHA_160_PKCS_ID)) { byte[] expectedHash = ByteReader.ReadBytes(decodedSignature, SHA_160_PKCS_ID.Length, 20); byte[] hash = SHA1Managed.Create().ComputeHash(tbsCertificate); return(ByteUtils.AreByteArraysEqual(hash, expectedHash)); } else { throw new NotImplementedException("Unsupported Signature PKCS ID"); } }
public static string DecryptString(string text, string password) { byte[] baPwd = Encoding.UTF8.GetBytes(password); // Hash the password with SHA256 byte[] baPwdHash = SHA256Managed.Create().ComputeHash(baPwd); byte[] baText = Convert.FromBase64String(text); byte[] baDecrypted = AES_Decrypt(baText, baPwdHash); // Remove salt int saltLength = GetSaltLength(); byte[] baResult = new byte[baDecrypted.Length - saltLength]; for (int i = 0; i < baResult.Length; i++) { baResult[i] = baDecrypted[i + saltLength]; } string result = Encoding.UTF8.GetString(baResult); return(result); }
//Valida que la contraseña corresponda a los credenciales public Boolean validar() { Usuario_TO usuario = new Usuario_TO(); usuario.Id = this.Id; usuario.Nombre = this.Nombre; usuario.Contraseña = this.Contraseña; Usuario_TO usuario_bd = new Usuario_BD().validar(usuario); if (usuario_bd.Id != 0) { SHA256 sha256 = SHA256Managed.Create(); byte[] bytes = Encoding.UTF8.GetBytes(this.Contraseña); byte[] hash = sha256.ComputeHash(bytes); StringBuilder result = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { result.Append(hash[i].ToString("X2")); } if (usuario_bd.Contraseña.Equals(result.ToString())) { return(true); } else { return(false); } } else { return(false); } }
//verifica los datos, encripta la contraseña y nos lleva a la siguiente pantalla para completar el domicilio private void button2_Click(object sender, EventArgs e) { if (this.camposCompletos()) { Empresa.RazonSocial = textBoxRazonSocial.Text; Empresa.Cuit = Int64.Parse(textBoxCUIT.Text); Empresa.FechaDeCreacion = Sesion.getInstance().fecha; if (!string.IsNullOrWhiteSpace(textBoxMail.Text)) { Empresa.Mail = textBoxMail.Text; } if (string.IsNullOrWhiteSpace(empresa.NombreUsuario) || empresa.DebeCambiarContraseña) { empresa.NombreUsuario = textBoxCUIT.Text; StringBuilder Sb = new StringBuilder(); using (SHA256 hash = SHA256Managed.Create()) { Encoding enc = Encoding.UTF8; Byte[] result = hash.ComputeHash(enc.GetBytes(textBoxCUIT.Text.ToString())); foreach (Byte b in result) { Sb.Append(b.ToString("x2")); } } empresa.Contrasenia = Sb.ToString(); empresa.DebeCambiarContraseña = true; } new RegistroDomicilio(this, this.Empresa).Show(); this.Hide(); } }