JAVA加密解密之DH算法

简介:

Diffie-Hellman:一种确保共享KEY安全穿越不安全网络的方法,它是OAKLEY的一个组成部分。Whitfield Diffie与Martin Hellman在1976年提出了一个奇妙的密钥交换协议,称为Diffie-Hellman密钥交换协议/算法(Diffie-Hellman Key Exchange/Agreement Algorithm).这个机制的巧妙在于需要安全通信的双方可以用这个方法确定对称密钥。然后可以用这个密钥进行加密和解密。但是注意,这个密钥交换协议/算法只能用于密钥的交换,而不能进行消息的加密和解密。双方确定要用的密钥后,要使用其他对称密钥操作加密算法实际加密和解密消息。

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

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

/**
 * DH(Diffie-Hellman算法(D-H算法),密钥一致协议)
 * 
 * @author jianggujin
 * 
 */
public class DHCoder
{
   private final String ALGORITHM = "DH";

   /**
    * 默认密钥字节数
    * 
    * <pre>
    * 默认密钥大小为1024,密钥长度必须是64的倍数,从512到1024
    * </pre>
    */
   private final int KEY_SIZE = 1024;

   /** DH加密下需要一种对称加密算法对数据加密,这里我们使用DES,也可以使用其他对称加密算法。 **/
   public String SECRET_ALGORITHM = "DES";
   /** 公钥Key **/
   public static final String PUBLIC_KEY = "DHPublicKey";
   /** 私钥Key **/
   public static final String PRIVATE_KEY = "DHPrivateKey";

   /**
    * 初始化甲方密钥
    * 
    * @return
    * @throws Exception
    */
   public Map<String, byte[]> initKey() throws Exception
   {
      KeyPairGenerator keyPairGenerator = KeyPairGenerator
            .getInstance(ALGORITHM);
      keyPairGenerator.initialize(KEY_SIZE);

      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      // 甲方公钥
      DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();

      // 甲方私钥
      DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();

      Map<String, byte[]> keyMap = new HashMap<String, byte[]>(2);

      keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
      keyMap.put(PRIVATE_KEY, privateKey.getEncoded());
      return keyMap;
   }

   /**
    * 初始化乙方密钥
    * 
    * @param key
    *           甲方公钥
    * @return
    * @throws Exception
    */
   public Map<String, byte[]> initKey(byte[] key) throws Exception
   {
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
      PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

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

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

      KeyPair keyPair = keyPairGenerator.generateKeyPair();

      // 乙方公钥
      DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();

      // 乙方私钥
      DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();

      Map<String, byte[]> keyMap = new HashMap<String, byte[]>(2);

      keyMap.put(PUBLIC_KEY, publicKey.getEncoded());
      keyMap.put(PRIVATE_KEY, privateKey.getEncoded());

      return keyMap;
   }

   /**
    * 加密<br>
    * 
    * @param data
    *           待加密数据
    * @param publicKey
    *           甲方公钥
    * @param privateKey
    *           乙方私钥
    * @return
    * @throws Exception
    */
   public byte[] encrypt(byte[] data, byte[] publicKey, byte[] privateKey)
         throws Exception
   {
      // 生成本地密钥
      SecretKey secretKey = getSecretKey(publicKey, privateKey);

      // 数据加密
      Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);

      return cipher.doFinal(data);
   }

   /**
    * 解密<br>
    * 
    * @param data
    *           待解密数据
    * @param publicKey
    *           乙方公钥
    * @param privateKey
    *           乙方私钥
    * @return
    * @throws Exception
    */
   public byte[] decrypt(byte[] data, byte[] publicKey, byte[] privateKey)
         throws Exception
   {
      // 生成本地密钥
      SecretKey secretKey = getSecretKey(publicKey, privateKey);
      // 数据解密
      Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, secretKey);

      return cipher.doFinal(data);
   }

   /**
    * 构建密钥
    * 
    * @param publicKey
    *           公钥
    * @param privateKey
    *           私钥
    * @return
    * @throws Exception
    */
   private SecretKey getSecretKey(byte[] publicKey, byte[] privateKey)
         throws Exception
   {
      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);

      // 生成本地密钥
      SecretKey secretKey = keyAgree.generateSecret(SECRET_ALGORITHM);

      return secretKey;
   }
}
目录
相关文章
|
23天前
|
存储 算法 Java
Java数据结构与算法-java数据结构与算法(二)
Java数据结构与算法-java数据结构与算法
66 1
|
11天前
|
算法 安全 Java
java代码 实现AES_CMAC 算法测试
该代码实现了一个AES-CMAC算法的简单测试,使用Bouncy Castle作为安全提供者。静态变量K定义了固定密钥。`Aes_Cmac`函数接受密钥和消息,返回AES-CMAC生成的MAC值。在`main`方法中,程序对给定的消息进行AES-CMAC加密,然后模拟接收ECU的加密结果并进行比较。如果两者匹配,输出&quot;验证成功&quot;,否则输出&quot;验证失败&quot;。辅助方法包括将字节转为16进制字符串和将16进制字符串转为字节。
|
11天前
|
Java 数据安全/隐私保护
java base64 加密 解密
java base64 加密 解密
|
17天前
|
搜索推荐 Java
Java排序算法
Java排序算法
18 0
|
17天前
|
搜索推荐 Java
Java基础(快速排序算法)
Java基础(快速排序算法)
23 4
|
20天前
|
存储 算法 JavaScript
Java入门高频考查算法逻辑基础知识3-编程篇(超详细18题1.8万字参考编程实现)
解决这类问题时,建议采取下面的步骤: 理解数学原理:确保你懂得基本的数学公式和法则,这对于制定解决方案至关重要。 优化算法:了解时间复杂度和空间复杂度,并寻找优化的机会。特别注意避免不必要的重复计算。 代码实践:多编写实践代码,并确保你的代码是高效、清晰且稳健的。 错误检查和测试:要为你的代码编写测试案例,测试标准的、边缘情况以及异常输入。 进行复杂问题简化:面对复杂的问题时,先尝试简化问题,然后逐步分析和解决。 沟通和解释:在编写代码的时候清晰地沟通你的思路,不仅要写出正确的代码,还要能向面试官解释你的
32 0
|
21天前
|
编解码 算法 安全
【Java技术专题】「入门到精通系列」深入探索Java技术中常用到的六种加密技术和实现
【Java技术专题】「入门到精通系列」深入探索Java技术中常用到的六种加密技术和实现
44 0
|
23天前
|
XML 存储 算法
Java数据结构与算法-java数据结构与算法(五)
Java数据结构与算法-java数据结构与算法
47 0
|
28天前
|
安全 Java 数据安全/隐私保护
提升 Java 编程安全性 - 代码加密混淆工具的重要性和应用
提升 Java 编程安全性 - 代码加密混淆工具的重要性和应用
|
Java 数据安全/隐私保护
Java实现最电话号码的简单加密源码
Java实现最电话号码的简单加密源码
17 0