通信加密

解决方案

2014/01/02 v1.0

设定A B 两用户,A用户发送经加密的信息给B用户,B用户识别后是加密信息进行解密,识别后是非加密信息不进行解密。

采用基于时间机制的随机密匙,每隔30秒将会生成新的随机密匙,保证A B 随机密匙相同。(类似Authenticator)

假定A发送文本消息为Hello, 然后使用随机密匙加密该文本消息,然后发送给B,B接收消息后取得当前网络的随机密匙解密获得文本信息。

测试代码

package start;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    private static long oldtime = 0;
    private static String oldkey = "";
    /**
     * @param args
     */
    public static void main(String[] args) {
        String send = "HELLO";
        while (true) {
            String key = getKey();
            System.out.println(key);

            try {
                byte[] str = encrypt(send, key);
                str = decrypt(str, key);
                System.out.println(new String(str));
                
                Thread.sleep(3 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    private static String getKey(){
        long newtime = System.currentTimeMillis();
        if (newtime - oldtime < 3 * 1000){
            return oldkey;
        }
        String key1 = String.valueOf((int) (Math.random() * 100000000));
        String key2 = String.valueOf((int) (Math.random() * 100000000));
        oldtime = newtime;
        oldkey = key1 + key2;
        return oldkey;
    }
    
    public static byte[] decrypt(byte[] msg, String password){
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(msg);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static byte[] encrypt(String msg, String password){
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(msg.getBytes());
            return result;
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}

缺点是:

密匙接口如果是开放的,那么将无法作用于加密,因为密匙是公开的。即使不是开放密匙,也不适用于多对多的用户情况。

期望结果是能 多用户对多用户的密匙。


你可能感兴趣的:(通信加密)