天天看點

JAVA加密解密之DH(Diffie-Hellman)算法DH算法簡介DH算法實作

DH算法簡介

Diffie-Hellman算法(D-H算法),密鑰一緻協定。是由公開密鑰密碼體制的創始者Diffie和Hellman所提出的一種思想。簡單的說就是允許兩名使用者在公開媒體上交換資訊以生成”一緻”的、可以共享的密鑰。換句話說,就是由甲方産出一對密鑰(公鑰、私鑰),乙方依照甲方公鑰産生乙方密鑰對(公鑰、私鑰)。以此為基線,作為資料傳輸保密基礎,同時雙方使用同一種對稱加密算法建構本地密鑰(SecretKey)對資料加密。這樣,在互通了本地密鑰(SecretKey)算法後,甲乙雙方公開自己的公鑰,使用對方的公鑰和剛才産生的私鑰加密資料,同時可以使用對方的公鑰和自己的私鑰對資料解密。不單單是甲乙雙方兩方,可以擴充為多方共享資料通訊,這樣就完成了網絡互動資料的安全通訊!該算法源于中國的同餘定理——中國馀數定理。

  1. 甲方建構密鑰對兒,将公鑰公布給乙方,将私鑰保留;雙方約定資料加密算法;乙方通過甲方公鑰建構密鑰對兒,将公鑰公布給甲方,将私鑰保留。
  2. 甲方使用私鑰、乙方公鑰、約定資料加密算法建構本地密鑰,然後通過本地密鑰加密資料,發送給乙方加密後的資料;乙方使用私鑰、甲方公鑰、約定資料加密算法建構本地密鑰,然後通過本地密鑰對資料解密。
  3. 乙方使用私鑰、甲方公鑰、約定資料加密算法建構本地密鑰,然後通過本地密鑰加密資料,發送給甲方加密後的資料;甲方使用私鑰、乙方公鑰、約定資料加密算法建構本地密鑰,然後通過本地密鑰對資料解密。

DH算法實作

package com.jianggujin.codec;

import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;

import com.jianggujin.codec.util.JCipherInputStream;
import com.jianggujin.codec.util.JCipherOutputStream;
import com.jianggujin.codec.util.JCodecException;

/**
 * Diffie-Hellman算法(D-H算法),密鑰一緻協定。是由公開密鑰密碼體制的創始者Diffie和Hellman所提出的一種思想。
 * 簡單的說就是允許兩名使用者在公開媒體上交換資訊以生成"一緻"的、可以共享的密鑰。換句話說,就是由甲方産出一對密鑰(公鑰、私鑰),
 * 乙方依照甲方公鑰産生乙方密鑰對(公鑰、私鑰)。以此為基線,作為資料傳輸保密基礎,同時雙方使用同一種對稱加密算法建構本地密鑰(SecretKey)對資料加密
 * 。這樣,在互通了本地密鑰(SecretKey)算法後,甲乙雙方公開自己的公鑰,使用對方的公鑰和剛才産生的私鑰加密資料,
 * 同時可以使用對方的公鑰和自己的私鑰對資料解密。不單單是甲乙雙方兩方,可以擴充為多方共享資料通訊,這樣就完成了網絡互動資料的安全通訊!
 * 該算法源于中國的同餘定理——中國馀數定理
 * <ol>
 * <li>甲方建構密鑰對兒,将公鑰公布給乙方,将私鑰保留;雙方約定資料加密算法;乙方通過甲方公鑰建構密鑰對兒,将公鑰公布給甲方,将私鑰保留。</li>
 * <li>甲方使用私鑰、乙方公鑰、約定資料加密算法建構本地密鑰,然後通過本地密鑰加密資料,發送給乙方加密後的資料;乙方使用私鑰、甲方公鑰、
 * 約定資料加密算法建構本地密鑰,然後通過本地密鑰對資料解密。</li>
 * <li>乙方使用私鑰、甲方公鑰、約定資料加密算法建構本地密鑰,然後通過本地密鑰加密資料,發送給甲方加密後的資料;甲方使用私鑰、乙方公鑰、
 * 約定資料加密算法建構本地密鑰,然後通過本地密鑰對資料解密。</li>
 * </ol>
 * 
 * @author jianggujin
 * 
 */
public class JDH {

   private final static String ALGORITHM = "DH";

   /**
    * 對稱算法
    * 
    * @author jianggujin
    *
    */
   public static enum JDHSymmetricalAlgorithm {
      DES, DESede;
      public String getName() {
         return this.name();
      }
   }

   /**
    * 初始化甲方密鑰
    * 
    * @return
    */
   public static KeyPair initPartyAKey() {
      return initPartyAKey();
   }

   /**
    * 初始化甲方密鑰
    * 
    * @param keySize
    * @return
    */
   public static KeyPair initPartyAKey(int keySize) {
      try {
         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
         keyPairGen.initialize(keySize);
         return keyPairGen.generateKeyPair();
      } catch (NoSuchAlgorithmException e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 初始化乙方密鑰
    * 
    * @param partyAPublicKey
    *           甲方公鑰
    * @return
    */
   public static KeyPair initPartyBKey(byte[] partyAPublicKey) {
      try {
         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(partyAPublicKey);
         KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
         PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

         // 由甲方公鑰建構乙方密鑰
         DHParameterSpec dhParamSpec = ((DHPublicKey) pubKey).getParams();

         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyFactory.getAlgorithm());
         keyPairGenerator.initialize(dhParamSpec);

         return keyPairGenerator.generateKeyPair();
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 加密
    * 
    * @param data
    *           加密資料
    * @param privateKey
    *           己方私鑰
    * @param publicKey
    *           對方公鑰
    * @param algorithm
    *           對稱算法
    * @return
    */
   public static byte[] encrypt(byte[] data, byte[] privateKey, byte[] publicKey, String algorithm) {
      // 資料加密
      Cipher cipher = getEncryptCipher(privateKey, publicKey, algorithm);

      try {
         return cipher.doFinal(data);
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 包裹輸出流,包裹後的輸出流為加密輸出流
    * 
    * @param out
    * @param privateKey
    * @param publicKey
    * @param algorithm
    * @return
    */
   public static OutputStream wrap(OutputStream out, byte[] privateKey, byte[] publicKey, String algorithm) {
      // 資料加密
      Cipher cipher = getEncryptCipher(privateKey, publicKey, algorithm);

      return new JCipherOutputStream(cipher, out);
   }

   /**
    * 獲得加密模式的{@link Cipher}
    * 
    * @param privateKey
    * @param publicKey
    * @param algorithm
    * @return
    */
   public static Cipher getEncryptCipher(byte[] privateKey, byte[] publicKey, String algorithm) {
      return getCipher(privateKey, publicKey, algorithm, Cipher.ENCRYPT_MODE);
   }

   /**
    * 解密
    * 
    * @param data
    *           解密資料
    * @param privateKey
    *           己方私鑰
    * @param publicKey
    *           對方公鑰
    * @param algorithm
    *           對稱算法
    * @return
    */
   public static byte[] decrypt(byte[] data, byte[] privateKey, byte[] publicKey, String algorithm) {
      // 資料解密
      Cipher cipher = getDecryptCipher(privateKey, publicKey, algorithm);
      try {
         return cipher.doFinal(data);
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 包裹輸入流,原輸入流為加密資料輸入流
    * 
    * @param in
    * @param privateKey
    * @param publicKey
    * @param algorithm
    * @return
    */
   public static InputStream wrap(InputStream in, byte[] privateKey, byte[] publicKey, String algorithm) {
      // 資料解密
      Cipher cipher = getDecryptCipher(privateKey, publicKey, algorithm);
      return new JCipherInputStream(cipher, in);
   }

   /**
    * 獲得解密模式的{@link Cipher}
    * 
    * @param privateKey
    * @param publicKey
    * @param algorithm
    * @return
    */
   public static Cipher getDecryptCipher(byte[] privateKey, byte[] publicKey, String algorithm) {
      return getCipher(privateKey, publicKey, algorithm, Cipher.DECRYPT_MODE);
   }

   private static Cipher getCipher(byte[] privateKey, byte[] publicKey, String algorithm, int opmode) {
      // 生成本地密鑰
      SecretKey secretKey = getSecretKey(privateKey, publicKey, algorithm);

      try {
         // 資料加密
         Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
         cipher.init(opmode, secretKey);
         return cipher;
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }

   /**
    * 獲得密鑰
    * 
    * @param privateKey
    *           己方私鑰
    * @param publicKey
    *           對方公鑰
    * @param algorithm
    *           對稱算法
    * @return
    */
   private static SecretKey getSecretKey(byte[] privateKey, byte[] publicKey, String algorithm) {
      try {
         KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
         X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
         PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

         PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
         Key priKey = keyFactory.generatePrivate(pkcs8KeySpec);

         KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
         keyAgree.init(priKey);
         keyAgree.doPhase(pubKey, true);

         // 生成本地密鑰
         return keyAgree.generateSecret(algorithm);
      } catch (Exception e) {
         throw new JCodecException(e);
      }
   }
}
           

測試代碼:

package com.jianggujin.codec.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyPair;

import org.junit.Test;

import com.jianggujin.codec.JBase64;
import com.jianggujin.codec.JBase64.JEncoder;
import com.jianggujin.codec.JDH;
import com.jianggujin.codec.JDH.JDHSymmetricalAlgorithm;

public class DHTest {
   String str = "jianggujin";
   File file = new File(getClass().getSimpleName() + ".dat");

   @Test
   public void test() throws Exception {
      System.out.println("原串:" + str);
      JEncoder encoder = JBase64.getEncoder();
      KeyPair keyPairA = JDH.initPartyAKey();
      byte[] keyPairAPrivate = keyPairA.getPrivate().getEncoded();
      byte[] keyPairAPublic = keyPairA.getPublic().getEncoded();
      System.out.println("甲方私鑰:" + encoder.encodeToString(keyPairAPrivate, "UTF-8"));
      System.out.println("甲方公鑰:" + encoder.encodeToString(keyPairAPublic, "UTF-8"));
      KeyPair keyPairB = JDH.initPartyBKey(keyPairAPublic);
      byte[] keyPairBPrivate = keyPairB.getPrivate().getEncoded();
      byte[] keyPairBPublic = keyPairB.getPublic().getEncoded();
      System.out.println("乙方私鑰:" + encoder.encodeToString(keyPairBPrivate, "UTF-8"));
      System.out.println("乙方公鑰:" + encoder.encodeToString(keyPairBPublic, "UTF-8"));
      for (JDHSymmetricalAlgorithm algorithm : JDHSymmetricalAlgorithm.values()) {
         System.out.println("-----------------------------------------");
         System.out.println("對稱算法:" + algorithm.getName());
         byte[] encrypt = JDH.encrypt(str.getBytes(), keyPairAPrivate, keyPairBPublic, algorithm.getName());
         System.out.println("加密:" + encoder.encodeToString(encrypt, "UTF-8"));
         System.out
               .println("解密:" + new String(JDH.decrypt(encrypt, keyPairBPrivate, keyPairAPublic, algorithm.getName())));

         System.out.print("輸出流加密:" + file.getAbsolutePath());
         OutputStream out = JDH.wrap(new FileOutputStream(file), keyPairAPrivate, keyPairBPublic, algorithm.getName());
         out.write(str.getBytes());
         out.flush();
         out.close();
         System.out.println();
         System.out.print("輸入流解密:");
         InputStream in = JDH.wrap(new FileInputStream(file), keyPairBPrivate, keyPairAPublic, algorithm.getName());
         byte[] buffer = new byte[];
         int len = in.read(buffer);
         System.out.println(new String(buffer, , len));
      }
   }
}
           

測試結果:

原串:jianggujin

甲方私鑰:MIIBZwIBADCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoCAgIABEMCQQCKZ/IM4bTS0YkWGsMGFY6NAAICuvHpvhSBaPZ3Le4PS/owyrEnsiS3AXig5OYYko/fVvIBz1kOaKTl/0tsQLtt

甲方公鑰:MIIBpzCCARsGCSqGSIb3DQEDATCCAQwCgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F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iUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoCAgIAA4GEAAKBgDtzbZB/0vIobewwv7mUGGS54TBuNGf6wl3lLsAfTKylvzD2//qPqTJVXBGy9ZInHMYOwLb5nn85l8oULoXsp0uwZe2cFpmgJfRFpRD2FH+ZahBbtb7zgdsB30t0y42Qed+bL/o8znzv5yE1E6/z2iQdKhCRc52254hWgUVDkrH5

—————————————–

對稱算法:DES

加密:zBJhlhWDFme0qIlClaBUQw==

解密:jianggujin

輸出流加密:F:\workspace\java\eclipse\JCodec\DHTest.dat

輸入流解密:jianggujin

—————————————–

對稱算法:DESede

加密:0TFsnTdcA3JuJH2ZYn1ZcQ==

解密:jianggujin

輸出流加密:F:\workspace\java\eclipse\JCodec\DHTest.dat

輸入流解密:jianggujin