怎樣用Java的加密機(jī)制來保護(hù)你的數(shù)據(jù) |
作者:http://www. 發(fā)文時(shí)間:2005.06.29 |
|
Java開發(fā)工具包(JDK)對(duì)加密和安全性有很好的支持,。其中一個(gè)優(yōu)勢(shì)就是其內(nèi)置的對(duì)Socket通信的支持。因此,,很容易做到在服務(wù)器和客戶之間建立安全的數(shù)據(jù)流,。
Java streams 是一個(gè)強(qiáng)大的編程工具。java.io包提供了很多標(biāo)準(zhǔn)的流類型,并能很容易的建立自己的流類型,。流的一個(gè)有用的特點(diǎn)是和鏈表一樣的簡單處理過程,。表A是一個(gè)用鏈表讀取文本的例子:
ufferedReader br =
new BufferedReader(
new FileReader(“c:\foo.txt”));
String line = null;
while((line =
br.readLine()) != null)
{
System.out.println(line);
} |
這段代碼將 FileReader和 BufferedReader鏈接起來。我們?cè)谟每蛻魴C(jī)/服務(wù)器應(yīng)用程序的時(shí)候也會(huì)用到類似的概念,。
關(guān)鍵字
對(duì)于驗(yàn)證來說,,關(guān)鍵字很重要,表B(KeyGen.java)提供了一個(gè)稱為getSecretKey的標(biāo)準(zhǔn)方法,。通過運(yùn)行KeyGen來產(chǎn)生一個(gè)關(guān)鍵字,。因?yàn)槲覀儾捎猛椒椒ǎ钥蛻魴C(jī)和服務(wù)器必須用相同的關(guān)鍵字,。
isting B?KeyGen.java
/*
* Created by IntelliJ IDEA.
* User: jbirchfield
* Date: Mar 19, 2002
* Time: 9:33:22 AM
*/
import com.sun.crypto.provider.SunJCE;
import javax.crypto.KeyGenerator;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
public class KeyGen
{
public static final String
KEY_FILE = "secret.key";
public static final String
ALGORITHM = "DES";
public static void main(String[] args)
{
Security.addProvider(new SunJCE());
new KeyGen();
}
public KeyGen()
{
KeyGenerator kg = null;
try {
kg = KeyGenerator.
getInstance(ALGORITHM);
Key key = kg.generateKey();
writeKey(KEY_FILE, key);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
}
private void writeKey(String
filename, Object o)
{
try {
FileOutputStream fos =
new FileOutputStream(filename);
ObjectOutputStream oos =
new ObjectOutputStream(fos);
oos.writeObject(o);
oos.flush();
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static Key getSecretKey()
{
Security.addProvider(new SunJCE());
FileInputStream fis = null;
try
{
fis = new FileInputStream(KEY_FILE);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
Key key = null;
try {
ObjectInputStream ois = null;
ois = new ObjectInputStream(fis);
key = null;
key = (Key) ois.readObject();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
System.out.println("key = " + key);
return key;
}
} |
安全socket
我們從一個(gè)簡單的類開始,,它提供我們?cè)谄胀╯ocket對(duì)象之上的加密。表C(SecretSocket.java)包含了兩段代碼-Socket和Key對(duì)象,。我們的構(gòu)造器創(chuàng)建了變量并初始化了密碼:
outCipher = Cipher.getInstance(algorithm);
outCipher.init(Cipher.ENCRYPT_MODE, key);
inCipher = Cipher.getInstance(algorithm);
inCipher.init(Cipher.DECRYPT_MODE, key);
isting C?SecretSocket.java
/*
* Created by IntelliJ IDEA.
* User: jbirchfield
* Date: Mar 20, 2002
* Time: 9:07:51 AM
*/
import org.bouncycastle.
jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
public class SecretSocket
{
private Key key = null;
private Cipher outCipher = null;
private Cipher inCipher = null;
private CipherInputStream cis = null;
private CipherOutputStream cos = null;
private Socket socket = null;
private String algorithm = "DES";
public SecretSocket
(Socket socket, Key key)
{
this.socket = socket;
this.key = key;
algorithm = key.getAlgorithm();
initializeCipher();
}
private void initializeCipher()
{
try
{
outCipher = Cipher.getInstance
(algorithm);
outCipher.init(Cipher.ENCRYPT_MODE, key);
inCipher = Cipher.getInstance
(algorithm);
inCipher.init(Cipher.DECRYPT_MODE, key);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
}
public InputStream getInputStream()
throws IOException {
InputStream is =
socket.getInputStream();
cis = new CipherInputStream
(is, inCipher);
return cis;
}
public OutputStream getOutputStream()
throws IOException {
OutputStream os
= socket.getOutputStream();
cos = new CipherOutputStream
(os, outCipher);
return cos;
}
} |
因?yàn)閟ocket是雙向的通信,,所以我們采用兩個(gè)密碼。加密輸出的數(shù)據(jù)并解密輸入的數(shù)據(jù),。我們使用getInputStream()和getOutputStream(),這兩種方法來加密合解密通用的輸入和輸出的經(jīng)過包裝的數(shù)據(jù)流,。見表D。
isting D
public InputStream getInputStream()
throws IOException
{
InputStream is = socket.getInputStream();
cis = new CipherInputStream(is, inCipher);
return cis;
}
public OutputStream getOutputStream()
throws IOException {
OutputStream os = socket.getOutputStream();
cos = new CipherOutputStream(os, outCipher);
return cos;
} |
在JCE的javax.crypto包中包含CipherInputStream和CipherOutputStream這兩種流類型,。他們接收輸入輸出的流對(duì)象和密碼對(duì)象,。
Socket 服務(wù)器
開始寫我們的socket服務(wù)器類吧。表E(SecretSocketServer.java)是一個(gè)完整的列表,。SecretSocketServer在一個(gè)端口打開ServerSocket,當(dāng)接收到連接時(shí),,使用SocketHandler產(chǎn)生一個(gè)線程來操作連接,。
isting E?SecretSocketServer.java
/*
* Created by IntelliJ IDEA.
* User: jbirchfield
* Date: Mar 20, 2002
* Time: 9:32:17 AM
*/
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public class SecretSocketServer
{
public static void
main(String[] args)
{
new SecretSocketServer();
}
public SecretSocketServer()
{
ServerSocket ss = null;
try {
ss = new ServerSocket(4444);
}
catch (IOException e)
{
e.printStackTrace();
}
while(true) {
try {
System.out.println
("Waiting...");
Socket s = ss.accept();
SocketHandler h = new SocketHandler(s);
Thread t = new Thread(h);
t.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
} |
Socket 句柄
表F(SocketHandler.java)確定一個(gè)socket對(duì)象,通過KeyGen來定位關(guān)鍵字,,并建立一個(gè) SecretSocket 對(duì)象,。
Key key = KeyGen.getSecretKey();
this.ss = new SecretSocket(s, key);
isting F?SocketHandler.java
/*
* Created by IntelliJ IDEA.
* User: jbirchfield
* Date: Mar 20, 2002
* Time: 9:34:22 AM
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.Key;
public class SocketHandler
implements Runnable
{
private Socket s = null;
private SecretSocket ss = null;
private InputStream in = null;
public SocketHandler(Socket s)
{
this.s = s;
Key key = KeyGen.getSecretKey();
this.ss = new SecretSocket(s, key);
try {
in = ss.getInputStream();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void run()
{
boolean bool = true;
while (bool) {
bool = listen();
}
try {
s.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public boolean listen()
{
int aByte;
try
{
while ((aByte = in.read()) >= 0)
{
System.out.println((char)aByte);
}
}
catch (IOException e)
{
System.out.println
("returning false...");
}
return false;
}
} |
注意表F中的ss對(duì)SocketHandler來說是一個(gè)實(shí)變量。所有的socket處理都是通過SecretSocket而不是Socket對(duì)象,。然后我們使用下面的代碼:
in = ss.getInputStream(); |
記住,,在SecretSocket中,getInputStream是和CipherInputStream以及InputStream相結(jié)合的,。因?yàn)镾ocketHandler是一個(gè)可執(zhí)行的界面,,我們?yōu)樗梢粋€(gè)run()方法。這個(gè)方法只是在等待socket的數(shù)據(jù):
boolean bool = true;
while (bool)
{
bool = listen();
}
listen方法用來監(jiān)聽socket ,。
int aByte;
while ((aByte = in.read()) >= 0)
{
system.out.println((char)aByte);
} |
Socket 客戶
現(xiàn)在我們來看看客戶端,。見表G??蛻舳说墓ぷ骱头?wù)器端很相似,,只是反過來了,。首先,我們創(chuàng)立一個(gè)套接字連接到服務(wù)器,。使用KeyGen找到關(guān)鍵字,,創(chuàng)立一個(gè)安全套接字(SecretSocket)。然后我們利用它的OutputStream給服務(wù)器發(fā)送數(shù)據(jù):
Key key = KeyGen.getSecretKey();
Socket s = new Socket("localhost", 4444);
SecretSocket ss = new SecretSocket(s, key);
OutputStream os = ss.getOutputStream();
os.write("Hello World!".getBytes());
os.flush();
os.close();
s.close(); |
通過JCE中的Java流和鏈表,,我們可以輕松的加密基于socket的網(wǎng)絡(luò)通信,。
(T117)
|
|