在c#中加密密码 [英] Encrypting password in c#
本文介绍了在c#中加密密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
先生!
我希望使用Csharp加密winforms中的密码以存储在sqlserver中。
怎么可能!
sir!
I want to encrypt a password in winforms to be stored in sqlserver using Csharp.
how can it be possible!
推荐答案
如果你想看到一种方法:加密SQL Server中的密码字段,注册表信息&查询字符串 [ ^ ]
这是一个更好的方法,我建议阅读:简单安全密码认证解释 [ ^ ]
If you want to see one way to do it: Encrypt Password Field in SQL Server, Registry Information & Query String[^]
A better way to do this and the one I would suggest reading: Secure Password Authentication Explained Simply[^]
不要加密密码,他们很容易受到攻击解密和攻击。反而哈希他们。这样的事情:
Don''t encrypt passwords, they''re vulnerable to decryption and attacks. Hash them instead. Something like this:
using System.Security.Cryptography;
public static string EncodePasswordToBase64(string password)
{ byte[] bytes = Encoding.Unicode.GetBytes(password);
byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
return Convert.ToBase64String(inArray);
}
tusharkaushik -
你可以在现有的东西上添加这样的东西class:
tusharkaushik -
You could add something like this to an existing class:
public static byte[] GetHashKey(string hashKey)
{
// Initialize
UTF8Encoding encoder = new UTF8Encoding();
// Get the salt
string salt = !string.IsNullOrEmpty(Salt) ? Salt : "I am a nice little salt";
byte[] saltBytes = encoder.GetBytes(salt);
// Setup the hasher
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(hashKey, saltBytes);
// Return the key
return rfc.GetBytes(16);
}
public static string Encrypt(byte[] key, string dataToEncrypt)
{
// Initialize
AesManaged encryptor = new AesManaged();
// Set the key
encryptor.Key = key;
encryptor.IV = key;
// create a memory stream
using (MemoryStream encryptionStream = new MemoryStream())
{
// Create the crypto stream
using (CryptoStream encrypt = new CryptoStream(encryptionStream, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
// Encrypt
byte[] utfD1 = UTF8Encoding.UTF8.GetBytes(dataToEncrypt);
encrypt.Write(utfD1, 0, utfD1.Length);
encrypt.FlushFinalBlock();
encrypt.Close();
// Return the encrypted data
return Convert.ToBase64String(encryptionStream.ToArray());
}
}
}
public static string Decrypt(byte[] key, string encryptedString)
{
// Initialize
AesManaged decryptor = new AesManaged();
byte[] encryptedData = Convert.FromBase64String(encryptedString);
// Set the key
decryptor.Key = key;
decryptor.IV = key;
// create a memory stream
using (MemoryStream decryptionStream = new MemoryStream())
{
// Create the crypto stream
using (CryptoStream decrypt = new CryptoStream(decryptionStream, decryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
// Encrypt
decrypt.Write(encryptedData, 0, encryptedData.Length);
decrypt.Flush();
decrypt.Close();
// Return the unencrypted data
byte[] decryptedData = decryptionStream.ToArray();
return UTF8Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length);
}
}
}
这篇关于在c#中加密密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文