網(wǎng)絡(luò )數據加密需要解決三個(gè)問(wèn)題:完整:數據不被篡改;
安全:數據不被截獲,或者截獲也無(wú)法得到明文;
可靠:數據從真正的發(fā)送方而來(lái),其他人無(wú)法偽造一個(gè)數據來(lái)欺騙接受方;
下面例子只解決了安全這個(gè)問(wèn)題: 非對稱(chēng)算法使用的兩個(gè)密鑰有如下關(guān)系:使用公共密鑰加密的信息只能被相應的私有密鑰解密。因此,我首要求你給我發(fā)送你的公共密鑰。在發(fā)送給我的途中可能有人會(huì )截取它,但是沒(méi)有關(guān)系,因為他們只能使用該密鑰給你的信息加密。我使用你的公共密鑰加密文檔并發(fā)送給你。你使用私有密鑰解密該文檔,這是唯一可以解密的密鑰,并且沒(méi)有通過(guò)網(wǎng)絡(luò )傳遞。
不對稱(chēng)算法比對稱(chēng)算法計算的花費多、速度慢。因此我們不希望在線(xiàn)對話(huà)中使用不對稱(chēng)算法加密所有信息。相反,我們使用對稱(chēng)算法。下面的例子中我們使用不對稱(chēng)加密來(lái)加密對稱(chēng)密鑰。接著(zhù)就使用對稱(chēng)算法加密了。實(shí)際上安全接口層(SSL)建立服務(wù)器和瀏覽器之間的安全對話(huà)使用的就是這種工作方式。
示例是一個(gè)TCP程序,分為服務(wù)器端和客戶(hù)端。服務(wù)器端的工作流程是:
從客戶(hù)端接收公共密鑰。
使用公共密鑰加密未來(lái)使用的對稱(chēng)密鑰。
將加密了的對稱(chēng)密鑰發(fā)送給客戶(hù)端。
給客戶(hù)端發(fā)送使用該對稱(chēng)密鑰加密的信息。
代碼如下:
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;
}
//建立監聽(tīng)
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;
// 獲取客戶(hù)端公共密鑰
rsa.ImportParameters(getClientPublicKey(client));
symm = new TripleDESCryptoServiceProvider();
symm.KeySize = TDES_KEY_SIZE_BITS;
//使用客戶(hù)端的公共密鑰加密對稱(chēng)密鑰并發(fā)送給客。
encryptAndSendSymmetricKey(client, rsa, symm);
//使用對稱(chēng)密鑰加密信息并發(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)
{
// 從字節流獲取串行化的公共密鑰,通過(guò)串并轉換寫(xiě)入類(lèi)的實(shí)例
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)
{
// 使用客戶(hù)端的公共密鑰加密對稱(chēng)密鑰
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)
{
// 使用對稱(chēng)密鑰和初始化矢量加密信息并發(fā)送給客戶(hù)端
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();
}
}
客戶(hù)端的工作流程是:
建立和發(fā)送公共密鑰給服務(wù)器。
從服務(wù)器接收被加密的對稱(chēng)密鑰。
解密該對稱(chēng)密鑰并將它作為私有的不對稱(chēng)密鑰。
接收并使用不對稱(chēng)密鑰解密信息。
代碼如下:
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)
{
//獲取加密的對稱(chēng)密鑰、初始化矢量、秘密信息。對稱(chēng)密鑰用公共RSA密鑰
//加密,秘密信息用對稱(chēng)密鑰加密
MemoryStream ms = new MemoryStream();
NetworkStream ns = client.GetStream();
byte[] buffer = new byte[1024];
int len=0;
// 將NetStream 的數據寫(xiě)入內存流
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)
{
//內存流中的所有數據都被加密了
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();
// 內存流現在是解密信息,是字節的形式,將它轉換為字符串
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);
}
}
}
---------------------------------------------------------------------