很久很久很久,简直久以前的密码算法实验。。。
服务器启动,开启6666端口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| try { ss = new ServerSocket(6666); started = true; } catch (BindException e) { System.out.println("Sorry,Port in use!"); System.out.println("Please turn off the program to restart the server!"); System.exit(0); } catch (IOException e) { e.printStackTrace(); } try { while (started) { Socket s = ss.accept(); Client c = new Client(s); System.out.println("a client connected!"); new Thread(c).start(); clients.add(c); } } catch (IOException e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } }
|
客户机接入
1 2 3 4 5 6 7 8 9 10
| try { s = new Socket("localhost", 6666); dos = new DataOutputStream(s.getOutputStream()); dis = new DataInputStream(s.getInputStream()); bConnected = true; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
|
客户机构建窗体
(比较简陋的项目,只是eclipse里面做个窗体来假装客户机)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| setLocation(600, 300); add(tfTxt, BorderLayout.SOUTH); add(taContent, BorderLayout.NORTH); pack(); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent arg0) { disconnect(); System.exit(0); } }); tfTxt.addActionListener(new TFListener()); setVisible(true); connect(); tRecv.start();
|
服务器监听端口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| try { while (started) { Socket s = ss.accept(); Client c = new Client(s); System.out.println("a client connected!"); new Thread(c).start(); clients.add(c); } } catch (IOException e) { e.printStackTrace(); } finally { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } }
|
加密身份认证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| String str1 = null; Random random = new Random(); int r = random.nextInt(); String u = "hhardyy"; String Verification_code = u + r; String Decryption_certification = null; System.out.println("发送的认证消息" + u + r);
try { Rsa rsa = new Rsa(); KeyPair rsak = rsa.genKeyPair(); PrivateKey ks = rsak.getPrivate(); PublicKey kp = rsak.getPublic();
byte[] byte_Verification_code = Verification_code.getBytes("utf-8"); byte[] er = rsa.encrypt(byte_Verification_code, kp); saveKey(ks, "key_Private.key"); saveData(er, "key_pubData.data");
str1 = new String(er); System.out.println("服务器收到的客户机加密用户认证:" + str1); } catch (Exception e1) { e1.printStackTrace(); }
|
解密认证
注意:这里判断两个值是否相等不能用==或者===,=更不行,因为==或者===对比的是值得路径等等,所以要用str1.equals(str2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| String DemsgString=null; try { Rsa rsa = new Rsa(); PrivateKey privatekey = readKey("key_Private.key"); byte[] er = readData("key_pubData.data"); byte[] k = rsa.decrypt(er, privatekey); if (Verification_code.equals(Decryption_certification)) { str2 = "认证成功,允许通信"; } else { str2 = "认证失败"; DemsgString="身份认证失败"; } } catch (Exception e2) { e2.printStackTrace(); }
|
通信数据加密
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| try { Aes aes = new Aes(); String pwd = "xiaofangkuai"; byte[] aesKs = aes.genKey(pwd); System.out.println("通信内容:"+str); byte[] msgb=str.getBytes("utf-8"); byte[] em = aes.encrypt(msgb, aesKs); print("AES口令生成秘钥Key:",aesKs); System.out.println(""); String EemsgString = new String(em, "UTF-8"); System.out.println("加密之后:"+EemsgString); byte[] m = aes.decrypt(em, aesKs); DemsgString = new String(m, "UTF-8"); System.out.println("解密之后:"+m); System.out.println("转码:"+DemsgString); } catch (Exception ec) { ec.printStackTrace(); }
|
客户机关闭连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| try { dos.close(); dis.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } try { bConnected = false; tRecv.join(); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { dos.close(); dis.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } }
|
例子比较简陋,看懂不懂没关系,主要看配图
剑谱
保存秘钥的方法
1 2 3 4 5 6 7
| public static void saveKey(Key key, String keyName) throws Exception { FileOutputStream foskey = new FileOutputStream(keyName); ObjectOutputStream oos = new ObjectOutputStream(foskey); oos.writeObject(key); oos.close(); foskey.close(); }
|
保存数据的方法
1 2 3 4 5
| public static void saveData(byte[] results, String dataName) throws Exception { FileOutputStream fosData = new FileOutputStream(dataName); fosData.write(results); fosData.close(); }
|
读取数据的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public static byte[] readData(String dataName) throws Exception { FileInputStream fisDat = new FileInputStream(dataName);
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); int len = 0; byte[] data = new byte[1024]; while ((len = fisDat.read(data)) != -1) { arrayOutputStream.write(data, 0, len); } byte[] result = arrayOutputStream.toByteArray(); arrayOutputStream.close();
fisDat.close(); return result; }
|
读取秘钥的方法
1 2 3 4 5 6 7 8
| public static PrivateKey readKey(String keyName) throws Exception { FileInputStream fiskey = new FileInputStream(keyName); ObjectInputStream oiskey = new ObjectInputStream(fiskey); PrivateKey key = (PrivateKey) oiskey.readObject(); oiskey.close(); fiskey.close(); return key; }
|
Coder.java
1 2 3 4 5 6 7 8 9 10 11 12
| import java.util.Base64; public class Coder { public static String encode(byte[] data) { Base64.Encoder ecd = Base64.getEncoder(); return ecd.encodeToString(data); } public static byte[] decode(String str) { Base64.Decoder dcd = Base64.getDecoder(); return dcd.decode(str); } }
|
AES.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec;
public class TestAES { private Cipher cipher; public TestAES() throws Exception { cipher=Cipher.getInstance("AES"); } private SecretKey getKey(byte[] key) throws Exception{ return new SecretKeySpec(key, "AES"); } public byte[] encrypt(byte[] data, byte[] key) throws Exception{ cipher.init(Cipher.ENCRYPT_MODE, getKey(key)); byte [] encData=cipher.doFinal(data); return encData; } public byte[] decrypt(byte[] encData, byte[] key) throws Exception { cipher.init(Cipher.DECRYPT_MODE, getKey(key)); byte [] data=cipher.doFinal(encData); return data; } public byte[] genKey(String fact) throws Exception{ KeyGenerator keygen=KeyGenerator.getInstance("AES"); keygen.init(128, new SecureRandom(fact.getBytes())); SecretKey original_key=keygen.generateKey(); byte [] key=original_key.getEncoded(); return key; } public String genKeyStr(String fact) throws Exception{ byte [] key=genKey(fact); String keyStr = Coder.encode(key); return keyStr; } public String encrypt(String dataStr, String keyStr) throws Exception{ byte[] data = dataStr.getBytes(); byte[] key = Coder.decode(keyStr); byte[] edata = encrypt(data,key); return Coder.encode(edata); } public String decrypt(String encDataStr, String keyStr) throws Exception { byte[] edata = Coder.decode(encDataStr); byte[] key = Coder.decode(keyStr); byte [] data = decrypt(edata,key); return new String(data); } public static void main(String[] args) { try { TestAES t = new TestAES(); String pwd = "123456"; byte[] k = t.genKey(pwd); String msg = "Plain text 1"; byte[] msgb=msg.getBytes(); byte[] emsgb = t.encrypt(msgb, k); byte[] dmsgb = t.decrypt(emsgb, k);
t.print("Key",k); t.print("msgb", msgb); t.print("emsgb", emsgb); t.print("dmsgb", dmsgb);
System.out.println("End"); } catch(Exception ec) { ec.printStackTrace(); }
} private void print(String note, byte[] bs){ System.out.println(note+": "+Coder.encode(bs)); } }
|
Hash.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import java.security.MessageDigest;
public class TestHash { public byte[] getSha256(byte[] data) throws Exception{ MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(data); return md.digest(); } public byte[] getSha1(byte[] data) throws Exception { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); messageDigest.update(data); return messageDigest.digest(); } public static void main(String[] args) { try { TestHash t = new TestHash(); String msg = "a"; byte[] msgb=msg.getBytes(); byte[] d = t.getSha256(msgb); t.print("msgb", msgb); t.print("Dig", d); } catch(Exception ec) { ec.printStackTrace(); }
} private void print(String note, byte[] bs){ System.out.println(note+"["+bs.length+"]: "+Coder.encode(bs)); } }
|
RSA.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.Cipher;
public class TestRSA { Cipher cipher; public TestRSA() throws Exception{ cipher=Cipher.getInstance("RSA"); } public KeyPair genKeyPair() throws Exception{ KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); return keyPairGenerator.generateKeyPair(); } public String getKeyString() throws Exception { KeyPair k = genKeyPair(); String kstr = ""; return kstr; } public byte[] encrypt(byte[] content, PublicKey pKey) throws Exception{ cipher.init(Cipher.ENCRYPT_MODE, pKey); return cipher.doFinal(content); } public byte[] decrypt(byte[] content, PrivateKey sKey) throws Exception{ cipher.init(Cipher.DECRYPT_MODE, sKey); return cipher.doFinal(content); } public byte[] encrypt(byte[] content, PrivateKey sKey) throws Exception{ cipher.init(Cipher.ENCRYPT_MODE, sKey); return cipher.doFinal(content); } public byte[] decrypt(byte[] content, PublicKey pKey) throws Exception{ cipher.init(Cipher.DECRYPT_MODE, pKey); return cipher.doFinal(content); } public static void main(String[] args) { try { TestRSA t = new TestRSA(); KeyPair k = t.genKeyPair(); PrivateKey ks = k.getPrivate(); PublicKey kp = k.getPublic(); t.print("Private Key",ks.getEncoded()); t.print("Public Key",kp.getEncoded()); String msg="abcd"; byte[] msgb = msg.getBytes(); byte[] emsgb = t.encrypt(msgb,ks); byte[] dmsgb = t.decrypt(emsgb, kp); t.print("msgb", msgb); t.print("emsgb", emsgb); t.print("dmsgb", dmsgb); emsgb = t.encrypt(msgb,kp); dmsgb = t.decrypt(emsgb, ks); t.print("msgb", msgb); t.print("emsgb", emsgb); t.print("dmsgb", dmsgb); } catch(Exception ec) { ec.printStackTrace(); } } private void print(String note, byte[] bs){ System.out.println(note+"["+bs.length+"]: "+Coder.encode(bs)); } }
|