總結(jié):注冊的時候經(jīng)過MD5加密存進數(shù)據(jù)庫,在登錄的時候需要先加密輸入的密碼,再進行和數(shù)據(jù)庫里的比對,因為同一字符串加密后是一樣的,并不是無規(guī)則的:實例:
string name = this.TextBox1.Text;
string pwd = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(this.TextBox2.Text, "MD5");
Response.Write(name+"<br>"+pwd);
------------------------------------------------分界線--------------------------------------------------
.NET將原來獨立的API和SDK合并到一個框架中,這對于程序開發(fā)人員非常有利。它將CryptoAPI改編進.NET的System.Security.Cryptography名字空間,使密碼服務(wù)擺脫了SDK平臺
的神秘性,變成了簡單的.NET名字空間的使用。
加密和解密的算法
System.Security.Cryptography名字空間包含了實現(xiàn)安全方案的類,例如加密和解密數(shù)據(jù)、管理密鑰、驗證數(shù)據(jù)的完整性并確保數(shù)據(jù)沒有被篡改等等
加密和解密的算法分為對稱(symmetric)算法和不對稱(asymmetric)算法。對稱算法在加密和解密數(shù)據(jù)時使用相同的密鑰和初始化矢量,通過私鑰對數(shù)據(jù)塊進行加密,只有
與之對應(yīng)發(fā)布的公鑰才能解密。從而確保了發(fā)布消息的正確身份。典型的有DES、 TripleDES和Rijndael算法,它適用于不需要傳遞密鑰的情況,主要用于本地文檔或數(shù)據(jù)的加密。
不對稱算法有兩個不同的密鑰,分別是公共密鑰和私有密鑰,公共密鑰在網(wǎng)絡(luò)中傳遞,用于加密數(shù)據(jù),而私有密鑰用于解密數(shù)據(jù)。不對稱算法主要有RSA、DSA等,主要用于網(wǎng)
絡(luò)數(shù)據(jù)的加密。
--------------------------------------------------------------------------
部分名詞
密鑰 Secret key
對稱加密算法 symmetric cryptography
非對稱加密算法 asymmetric cryptography
數(shù)字簽名 digital signature
證書 certificate
認證授權(quán) certificate
摘要 digest
---------------------------------------------------------------------------
.NET的提供的加密功能類
對稱加密類
System.Security.Cryptography.SymmetricAlgorithm
System.Security.Cryptography.DES
System.Security.Cryptography.RC2
System.Security.Cryptography.Rijndael
System.Security.Cryptography.TripleDES
非對稱加密類
System.Security.Cryptography.AsymmetricAlgorithm
System.Security.Cryptography.DSA
System.Security.Cryptography.RSA
---------------------------------------------------------------------------
具體使用方法
加密和解密本地文檔 使用的是Rijndael對稱算法
對稱算法在數(shù)據(jù)流通過時對它進行加密。因此首先需要建立一個正常的流(例如I/O流)。文章使用FileStream類將文本文件讀入字節(jié)數(shù)組,也使用該類作為輸出機制。
接下來定義相應(yīng)的對象變量。在定義SymmetricAlgorithm抽象類的對象變量時我們可以指定任何一種對稱加密算法提供程序。代碼使用的是Rijndael算法,但是很容易改為DES
或者TripleDES算法。.NET使用強大的隨機密鑰設(shè)置了提供程序的實例,選擇自己的密鑰是比較危險的,接受計算機產(chǎn)生的密鑰是一個更好的選擇,文中的代碼使用的是計算機
產(chǎn)生的密鑰。算法實例提供了一個對象來執(zhí)行實際數(shù)據(jù)傳輸。每種算法都有CreateEncryptor和CreateDecryptor兩個方法,它們返回實現(xiàn)ICryptoTransform接口的對象。
最后,現(xiàn)在使用BinaryReader的ReadBytes方法讀取源文件,它會返回一個字節(jié)數(shù)組。BinaryReader讀取源文件的輸入流,在作為CryptoStream.Write方法的參數(shù)時調(diào)用
ReadBytes方法。指定的CryptoStream實例被告知它應(yīng)該操作的下層流,該對象將執(zhí)行數(shù)據(jù)傳遞,無論流的目的是讀或者寫
string file = args[0];
string tempfile = Path.GetTempFileName();
//打開指定的文件
FileStream fsIn = File.Open(file,FileMode.Open,FileAccess.Read);
FileStream fsOut = File.Open(tempfile, FileMode.Open,FileAccess.Write);
//定義對稱算法對象實例和接口 SymmetricAlgorithm所有的對稱算法類都是從這個基類繼承而來的
SymmetricAlgorithm symm = new RijndaelManaged();
ICryptoTransform transform = symm.CreateEncryptor();
System.Security.Cryptography.CryptoStream cstream = new CryptoStrea(fsOut,transform,System.Security.Cryptography.CryptoStreamMode.Write);
BinaryReader br = new BinaryReader(fsIn);
// 讀取源文件到cryptostream
cstream.Write(br.ReadBytes((int)fsIn.Length),0,(int)fsIn.Length);
cstream.FlushFinalBlock();
cstream.Close();
fsIn.Close();
fsOut.Close();
Console.WriteLine("created encrypted file {0}", tempfile);
Console.WriteLine("will now decrypt and show contents");
// 反向操作--解密剛才加密的臨時文件
afsIn = File.Open(tempfile,FileMode.Open,FileAccess.Read);
transform = symm.CreateDecryptor();
cstream = new CryptoStream(fsIn,transform,CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cstream);
Console.WriteLine("decrypted file text: " + sr.ReadToEnd());
fsIn.Close();
加密網(wǎng)絡(luò)數(shù)據(jù)
如果我有一個只想自己看到的文檔,我不會簡單的通過e-mail發(fā)送給你。我將使用對稱算法加密它;如果有人截取了它,他們也不能閱讀該文檔,因為他們沒有用于加密的唯
一密鑰。但是你也沒有密鑰。我需要使用某種方式將密鑰給你,這樣你才能解密文檔,但是不能冒密鑰和文檔被截取的風險。
非對稱算法就是一種解決方案。這類算法使用的兩個密鑰有如下關(guān)系:使用公共密鑰加密的信息只能被相應(yīng)的私有密鑰解密。因此,我首要求你給我發(fā)送你的公共密鑰。在發(fā)
送給我的途中可能有人會截取它,但是沒有關(guān)系,因為他們只能使用該密鑰給你的信息加密。我使用你的公共密鑰加密文檔并發(fā)送給你。你使用私有密鑰解密該文檔,這是唯一可
以解密的密鑰,并且沒有通過網(wǎng)絡(luò)傳遞。
不對稱算法比對稱算法計算的花費多、速度慢。因此我們不希望在線對話中使用不對稱算法加密所有信息。相反,我們使用對稱算法。下面的例子中我們使用不對稱加密來加
密對稱密鑰。接著就使用對稱算法加密了。實際上安全接口層(SSL)建立服務(wù)器和瀏覽器之間的安全對話使用的就是這種工作方式。
示例是一個TCP程序,分為服務(wù)器端和客戶端。
服務(wù)器端的工作流程是:
從客戶端接收公共密鑰。
使用公共密鑰加密未來使用的對稱密鑰。
將加密了的對稱密鑰發(fā)送給客戶端。
給客戶端發(fā)送使用該對稱密鑰加密的信息。
代碼如下:
namespace com.billdawson.crypto
{
public class CryptoServer
{
private const int RSA_KEY_SIZE_BITS = 1024;
private const int RSA_KEY_SIZE_BYTES = 252;
private const int TDES_KEY_SIZE_BITS = 192;
public static void Main(string[] args)
{
int port;
string msg;
TcpListener listener;
TcpClient client;
SymmetricAlgorithm symm;
RSACryptoServiceProvider rsa;
//獲取端口
try
{
port = Int32.Parse(args[0]);
msg = args[1];
}
catch
{
Console.WriteLine(USAGE);
return;
}
//建立監(jiān)聽
try
{
listener = new TcpListener(port);
listener.Start();
Console.WriteLine("Listening on port {0}...",port);
client = listener.AcceptTcpClient();
Console.WriteLine("connection....");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return;
}
try
{
rsa = new RSACryptoServiceProvider();
rsa.KeySize = RSA_KEY_SIZE_BITS;
// 獲取客戶端公共密鑰
rsa.ImportParameters(getClientPublicKey(client));
symm = new TripleDESCryptoServiceProvider();
symm.KeySize = TDES_KEY_SIZE_BITS;
//使用客戶端的公共密鑰加密對稱密鑰并發(fā)送給客。
encryptAndSendSymmetricKey(client, rsa, symm);
//使用對稱密鑰加密信息并發(fā)送
encryptAndSendSecretMessage(client, symm, msg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
finally
{
try
{
client.Close();
listener.Stop();
}
catch
{
//錯誤
}
Console.WriteLine("Server exiting...");
}
}
private static RSAParameters getClientPublicKey(TcpClient client)
{
// 從字節(jié)流獲取串行化的公共密鑰,通過串并轉(zhuǎn)換寫入類的實例
byte[] buffer = new byte[RSA_KEY_SIZE_BYTES];
NetworkStream ns = client.GetStream();
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
RSAParameters result;
int len = 0;
int totalLen = 0;
while(totalLen (len = ns.Read(buffer,0,buffer.Length))>0)
{
totalLen+=len;
ms.Write(buffer, 0, len);
}
ms.Position=0;
result = (RSAParameters)bf.Deserialize(ms);
ms.Close();
return result;
}
private static void encryptAndSendSymmetricKey(
TcpClient client,
RSACryptoServiceProvider rsa,
SymmetricAlgorithm symm)
{
// 使用客戶端的公共密鑰加密對稱密鑰
byte[] symKeyEncrypted;
byte[] symIVEncrypted;
NetworkStream ns = client.GetStream();
symKeyEncrypted = rsa.Encrypt(symm.Key, false);
symIVEncrypted = rsa.Encrypt(symm.IV, false);
ns.Write(symKeyEncrypted, 0, symKeyEncrypted.Length);
ns.Write(symIVEncrypted, 0, symIVEncrypted.Length);
}
private static void encryptAndSendSecretMessage(TcpClient client,
SymmetricAlgorithm symm,
string secretMsg)
{
// 使用對稱密鑰和初始化矢量加密信息并發(fā)送給客戶端
byte[] msgAsBytes;
NetworkStream ns = client.GetStream();
ICryptoTransform transform =
symm.CreateEncryptor(symm.Key,symm.IV);
CryptoStream cstream =new CryptoStream(ns, transform, CryptoStreamMode.Write);
msgAsBytes = Encoding.ASCII.GetBytes(secretMsg);
cstream.Write(msgAsBytes, 0, msgAsBytes.Length);
cstream.FlushFinalBlock();
}
}
客戶端的工作流程是:
建立和發(fā)送公共密鑰給服務(wù)器。
從服務(wù)器接收被加密的對稱密鑰。
解密該對稱密鑰并將它作為私有的不對稱密鑰。
接收并使用不對稱密鑰解密信息。
代碼如下:
namespace com.billdawson.crypto
{
public class CryptoClient
{
private const int RSA_KEY_SIZE_BITS = 1024;
private const int RSA_KEY_SIZE_BYTES = 252;
private const int TDES_KEY_SIZE_BITS = 192;
private const int TDES_KEY_SIZE_BYTES = 128;
private const int TDES_IV_SIZE_BYTES = 128;
public static void Main(string[] args)
{
int port;
string host;
TcpClient client;
SymmetricAlgorithm symm;
RSACryptoServiceProvider rsa;
if (args.Length!=2)
{
Console.WriteLine(USAGE);
return;
}
try
{
host = args[0];
port = Int32.Parse(args[1]);
}
catch
{
Console.WriteLine(USAGE);
return;
}
try //連接
{
client = new TcpClient();
client.Connect(host,port);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.Write(e.StackTrace);
return;
}
try
{
Console.WriteLine("Connected. Sending public key.");
rsa = new RSACryptoServiceProvider();
rsa.KeySize = RSA_KEY_SIZE_BITS;
sendPublicKey(rsa.ExportParameters(false),client);
symm = new TripleDESCryptoServiceProvider();
symm.KeySize = TDES_KEY_SIZE_BITS;
MemoryStream ms = getRestOfMessage(client);
extractSymmetricKeyInfo(rsa, symm, ms);
showSecretMessage(symm, ms);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.Write(e.StackTrace);
}
finally
{
try
{
client.Close();
}
catch { //錯誤
}
}
}
private static void sendPublicKey(
RSAParameters key,
TcpClient client)
{
NetworkStream ns = client.GetStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ns,key);
}
private static MemoryStream getRestOfMessage(TcpClient client)
{
//獲取加密的對稱密鑰、初始化矢量、秘密信息。對稱密鑰用公共RSA密鑰
//加密,秘密信息用對稱密鑰加密
MemoryStream ms = new MemoryStream();
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[1024];
int len=0;
// 將NetStream 的數(shù)據(jù)寫入內(nèi)存流
while((len = ns.Read(buffer, 0, buffer.Length))>0)
{
ms.Write(buffer, 0, len);
}
ms.Position = 0;
return ms;
}
private static void extractSymmetricKeyInfo(
RSACryptoServiceProvider rsa,
SymmetricAlgorithm symm,
MemoryStream msOrig)
{
MemoryStream ms = new MemoryStream();
// 獲取TDES密鑰--它被公共RSA密鑰加密,使用私有密鑰解密
byte[] buffer = new byte[TDES_KEY_SIZE_BYTES];
msOrig.Read(buffer,0,buffer.Length);
symm.Key = rsa.Decrypt(buffer,false);
// 獲取TDES初始化矢量
buffer = new byte[TDES_IV_SIZE_BYTES];
msOrig.Read(buffer, 0, buffer.Length);
symm.IV = rsa.Decrypt(buffer,false);
}
private static void showSecretMessage(
SymmetricAlgorithm symm,
MemoryStream msOrig)
{
//內(nèi)存流中的所有數(shù)據(jù)都被加密了
byte[] buffer = new byte[1024];
int len = msOrig.Read(buffer,0,buffer.Length);
MemoryStream ms = new MemoryStream();
ICryptoTransform transform =symm.CreateDecryptor(symm.Key,symm.IV);
CryptoStream cstream =new CryptoStream(ms, transform,
CryptoStreamMode.Write);
cstream.Write(buffer, 0, len);
cstream.FlushFinalBlock();
// 內(nèi)存流現(xiàn)在是解密信息,是字節(jié)的形式,將它轉(zhuǎn)換為字符串
ms.Position = 0;
len = ms.Read(buffer,0,(int) ms.Length);
ms.Close();
string msg = Encoding.ASCII.GetString(buffer,0,len);
Console.WriteLine("The host sent me this secret message:");
Console.WriteLine(msg);
}
}
}
結(jié)論
使用對稱算法加密本地數(shù)據(jù)時比較適合。在保持代碼通用時我們可以選擇多種算法,當數(shù)據(jù)通過特定的CryptoStream時算法使用轉(zhuǎn)換對象加密該數(shù)據(jù)。需要將數(shù)據(jù)通過網(wǎng)絡(luò)發(fā)
送時,首先使用接收的公共不對稱密鑰加密對稱密鑰。
本文只涉及到System.Security.Cryptography名字空間的一部分服務(wù)。盡管文章保證只有某個私有密鑰可以解密相應(yīng)公共密鑰加密的信息,但是它沒有保證是誰發(fā)送的公共密
鑰,發(fā)送者也可能是假的。需要使用處理數(shù)字證書的類來對付該風險。
------------------------------------------------------------------------
DES對稱加密算法
//名稱空間
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
//方法
//加密方法
public string Encrypt(string pToEncrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//把字符串放到byte數(shù)組中
//原來使用的UTF8編碼,我改成Unicode編碼了,不行
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
//byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);
//建立加密對象的密鑰和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得輸入密碼必須輸入英文文本
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);
//Write the byte array into the crypto stream
//(It will end up in the memory stream)
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
//Get the data back from the memory stream, and into a string
StringBuilder ret = new StringBuilder();
foreach(byte b in ms.ToArray())
{
//Format as hex
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
//解密方法
public string Decrypt(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//Put the input string into the byte array
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for(int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
//建立加密對象的密鑰和偏移量,此值重要,不能修改
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(),CryptoStreamMode.Write);
//Flush the data through the crypto stream into the memory stream
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
//Get the decrypted data back from the memory stream
//建立StringBuild對象,CreateDecrypt使用的是流對象,必須把解密后的文本變成流對象
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
2.2 范例
使用非對稱算法加密消息的四個主要步驟
1. 獲取發(fā)送者的私鑰和接收者的公鑰。
2. 借助隨機密鑰(random key)和初始化向量,用對稱算法加密消息。
3. 用接收者的公鑰為2步驟中的密鑰和初始化向量加密。
4. 用發(fā)送者的私鑰對消息進行數(shù)字簽名處理。
對應(yīng)的解密的四個步驟
1. 獲取發(fā)送者的公鑰和接收者的私鑰。
2. 驗證數(shù)字簽名。
3. 解密密鑰和初始化向量。
4. 使用解密后的密鑰和初始化向量解密消息。
代碼分析:
1. 獲取密鑰
...{
X509CertificateStore x509Store = null;
if (location == "CurrentUser")
...{
x509Store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
}
else
...{
x509Store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);
}
bool open = x509Store.OpenRead();
X509Certificate sender_cert = null;
X509Certificate receiver_cert = null;
if (!open)
...{
throw new Exception("unable to open the certificate store");
}
sender_cert = x509Store.FindCertificateBySubjectName("CN=XinChen, E=none@none.com")[0 ];
receiver_cert = x509Store.FindCertificateBySubjectName("CN=Sherry, E=none@none.com")[0 ];
RSAParameters sender_privateKey = sender_cert.Key.ExportParameters(true);
RSAParameters receiver_publicKey = receiver_cert.PublicKey.ExportParameters(false);
}
2. 對稱算法加密 (不指定初始密鑰和初始向量,則由系統(tǒng)自動生成)
...{
SymmetricAlgorithm symmProvider = SymmetricAlgorithm.Create("TripleDES");
encryptor = symmProvider.CreateEncryptor();
CryptoStream encStream = new CryptoStream(data, encryptor, CryptoStreamMode.Read);
MemoryStream encrypted = new MemoryStream();
byte[] buffer = new byte[1024];
int count = 0;
while ((count = encStream.Read(buffer,0,1024)) > 0)
...{
encrypted.Write(buffer,0,count);
}
}
3. 用接收者的公鑰為2步驟中的密鑰和初始化向量加密
...{
byte[] key;
byte[] iv;
RSACryptoServiceProvider asymmetricProvider = new RSACryptoServiceProvider();
asymmetricProvider.ImportParameters(receiver_publicKey);
key = asymmetricProvider.Encrypt(symmProvider.Key,false);
iv = asymmetricProvider.Encrypt(symmProvider.IV,false);
}
4. 創(chuàng)建數(shù)字簽名
使用密鑰為消息散列進行加密
...{
byte[] signature;
asymmetricProvider.ImportParameters(sender_privateKey);
signature = asymmetricProvider.SignData(encrypted.ToArray(), new SHA1CryptoServiceProvider());
}
上面四個步驟的最后輸出為encrypted、key、iv和signature
解密的代碼演示:
1. 獲取密鑰
...
2. 驗證數(shù)字簽名
...{
asymmetricProvider.ImportParameters(sender_publicKey);
bool verify = asymmetricProvider.VerifyData(encrypted, new SHA1CryptoServiceProvider(), signature)
}
3. 解密密鑰和初始化向量
...{
asymmetricProvider.ImportParameters(receiver_privateKey);
byte[] decryptedKey = asymmetricProvider.Decrypt(key, false);
byte[] decryptediv = asymmetricProvider.Decrypt(iv, false);
}
4. 使用解密后的密鑰和初始化向量解密消息。
...{
SymmetricAlgorithm symmProvider = SymmetricAlgorithm.Create("TripleDES");
ICryptoTransform decryptor = symmProvider.CreateDecryptor(decryptedKey, decryptediv);
CryptoStream decStream = new CryptoStream(encrypted, decryptor, CryptoStreamMode.Read);
}
3.Hash散列舉例
...{
System.Security.Cryptography.HashAlgorithm
System.Security.Cryptography.KeyedHashAlgorithm
System.Security.Cryptography.MD5
System.Security.Cryptography.SHA1
System.Security.Cryptography.SHA256
System.Security.Cryptography.SHA384
System.Security.Cryptography.SHA512
}
public static string Encrypt(string password)
...{
password = password.ToLower();
Byte[] clearBytes = new UnicodeEncoding().GetBytes(password);
Byte[] hashedBytes = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
return BitConverter.ToString(hashedBytes);
}