Java 加解密技術系列之 DH

來源:互聯網
上載者:User

標籤:加密   解密   技術   dh   



序
上一篇文章中簡單的介紹了一種非對稱式加密演算法 — — RSA,今天這篇文章,繼續介紹另一種非對稱式加密演算法 — — DH。當然,可能有很多人對這種密碼編譯演算法並不是很熟悉,不過沒關係,希望今天這篇文章能協助你熟悉他。

概念
DH,全稱為“Diffie-Hellman”,他是一種確保共用KEY安全穿越不安全網路的方法,也就是常說的密鑰一致協議。由公開密鑰密碼體制的奠基人Diffie和Hellman所提出的一種思想。
簡單的說就是允許兩名使用者在公開媒體上交換資訊以產生“一致”的、可以共用的密鑰。也就是由甲方產出一對密鑰(公開金鑰、私密金鑰),乙方依照甲方公開金鑰產生乙方金鑰組(公開金鑰、私密金鑰)。
以此為基準,作為資料轉送保密基礎,同時雙方使用同一種對稱式加密演算法構建本地密鑰(SecretKey)對資料加密。這樣,在互連了本地密鑰(SecretKey)演算法後,甲乙雙方公開自己的公開金鑰,使用對方的公開金鑰和剛才產生的私密金鑰加密資料,同時可以使用對方的公開金鑰和自己的私密金鑰對資料解密。不單單是甲乙雙方兩方,可以擴充為多方共用資料通訊,這樣就完成了網路互動資料的安全通訊!

原理
  • 通訊方A和通訊方B約定一個初始數g,g是公開的,如g=5;
  • A產生一個隨機數a,a是保密的,如a=6;
  • A計算g^a發送給B,g^a=5^6;
  • B產生一個隨機數b,b是保密的,如b=15;
  • B計算g^b發送給A,g^b=5^15;
  • A接收到g^b後,再使用保密的a,計算(g^b)^a=g^(a*b)=5^(6*15) ;
  • B接收到g^a後,再使用保密的b,計算(g^a)^b=g^(a*b)=5^(6*15);
  • 這樣通訊方A和B得到一個相同的“密鑰”g^(a*b)=5^(6*15)。

整個通訊過程中g、g^a、g^b是公開的,但由於g、a、b都是整數,通過g和g^a得到a還是比較容易的,b也是如此,所以最終的“密鑰”g^(a*b)還是可以被計算出來的。所以實際的過程還需要在基本原理上加入新的計算——模運算。
  • 通訊方A和通訊方B約定一個初始數g,如g=5,一個質數p,如p=23,g和p是公開的 ;
  • A產生一個隨機數a,a是保密的,如a=6 ;
  • A計算g^a%p發送給B,g^a%p=5^6%23=8 ;
  • B產生一個隨機數b,b是保密的,如b=15 ;
  • B計算g^b%p發送給A,g^b%p=5^15%23=19 ;
  • A接收到g^b%p後,再使用保密的a,計算(g^b%p)^a%p=19^6%23=2 ;
  • B接收到g^a%p後,再使用保密的b,計算(g^a%p)^b%p=8^15%23=2 ;
  • 這樣通訊方A和B得到一個相同的密鑰:2。

(g^b%p)^a%p=(g^a%p)^b%p 證明:
如果a=2:
  • (g^b%p)^a%p=(g^b%p)^2%p=(g^b-n*p)^2%p=(g^(2*b)-2*g^b*n*p+(n*p)^2)%p=g^(2*b)%p ;
  • 可以看出(g^b-n*p)^2展開後除g^(2*b)外,其它都是p的倍數,所以整個算式的結果是g^(2*b)%p ;
  • 同理對(g^b-n*p)^a展開後除g^(a*b)外,其它都是p的倍數,所以整個算式的結果是g^(a*b)%p ;
  • 同樣可以得出(g^a%p)^b%p=g^(a*b)%p ;
  • 所以(g^b%p)^a%p=(g^a%p)^b%p 。

整個通訊過程中g、p、g^a%p、g^b%p是公開的,這時通過g、p、g^a%p得到a比較難,同樣通過g、p、g^b%p得到b比較難,所以最終的密鑰是比較安全的。
以g=5、p=23、g^a%p=8計算a為例,a=log(5, (8+23*n)),這個只能將n的可能值逐個帶入公式實驗才能得到a的值。如果a、p是比較大的數那麼計算更加困難。
需要注意的是,為了防止應用最佳化演算法計算上述問題,質數p不是隨便選擇的,需要符合一定的條件。隨機數a、b的產生演算法也必需注意,應使結果儘可能隨機,不能出現可預測的規律,否則會使破解變的容易。

代碼實現
<span style="font-family:Comic Sans MS;font-size:12px;">package com.test.dh;import com.google.common.collect.Maps;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import javax.crypto.*;import javax.crypto.interfaces.DHPrivateKey;import javax.crypto.interfaces.DHPublicKey;import javax.crypto.spec.DHParameterSpec;import java.security.*;import java.security.spec.PKCS8EncodedKeySpec;import java.security.spec.X509EncodedKeySpec;import java.util.Map;/** * Created by xiang.li on 2015/3/4. * DH 加解密工具類 */public class DH {    /**     * 定義加密方式     */    private static final String KEY_DH = "DH";    /**     * 預設密鑰位元組數     */    private static final int KEY_SIZE = 1024;    /**     * DH加密下需要一種對稱式加密演算法對資料加密,這裡我們使用DES,也可以使用其他對稱式加密演算法     */    private static final String KEY_DH_DES = "DES";    private static final String KEY_DH_PUBLICKEY = "DHPublicKey";    private static final String KEY_DH_PRIVATEKEY = "DHPrivateKey";    /**     * 初始化甲方密鑰     * @return     */    public static Map<String, Object> init() {        Map<String, Object> map = null;        try {            KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_DH);            generator.initialize(KEY_SIZE);            KeyPair keyPair = generator.generateKeyPair();            // 甲方公開金鑰            DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();            // 甲方私密金鑰            DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();            map = Maps.newHashMap();            map.put(KEY_DH_PUBLICKEY, publicKey);            map.put(KEY_DH_PRIVATEKEY, privateKey);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        }        return map;    }    /**     * 初始化乙方密鑰     * @param key 甲方密鑰     * @return     */    public static Map<String, Object> init(String key) {        Map<String, Object> map = null;        try {            // 解析甲方密鑰            byte[] bytes = decryptBase64(key);            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);            KeyFactory factory = KeyFactory.getInstance(KEY_DH);            PublicKey publicKey = factory.generatePublic(keySpec);            // 由甲方公開金鑰構建乙方密鑰            DHParameterSpec spec = ((DHPublicKey) publicKey).getParams();            KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_DH);            generator.initialize(spec);            KeyPair keyPair = generator.generateKeyPair();            // 乙方公開金鑰            DHPublicKey dhPublicKey = (DHPublicKey) keyPair.getPublic();            // 乙方私密金鑰            DHPrivateKey dhPrivateKey = (DHPrivateKey) keyPair.getPrivate();            map = Maps.newHashMap();            map.put(KEY_DH_PUBLICKEY, dhPublicKey);            map.put(KEY_DH_PRIVATEKEY, dhPrivateKey);        } catch (Exception e) {            e.printStackTrace();        }        return map;    }    /**     * DH 加密     * @param data 帶加密資料     * @param publicKey 甲方公開金鑰     * @param privateKey 乙方私密金鑰     * @return     */    public static byte[] encryptDH(byte[] data, String publicKey, String privateKey) {        byte[] bytes = null;        try {            // 產生本地密鑰            SecretKey secretKey = getSecretKey(publicKey, privateKey);            // 資料加密            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());            cipher.init(Cipher.ENCRYPT_MODE, secretKey);            bytes = cipher.doFinal(data);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (NoSuchPaddingException e) {            e.printStackTrace();        } catch (InvalidKeyException e) {            e.printStackTrace();        } catch (BadPaddingException e) {            e.printStackTrace();        } catch (IllegalBlockSizeException e) {            e.printStackTrace();        }        return bytes;    }    /**     * DH 解密     * @param data 待解密資料     * @param publicKey 乙方公開金鑰     * @param privateKey 甲方私密金鑰     * @return     */    public static byte[] decryptDH(byte[] data, String publicKey, String privateKey) {        byte[] bytes = null;        try {            // 產生本地密鑰            SecretKey secretKey = getSecretKey(publicKey, privateKey);            // 資料解密            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());            cipher.init(Cipher.DECRYPT_MODE, secretKey);            bytes = cipher.doFinal(data);        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (NoSuchPaddingException e) {            e.printStackTrace();        } catch (InvalidKeyException e) {            e.printStackTrace();        } catch (BadPaddingException e) {            e.printStackTrace();        } catch (IllegalBlockSizeException e) {            e.printStackTrace();        }        return bytes;    }    /**     * 取得私密金鑰     * @param map     * @return     */    public static String getPrivateKey(Map<String, Object> map) {        String str = "";        try {            Key key = (Key) map.get(KEY_DH_PRIVATEKEY);            str = encryptBase64(key.getEncoded());        } catch (Exception e) {            e.printStackTrace();        }        return str;    }    /**     * 取得公開金鑰     * @param map     * @return     */    public static String getPublicKey(Map<String, Object> map) {        String str = "";        try {            Key key = (Key) map.get(KEY_DH_PUBLICKEY);            str = encryptBase64(key.getEncoded());        } catch (Exception e) {            e.printStackTrace();        }        return str;    }    /**     * 構建本地密鑰     * @param publicKey 公開金鑰     * @param privateKey 私密金鑰     * @return     */    private static SecretKey getSecretKey(String publicKey, String privateKey) {        SecretKey secretKey = null;        try {            // 初始化公開金鑰            byte[] publicBytes = decryptBase64(publicKey);            KeyFactory factory = KeyFactory.getInstance(KEY_DH);            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);            PublicKey localPublicKey = factory.generatePublic(keySpec);            // 初始化私密金鑰            byte[] privateBytes = decryptBase64(privateKey);            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateBytes);            PrivateKey localPrivateKey = factory.generatePrivate(spec);            KeyAgreement agreement = KeyAgreement.getInstance(factory.getAlgorithm());            agreement.init(localPrivateKey);            agreement.doPhase(localPublicKey, true);            // 產生本地密鑰            secretKey = agreement.generateSecret(KEY_DH_DES);        } catch (Exception e) {            e.printStackTrace();        }        return secretKey;    }    /**     * BASE64 解密     * @param key 需要解密的字串     * @return 位元組數組     * @throws Exception     */    public static byte[] decryptBase64(String key) throws Exception {        return (new BASE64Decoder()).decodeBuffer(key);    }    /**     * BASE64 加密     * @param key 需要加密的位元組數組     * @return 字串     * @throws Exception     */    public static String encryptBase64(byte[] key) throws Exception {        return (new BASE64Encoder()).encodeBuffer(key);    }    /**     * 測試方法     * @param args     */    public static void main(String[] args) {        // 產生甲方金鑰組        Map<String, Object> mapA = init();        String publicKeyA = getPublicKey(mapA);        String privateKeyA = getPrivateKey(mapA);        System.out.println("甲方公開金鑰:\n" + publicKeyA);        System.out.println("甲方私密金鑰:\n" + privateKeyA);        // 由甲方公開金鑰產生本地金鑰組        Map<String, Object> mapB = init(publicKeyA);        String publicKeyB = getPublicKey(mapB);        String privateKeyB = getPrivateKey(mapB);        System.out.println("乙方公開金鑰:\n" + publicKeyB);        System.out.println("乙方私密金鑰:\n" + privateKeyB);        String word = "abc";        System.out.println("原文: " + word);        // 由甲方公開金鑰,乙方私密金鑰構建密文        byte[] encWord = encryptDH(word.getBytes(), publicKeyA, privateKeyB);        // 由乙方公開金鑰,甲方私密金鑰解密        byte[] decWord = decryptDH(encWord, publicKeyB, privateKeyA);        System.out.println("解密: " + new String(decWord));    }}</span><span style="font-family: 微軟雅黑; font-size: 14px;"></span>


結果





結束語
這個機制的巧妙在於需要安全通訊的雙方可以用這個方法確定對稱金鑰。然後可以用這個密鑰進行加密和解密。但是注意,這個金鑰交換協議/演算法只能用於密鑰的交換,而不能進行訊息的加密和解密。雙方確定要用的密鑰後,要使用其他對稱金鑰操作密碼編譯演算法實際加密和解密訊息。

Java 加解密技術系列之 DH

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.