用Java的加密机制来保护你的数据

来源:互联网 发布:印度国产航母 知乎 编辑:程序博客网 时间:2024/05/16 17:36
<script type="text/javascript">google_ad_client = "pub-8800625213955058";/* 336x280, 创建于 07-11-21 */google_ad_slot = "0989131976";google_ad_width = 336;google_ad_height = 280;//</script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>Java开发工具包 (JDK)对加密和安全性有很好的支持。其中一个优势就是其内置的对Socket通信的支持。因此,很容易做到在服务器和客户之间建立安全的数据流。流Java streams 是一个强大的编程工具。java.io包提供了很多标准的流类型,并能很容易的建立自己的流类型。流的一个有用的特点是和链表一样的简单处理过程。表 A是一个用链表读取文本的例子。ufferedReader br = new BufferedReader( new FileReader(“c:/foo.txt”)); String line = null; while((line = br.readLine()) != null) { System.out.println(line); }这段代码将 FileReader和 BufferedReader链接起来。我们在用客户机/服务器应用程序的时候也会用到类似的概念。关键字对于验证来说,关键字很重要,表 B (KeyGen.java)提供了一个称为 getSecretKey的标准方法。通过运行KeyGen来产生一个关键字。因为我们采用同步方法,所以客户机和服务器必须用相同的关键字。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我们从一个简单的类开始,它提供我们在普通socket对象之上的加密。表 C (SecretSocket.java) 包含了两段代码-Socket和Key对象。我们的构造器创建了变量并初始化了密码: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; }}因为socket是双向的通信,所以我们采用两个密码。加密输出的数据并解密输入的数据。我们使用getInputStream()和 getOutputStream(),这两种方法来加密合解密通用的输入和输出的经过包装的数据流。见 表 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这两种流类型。他们接收输入输出的流对象和密码对象。Socket 服务器开始写我们的socket服务器类吧。 表 E (SecretSocketServer.java)是一个完整的列表。SecretSocketServer在一个端口打开ServerSocket,当接收到连接时,使用SocketHandler产生一个线程来操作连接。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) 确定一个socket对象,通过KeyGen来定位关键字,并建立一个 SecretSocket 对象。.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对SocketHandler来说是一个实变量。所有的socket 处理都是通过SecretSocket而不是Socket对象。然后我们使用下面的代码:in = ss.getInputStream();记住,在SecretSocket中,getInputStream是和CipherInputStream以及 InputStream相结合的。因为SocketHandler 是一个可执行的界面,我们为它生成一个 run()方法。这个方法只是在等待socket的数据:boolean bool = true;while (bool) {bool = listen();}listen方法用来监听socket 。int aByte;while ((aByte = in.read()) >= 0) {system.out.println((char)aByte);}Socket 客户现在我们来看看客户端。见 表 G 。客户端的工作和服务器端很相似,只是反过来了。首先,我们创立一个套接字连接到服务器。使用KeyGen 找到关键字,创立一个安全套接字(SecretSocket)。然后我们利用它的OutputStream给服务器发送数据: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的网络通信。
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小孩的脚踝扭伤怎么办 下楼梯脚扭伤了怎么办 脚扭伤脚背肿痛怎么办 瘫痪病人非常瘦怎么办 脚踝受伤肿了怎么办 跑步了脚痛了怎么办 半夜做噩梦惊醒怎么办 孩子英语不会读怎么办 减肥药吃完心慌怎么办 突然胃痛吐了怎么办 突然胃疼呕吐怎么办 胃疼呕吐厌食怎么办 小孩胃疼呕吐怎么办 胃疼得厉害怎么办 半夜胃痛的厉害怎么办 吃药刺激胃恶心怎么办 空腹吃药胃疼怎么办 吃药伤胃了怎么办 吃药刺激胃呕吐怎么办 吃药后胃不舒服怎么办 孩子脑子不开窍怎么办 打针打到神经怎么办 落枕严重动不了怎么办 因为着凉发烧了怎么办 烧到39度怎么办 来月经小腹痛怎么办 胃疼恶心呕吐怎么办 喝水吃东西胃疼怎么办 胃疼的厉害怎么办 肇事方没钱赔偿怎么办 车祸车主说没钱怎么办 癌症病吐血了怎么办 喝酒喝到吐血怎么办 抽烟咳痰有血丝怎么办 狗狗咳嗽气喘怎么办 小孩咳嗽有血丝怎么办 大学改名字学籍怎么办 改名字后护照怎么办 衣服变形变大了怎么办 衣服洗变形了怎么办 毛料西服缩水了怎么办