`
sillycat
  • 浏览: 2552183 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

bouncycastle(6)Learn from others DH

    博客分类:
  • JAVA
 
阅读更多
bouncycastle(6)Learn from others DH

DH (Diffie-Hellman)
A will generate the key pair A-key, and share the public key to B.
B will generate the key pair B-key, and share the public key to A.

A will use A-private-key and B-public-key to encrypt the data.
B will use A-public-key and B-private-key to decrypt the data.

B--->A will be opposite.

package com.sillycat.easycastle.encryption;

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;

public abstract class DHCoder extends Coder {

     public static final String ALGORITHM = "DH";

     /**
      * default key size
      * <pre>
      * DH
      * Default Keysize 1024 
      * Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).
      * </pre>
      */
     private static final int KEY_SIZE = 1024;

     /**
      * DH need a symmetry like DES to encrypt the data
      */
     public static final String SECRET_ALGORITHM = "DES";
     private static final String PUBLIC_KEY = "DHPublicKey";
     private static final String PRIVATE_KEY = "DHPrivateKey";

     /**
      * initiate A key pair
      * @return
      * @throws Exception
      */
     public static Map<String, Object> initKey() throws Exception {
          KeyPairGenerator keyPairGenerator = KeyPairGenerator
                    .getInstance(ALGORITHM);
          keyPairGenerator.initialize(KEY_SIZE);
          KeyPair keyPair = keyPairGenerator.generateKeyPair();
          //a public key
          DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
          //a private key
          DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();
          Map<String, Object> keyMap = new HashMap<String, Object>(2);
          keyMap.put(PUBLIC_KEY, publicKey);
          keyMap.put(PRIVATE_KEY, privateKey);
          return keyMap;
     }

     /**
      * initiate the b key pair
      * @param key
      *            a public key
      * @return
      * @throws Exception
      */
     public static Map<String, Object> initKey(String aPublicKey) throws Exception {
          //convert a public key
          byte[] keyBytes = decryptBASE64(aPublicKey);
          X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
          KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
          PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);

          // generate b private key from a public key
          DHParameterSpec dhParamSpec = ((DHPublicKey) pubKey).getParams();
          KeyPairGenerator keyPairGenerator = KeyPairGenerator
                    .getInstance(keyFactory.getAlgorithm());
          keyPairGenerator.initialize(dhParamSpec);
          KeyPair keyPair = keyPairGenerator.generateKeyPair();
          //b public key
          DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
          //b private key
          DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();
          Map<String, Object> keyMap = new HashMap<String, Object>(2);
          keyMap.put(PUBLIC_KEY, publicKey);
          keyMap.put(PRIVATE_KEY, privateKey);
          return keyMap;
     }

     /**
      * encryption
      *
      * @param data
      * @param publicKey
      * @param privateKey
      * @return
      * @throws Exception
      */
     public static byte[] encrypt(byte[] data, String publicKey,
               String privateKey) throws Exception {
          //generate the local key from public and private keys.
          SecretKey secretKey = getSecretKey(publicKey, privateKey);
          //encrypt the data
          Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
          cipher.init(Cipher.ENCRYPT_MODE, secretKey);
          return cipher.doFinal(data);
     }

     /**
      * decryption
      * @param data
      * @param publicKey
      * @param privateKey
      * @return
      * @throws Exception
      */
     public static byte[] decrypt(byte[] data, String publicKey,
               String privateKey) throws Exception {
          // generate the local key from public and private keys
          SecretKey secretKey = getSecretKey(publicKey, privateKey);
          // decrypt the data
          Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
          cipher.init(Cipher.DECRYPT_MODE, secretKey);
          return cipher.doFinal(data);
     }

     /**
      * generate the local key
      *
      * @param publicKey
      * @param privateKey
      * @return
      * @throws Exception
      */
     private static SecretKey getSecretKey(String publicKey, String privateKey)
               throws Exception {
          //decrypt the public key string
          byte[] pubKeyBytes = decryptBASE64(publicKey);
          KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
          X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);
          PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
          //decrypt the private key string
          byte[] priKeyBytes = decryptBASE64(privateKey);
          PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyBytes);
          Key priKey = keyFactory.generatePrivate(pkcs8KeySpec);

          KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory
                    .getAlgorithm());
          keyAgree.init(priKey);
          keyAgree.doPhase(pubKey, true);
          //generate the local key
          SecretKey secretKey = keyAgree.generateSecret(SECRET_ALGORITHM);
          return secretKey;
     }

     /**
      * get the private key from key map
      * @param keyMap
      * @return
      * @throws Exception
      */
     public static String getPrivateKey(Map<String, Object> keyMap)
               throws Exception {
          Key key = (Key) keyMap.get(PRIVATE_KEY);
          return encryptBASE64(key.getEncoded());
     }

     /**
      * get the public key from key map
      * @param keyMap
      * @return
      * @throws Exception
      */
     public static String getPublicKey(Map<String, Object> keyMap)
               throws Exception {
          Key key = (Key) keyMap.get(PUBLIC_KEY);
          return encryptBASE64(key.getEncoded());
     }
}


The test case will be as follow:
package com.sillycat.easycastle.encryption;

import static org.junit.Assert.assertEquals;

import java.util.Map;

import org.junit.Test;

public class DHCoderTest {

     @Test
     public void test() throws Exception {
          //generate the public key pair
          Map<String, Object> aKeyMap = DHCoder.initKey();
          String aPublicKey = DHCoder.getPublicKey(aKeyMap);
          String aPrivateKey = DHCoder.getPrivateKey(aKeyMap);

          System.out.println("A Public Key:\r" + aPublicKey);
          System.out.println("A Private Key:\r" + aPrivateKey);

          // B will generate the key pair based on A public key
          Map<String, Object> bKeyMap = DHCoder.initKey(aPublicKey);
          String bPublicKey = DHCoder.getPublicKey(bKeyMap);
          String bPrivateKey = DHCoder.getPrivateKey(bKeyMap);

          System.out.println("B Public Key:\r" + bPublicKey);
          System.out.println("B Private Key:\r" + bPrivateKey);

          System.out.println(" ===============first process================== ");
          String aInput = "original data content";
          System.out.println("data: " + aInput);
        
          // based on a public key, b private key, encryption
          byte[] aCode = DHCoder.encrypt(aInput.getBytes(), aPublicKey,
                    bPrivateKey);

          // based on b public key, a private key, decryption
          byte[] aDecode = DHCoder.decrypt(aCode, bPublicKey, aPrivateKey);
          String aOutput = (new String(aDecode));

          System.out.println("decryption 1: " + aOutput);
          assertEquals(aInput, aOutput);
          System.out.println(" ===============sencond process================== ");
          String bInput = "sencond data content";
          System.out.println("data: " + bInput);
          byte[] bCode = DHCoder.encrypt(bInput.getBytes(), bPublicKey,
                    aPrivateKey);
          byte[] bDecode = DHCoder.decrypt(bCode, aPublicKey, bPrivateKey);
          String bOutput = (new String(bDecode));
          System.out.println("decryption 2: " + bOutput);
          assertEquals(bInput, bOutput);
     }
}


DH is suitable for my system.

references:
http://snowolf.iteye.com/blog/382422


分享到:
评论

相关推荐

    BouncyCastle依赖.zip

    BouncyCastle是一个强大的Java安全库,它为加密、数字签名、证书处理以及许多其他安全功能提供了全面的支持。在Android开发中,BouncyCastle扮演着重要角色,特别是在处理SSL/TLS连接、加密通信以及生成和验证X.509...

    bouncycastle jar包

    **Bouncy Castle简介** Bouncy Castle是一个开源的Java加密库,提供了广泛的加密算法、协议实现以及相关的工具。这个jar包是专门为Java开发者设计的,它弥补了Java标准加密API(如JCE)在某些功能上的不足,使得...

    BouncyCastle.Crypto.dll

    BouncyCastle.Crypto.dll是一个开源的加密库,由The Legion of the Bouncy Castle组织开发,提供了大量加密算法和协议的实现,包括但不限于RSA、AES、DES、DH(Diffie-Hellman)、ECC(椭圆曲线密码学)等。...

    BouncyCastle.Crypto

    《BouncyCastle.Crypto:C#中的加密库详解》 在信息安全领域,加密技术是保障数据安全的关键。本文将深入探讨BouncyCastle.Crypto.dll,一个广泛使用的C#加密库,版本1.8.1。BouncyCastle项目,被誉为"The Legion ...

    org.bouncycastle 加密算法包 最新1.69版

    ** org.bouncycastle 加密算法包详解 ** `org.bouncycastle` 是一个开源的 Java 库,专门用于实现各种加密算法和相关的安全服务。它提供了广泛的加密功能,包括对称和非对称加密、数字签名、哈希函数、证书管理、...

    BouncyCastle.Crypto.dll 版本1.8.6 C#语言

    6. **可扩展性**:BouncyCastle库的模块化设计允许开发者轻松添加新的算法或实现自定义的密码学逻辑,增加了库的灵活性和适应性。 7. **跨平台兼容**:虽然我们在此讨论的是C#版本,但BouncyCastle最初是为Java设计...

    BouncyCastle.Crypto.dll 版本1.8.1

    6. **TLS/SSL 实现**:BouncyCastle 可以作为.NET的SSL/TLS实现,用于安全的网络连接。 7. **轻量级加密API (Lightweight API)**:对于资源有限的环境,BouncyCastle 提供了一个轻量级的加密API,以降低内存和CPU的...

    BouncyCastle.Crypto.rar

    《BouncyCastle.Crypto.dll:理解与应用》 在信息技术领域,加密库是保障数据安全的重要工具,而BouncyCastle.Crypto.dll就是这样一个强大的加密库,尤其在.NET框架下广泛被开发者所使用。BouncyCastle项目,作为一...

    bouncycastle1.59 帮助文档(包含html源文件制作工具)

    《BouncyCastle1.59帮助文档:深入理解与CHM制作详解》 BouncyCastle,作为Java和.NET平台上广泛使用的开源加密库,为开发者提供了丰富的加密算法、密码学标准接口以及证书处理功能。这份“BouncyCastle1.59帮助...

    BouncyCastle.dll C#依赖工具,用作数据的加解密辅助类

    6. **PKI组件**:Bouncy Castle还包含了证书和证书链的处理,支持X.509证书格式,可用于SSL/TLS协议,建立安全的网络连接。 7. **随机数生成器**:加密过程中需要使用高质量的随机数,Bouncy Castle提供了安全的...

    BouncyCastle.Crypto.dll 1.8.2

    《BouncyCastle.Crypto.dll 1.8.2:深入解析加密库的奥秘》 在信息技术领域,安全是至关重要的。特别是在网络通信、数据存储和传输等方面,强大的加密技术是保障信息安全的基础。BouncyCastle.Crypto.dll是这样一个...

    C# BouncyCastle实现带原文数据PKCS#7 签名、验签

    在C#编程环境中,虽然.NET框架提供了内置的安全类如RSACryptoServiceProvider,但在某些场景下,如与Java平台交互或者需要更灵活的加密库时,可能会选择第三方库,例如BouncyCastle。BouncyCastle是一个强大的开源...

    BouncyCastle.Crypto.dllC#下的BouncyCastle

    BouncyCastle是JAVA专属库,但出来了C#的库。这个非常实用。仅仅一个dll文件

    Bouncy Castle 1.64 API及制作工具

    **Bouncy Castle 1.64 API 深度解析** Bouncy Castle 是一个开源的 Java 安全库,提供了一整套加密算法、证书、SSL/TLS 协议以及 PKCS#7、PKCS#12、OpenSSL、CMS、S/MIME 和 X.509 的实现。在 1.64 版本中,这个库...

    bouncycastle集合包

    在这个集合包中,我们找到了四个不同版本的BouncyCastle相关jar文件,分别如下: 1. **bcprov-jdk16-1.46.jar**:这是BouncyCastle的主要提供者包,主要用于Java平台。"bcprov"代表BouncyCastle Provider,"jdk16...

    C# BouncyCastle实现带原文数据PKCS#7 签名

    本文将详细讲解如何使用C#语言和BouncyCastle库来实现带原文数据的PKCS#7签名。 PKCS#7(Public-Key Cryptography Standards #7)是由RSA Security提出的一种标准,它定义了证书、证书撤销列表(CRL)的格式以及...

    org.bouncycastle完整资源包

    《深入解析org.bouncycastle:Java安全加密与证书权威库》 在Java开发中,安全性是不可或缺的一部分,尤其是在处理敏感数据、网络通信以及数字签名时。`org.bouncycastle`库是一个强大的开源加密库,为Java开发者...

Global site tag (gtag.js) - Google Analytics