首页 | DV动态 | 数码产品 | 视频采编 | 网站建设 |
【收藏DV】
  最近3月排行
·赤马劫
·高中英语-单词表
·常用网管软件下载,持续更新中...
·品牌VIS设计以及CI、VI、VIS、UI、SI的含义
Java加密算法的实现实例细节分析讲解
2005/11/11 10:58:17
 

Java加密算法的实现实例细节分析讲解

第1章 基础知识

1.1、单钥密码体制

单钥密码体制是一种传统的加密算法,是指信息的发送方和接收方共同使用同一把密钥进行加解密。

通常,使用的加密算法比较简便高效,密钥简短,加解密速度快,破译极其困难。但是加密的安全性依靠密钥保管的安全性,在公开的计算机网络上安全地传送和保管密钥是一个严峻的问题,并且如果在多用户的情况下密钥的保管安全性也是一个问题。

单钥密码体制的代表是美国的DES

1.2、消息摘要

一个消息摘要就是一个数据块的数字指纹。即对一个任意长度的一个数据块进行计算,产生一个唯一指印(对于SHA1是产生一个20字节的二进制数组)。

消息摘要有两个基本属性:

两个不同的报文难以生成相同的摘要

难以对指定的摘要生成一个报文,而由该报文反推算出该指定的摘要

代表:美国国家标准技术研究所的SHA1和麻省理工学院Ronald Rivest提出的MD5

1.3、Diffie-Hellman密钥一致协议

密钥一致协议是由公开密钥密码体制的奠基人Diffie和Hellman所提出的一种思想。先决条件,允许两名用户在公开媒体上交换信息以生成"一致"的,可以共享的密钥

代表:指数密钥一致协议(Exponential Key Agreement Protocol)

1.4、非对称算法与公钥体系

1976年,Dittie和Hellman为解决密钥管理问题,在他们的奠基性的工作"密码学的新方向"一文中,提出一种密钥交换协议,允许在不安全的媒体上通过通讯双方交换信息,安全地传送秘密密钥。

在此新思想的基础上,很快出现了非对称密钥密码体制,即公钥密码体制。在公钥体制中,加密密钥不同于解密密钥,加密密钥公之于众,谁都可以使用;解密密钥只有解密人自己知道。它们分别称为公开密钥(Public key)和秘密密钥(Private key)。

迄今为止的所有公钥密码体系中,RSA系统是最著名、最多使用的一种。RSA公开密钥密码系统是由R.Rivest、A.Shamir和L.Adleman俊教授于1977年提出的。RSA的取名就是来自于这三位发明者的姓的第一个字母

1.5、数字签名

所谓数字签名就是信息发送者用其私钥对从所传报文中提取出的特征数据(或称数字指纹)进行RSA算法操作,以保证发信人无法抵赖曾发过该信息(即不可抵赖性),同时也确保信息报文在经签名后末被篡改(即完整性)。当信息接收者收到报文后,就可以用发送者的公钥对数字签名进行验证。 

在数字签名中有重要作用的数字指纹是通过一类特殊的散列函数(HASH函数)生成的,对这些HASH函数的特殊要求是:

接受的输入报文数据没有长度限制;

对任何输入报文数据生成固定长度的摘要(数字指纹)输出

从报文能方便地算出摘要;

难以对指定的摘要生成一个报文,而由该报文反推算出该指定的摘要;

两个不同的报文难以生成相同的摘要

代表:DSA
第2章 在Java中的实现

2.1、相关

Diffie-Hellman密钥一致协议和DES程序需要JCE工具库的支持,可以到

http://Java.sun.com/security/index.html 下载JCE,并进行安装。简易安装把

jce1.2.1\lib下的所有内容复制到%Java_home%\lib\ext下,如果没有ext目录自行建立

,再把jce1_2_1.jar和sunjce_provider.jar添加到CLASSPATH内。

2.2、消息摘要MD5和SHA的使用

使用方法:

首先用生成一个MessageDigest类,确定计算方法


Java.security.MessageDigest alga=Java.security.MessageDigest.getInstance("SHA-1");  

添加要进行计算摘要的信息

alga.update(myinfo.getBytes());


  

计算出摘要


byte[] digesta=alga.digest();



发送给其他人你的信息和摘要

其他人用相同的方法初始化,添加信息,最后进行比较摘要是否相同


algb.isEqual(digesta,algb.digest())

相关AIP

Java.security.MessageDigest 类

static getInstance(String algorithm)

返回一个MessageDigest对象,它实现指定的算法

参数:算法名,如 SHA-1 或MD5


void update (byte input)
  
void update (byte[] input)
  
void update(byte[] input, int offset, int len)

添加要进行计算摘要的信息


byte[] digest()
  

完成计算,返回计算得到的摘要(对于MD5是16位,SHA是20位)


void reset()


复位


static boolean isEqual
(byte[] digesta, byte[] digestb)


比效两个摘要是否相同

代码:













import Java.security.*;
  public class myDigest
{
  public static void
main(String[] args)
{
  
   myDigest my=new myDigest();
   my.testDigest();
  
  }
  public void testDigest()
  {
   try {
   String myinfo="我的测试信息";
  
   //Java.security.MessageDigest alg=
Java.security.MessageDigest.getInstance("MD5");
   Java.security.MessageDigest alga=
Java.security.MessageDigest.getInstance("SHA-1");
   alga.update(myinfo.getBytes());
   byte[] digesta=alga.digest();
   System.out.println
("本信息摘要是:"+byte2hex(digesta));
   //通过某中方式传给其他人你的信息
(myinfo)和摘要(digesta)
对方可以判断是否更改或传输正常
  Java.security.MessageDigest algb=
Java.security.MessageDigest.getInstance
("SHA-1");
   algb.update(myinfo.getBytes());
   if
(algb.isEqual(digesta,algb.digest()))
{
   System.out.println("信息检查正常");
   }
   else
   {
   System.out.println("摘要不相同");
   }
  
   }
   catch
(Java.security.NoSuchAlgorithmException ex)
{
   System.out.println("非法摘要算法");
   }
  
  }
  public String byte2hex(byte[] b)
//二行制转字符串
   {
   String hs="";
   String stmp="";
   for (int n=0;n  
{
   stmp=(Java.lang.Integer.toHexString
(b[n] & 0XFF));
   if (stmp.length()==1) hs=hs+"0"+stmp;
   else hs=hs+stmp;
   if (n   }
   return hs.toUpperCase();
   }
  
  }




2.3、数字签名DSA

对于一个用户来讲首先要生成他的密钥对,并且分别保存生成一个KeyPairGenerator实例:


Java.security.KeyPairGenerator keygen=
Java.security.KeyPairGenerator.getInstance("DSA");




如果设定随机产生器就用如相代码初始化


SecureRandom secrand=new SecureRandom();
   secrand.setSeed("tttt".getBytes());
//初始化随机产生器
   keygen.initialize(512,secrand);
//初始化密钥生成器




否则


keygen.initialize(512);




生成密钥公钥pubkey和私钥prikey


KeyPair keys=keygen.generateKeyPair();
//生成密钥组
   PublicKey pubkey=keys.getPublic();
   PrivateKey prikey=keys.getPrivate();




分别保存在myprikey.dat和mypubkey.dat中,以便下次不在生成


Java.io.ObjectOutputStream out=
new Java.io.ObjectOutputStream(new Java.io.FileOutputStream("myprikey.dat"));
   out.writeObject(prikey);
   out.close();
   out=new Java.io.ObjectOutputStream(new
Java.io.FileOutputStream("mypubkey.dat"));
   out.writeObject(pubkey);
   out.close();




用他私人密钥(prikey)对他所确认的信息(info)进行数字签名产生一个签名数组

从文件中读入私人密钥(prikey)


Java.io.ObjectInputStream in=
new Java.io.ObjectInputStream(new
Java.io.FileInputStream("myprikey.dat"));
PrivateKey myprikey=
(PrivateKey)in.readObject();
in.close();




初始一个Signature对象,并用私钥对信息签名


Java.security.Signature
signet=Java.security.Signature.getInstance("DSA");
   signet.initSign(myprikey);
   signet.update(myinfo.getBytes());
   byte[] signed=signet.sign();




把信息和签名保存在一个文件中(myinfo.dat)


Java.io.ObjectOutputStream out=
new Java.io.ObjectOutputStream(new
Java.io.FileOutputStream("myinfo.dat"));
   out.writeObject(myinfo);
   out.writeObject(signed);
   out.close();

把他的公钥的信息及签名发给其它用户

其他用户用他的公共密钥(pubkey)和签名(signed)和信息(info)进行验证是否由他签名的信息

读入公钥










Java.io.ObjectInputStream in=
new Java.io.ObjectInputStream(new
Java.io.FileInputStream("mypubkey.dat"));
PublicKey pubkey=
(PublicKey)in.readObject();
  in.close();




读入签名和信息


in=new Java.io.ObjectInputStream(new
Java.io.FileInputStream("myinfo.dat"));
  String info=(String)in.readObject();
  byte[] signed=(byte[])in.readObject();
  in.close();




初始一个Signature对象,并用公钥和签名进行验证:


signetcheck=Java.security.
Signature.getInstance("DSA");
  signetcheck.initVerify(pubkey);
  signetcheck.update(info.getBytes());
  
  if (signetcheck.verify(signed))
{
System.out.println("签名正常");
}




对于密钥的保存本文是用对象流的方式保存和传送的,也可可以用编码的方式保存.注意要


import Java.security.spec.*
import Java.security.*




具休说明如下:

public key是用X.509编码的,例码如下:


byte[]
bobEncodedPubKey=mypublic.getEncoded();
//生成编码
   //传送二进制编码
   //以下代码转换编码为相应key对象
   X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
   KeyFactory keyFactory =
KeyFactory.getInstance("DSA");
   PublicKey bobPubKey =
keyFactory.generatePublic(bobPubKeySpec);




对于Private key是用PKCS#8编码,例码如下:


byte[] bPKCS=myprikey.getEncoded();
  //传送二进制编码
  //以下代码转换编码为相应key对象
  PKCS8EncodedKeySpec priPKCS8=
new PKCS8EncodedKeySpec(bPKCS);
  KeyFactory keyf=
KeyFactory.getInstance("DSA");
  PrivateKey otherprikey=
keyf.generatePrivate(priPKCS8);




常用API

Java.security.KeyPairGenerator 密钥生成器类


public static KeyPairGenerator
getInstance(String algorithm)
throws NoSuchAlgorithmException




以指定的算法返回一个KeyPairGenerator 对象

参数: algorithm 算法名.如:"DSA","RSA"


public void initialize(int keysize)

.4、DESede/DES对称算法

首先生成密钥,并保存(这里并没的保存的代码,可参考DSA中的方法)














KeyGenerator keygen =
KeyGenerator.getInstance(Algorithm);
SecretKey deskey =
keygen.generateKey();


  

用密钥加密明文(myinfo),生成密文(cipherByte)


Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=
c1.doFinal(myinfo.getBytes());


  

传送密文和密钥

用密钥解密密文


c1 = Cipher.getInstance(Algorithm);
  
c1.init(Cipher.DECRYPT_MODE,deskey);
  
byte[] clearByte=c1.doFinal(cipherByte);


  

相对来说对称密钥的使用是很简单的,对于JCE来讲支技DES,DESede,Blowfish三种加密术,对于密钥的保存各传送可使用对象流或者用二进制编码,相关参考代码如下:


SecretKey deskey =
keygen.generateKey();
   byte[] desEncode=
deskey.getEncoded();
   Javax.crypto.spec.SecretKeySpec
destmp=new Javax.crypto.spec.
SecretKeySpec(desEncode,Algorithm);
   SecretKey mydeskey=destmp;




相关API

KeyGenerator 在DSA中已经说明,在添加JCE后在instance进可以如下参数:


DES,DESede,Blowfish,HmacMD5,HmacSHA1
Javax.crypto.Cipher
加/解密器
public static final Cipher
getInstance
(Java.lang.String transFORMation)
   throws Java.security.
NoSuchAlgorithmException,
   NoSuchPaddingException




返回一个指定方法的Cipher对象

参数:transFORMation 方法名(可用 DES,DESede,Blowfish)


public final void init(int opmode,
Java.security.Key key)
throws Java.security.InvalidKeyException


  

用指定的密钥和模式初始化Cipher对象

参数:opmode 方式(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)

key 密钥


public final byte[] doFinal(byte[] input)
   throws Java.lang.IllegalStateException,
   IllegalBlockSizeException,
   BadPaddingException


  

对input内的串,进行编码处理,返回处理后二进制串,是返回解密文还是加解文由init时的opmode决定。

注意:本方法的执行前如果有update,是对updat和本次input全部处理,否则是本inout的内容


/*
  安全程序 DESede/DES测试
  */
  import Java.security.*;
  import Javax.crypto.*;
  public class testdes
{
  public static void
main(String[] args)
{
   testdes my=new testdes();
   my.run();
  }
  public void run()
{
  //添加新安全算法,
如果用JCE就要把它添加进去
  Security.addProvider
(new com.sun.crypto.provider.SunJCE());
  String Algorithm="DES";
//定义 加密算法,可用 DES,DESede,Blowfish
  String myinfo="要加密的信息";
   try {
   //生成密钥
   KeyGenerator keygen =
KeyGenerator.getInstance(Algorithm);
   SecretKey deskey =
keygen.generateKey();
  
   //加密
   System.out.println
("加密前的二进串:"+
byte2hex(myinfo.getBytes()));
   System.out.println
("加密前的信息:"+myinfo);
   Cipher c1 =
Cipher.getInstance(Algorithm);
   c1.init(Cipher.ENCRYPT_MODE,deskey);
 byte[] cipherByte=
c1.doFinal(myinfo.getBytes());
   System.out.println
("加密后的二进串:"+
byte2hex(cipherByte));
  //解密
   c1 = Cipher.getInstance(Algorithm);
   c1.init(Cipher.DECRYPT_MODE,deskey);
   byte[] clearByte=c1.doFinal(cipherByte);
   System.out.println
("解密后的二进串:"+byte2hex(clearByte));
   System.out.println
("解密后的信息:"+(new String(clearByte)));
  
  }
   catch (Java.security.
NoSuchAlgorithmException e1)
{e1.printStackTrace();}
   catch (Javax.crypto.
NoSuchPaddingException e2)
{e2.printStackTrace();}
   catch (Java.lang.Exception e3)
{e3.printStackTrace();}
  }
  public String byte2hex(byte[] b)
//二行制转字符串
   {
   String hs="";
   String stmp="";
   for (int n=0;n  
{
   stmp=
(Java.lang.Integer.toHexString
(b[n] & 0XFF));
   if (stmp.length()==1)
hs=hs+"0"+stmp;
   else hs=hs+stmp;
   if (n   }
   return hs.toUpperCase();
   }
  
  }


.4、DESede/DES对称算法

首先生成密钥,并保存(这里并没的保存的代码,可参考DSA中的方法)














KeyGenerator keygen =
KeyGenerator.getInstance(Algorithm);
SecretKey deskey =
keygen.generateKey();


  

用密钥加密明文(myinfo),生成密文(cipherByte)


Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=
c1.doFinal(myinfo.getBytes());


  

传送密文和密钥

用密钥解密密文


c1 = Cipher.getInstance(Algorithm);
  
c1.init(Cipher.DECRYPT_MODE,deskey);
  
byte[] clearByte=c1.doFinal(cipherByte);


  

相对来说对称密钥的使用是很简单的,对于JCE来讲支技DES,DESede,Blowfish三种加密术,对于密钥的保存各传送可使用对象流或者用二进制编码,相关参考代码如下:


SecretKey deskey =
keygen.generateKey();
   byte[] desEncode=
deskey.getEncoded();
   Javax.crypto.spec.SecretKeySpec
destmp=new Javax.crypto.spec.
SecretKeySpec(desEncode,Algorithm);
   SecretKey mydeskey=destmp;




相关API

KeyGenerator 在DSA中已经说明,在添加JCE后在instance进可以如下参数:


DES,DESede,Blowfish,HmacMD5,HmacSHA1
Javax.crypto.Cipher
加/解密器
public static final Cipher
getInstance
(Java.lang.String transFORMation)
   throws Java.security.
NoSuchAlgorithmException,
   NoSuchPaddingException




返回一个指定方法的Cipher对象

参数:transFORMation 方法名(可用 DES,DESede,Blowfish)


public final void init(int opmode,
Java.security.Key key)
throws Java.security.InvalidKeyException


  

用指定的密钥和模式初始化Cipher对象

参数:opmode 方式(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)

key 密钥


public final byte[] doFinal(byte[] input)
   throws Java.lang.IllegalStateException,
   IllegalBlockSizeException,
   BadPaddingException


  

对input内的串,进行编码处理,返回处理后二进制串,是返回解密文还是加解文由init时的opmode决定。

注意:本方法的执行前如果有update,是对updat和本次input全部处理,否则是本inout的内容


/*
  安全程序 DESede/DES测试
  */
  import Java.security.*;
  import Javax.crypto.*;
  public class testdes
{
  public static void
main(String[] args)
{
   testdes my=new testdes();
   my.run();
  }
  public void run()
{
  //添加新安全算法,
如果用JCE就要把它添加进去
  Security.addProvider
(new com.sun.crypto.provider.SunJCE());
  String Algorithm="DES";
//定义 加密算法,可用 DES,DESede,Blowfish
  String myinfo="要加密的信息";
   try {
   //生成密钥
   KeyGenerator keygen =
KeyGenerator.getInstance(Algorithm);
   SecretKey deskey =
keygen.generateKey();
  
   //加密
   System.out.println
("加密前的二进串:"+
byte2hex(myinfo.getBytes()));
   System.out.println
("加密前的信息:"+myinfo);
   Cipher c1 =
Cipher.getInstance(Algorithm);
   c1.init(Cipher.ENCRYPT_MODE,deskey);
 byte[] cipherByte=
c1.doFinal(myinfo.getBytes());
   System.out.println
("加密后的二进串:"+
byte2hex(cipherByte));
  //解密
   c1 = Cipher.getInstance(Algorithm);
   c1.init(Cipher.DECRYPT_MODE,deskey);
   byte[] clearByte=c1.doFinal(cipherByte);
   System.out.println
("解密后的二进串:"+byte2hex(clearByte));
   System.out.println
("解密后的信息:"+(new String(clearByte)));
  
  }
   catch (Java.security.
NoSuchAlgorithmException e1)
{e1.printStackTrace();}
   catch (Javax.crypto.
NoSuchPaddingException e2)
{e2.printStackTrace();}
   catch (Java.lang.Exception e3)
{e3.printStackTrace();}
  }
  public String byte2hex(byte[] b)
//二行制转字符串
   {
   String hs="";
   String stmp="";
   for (int n=0;n  
{
   stmp=
(Java.lang.Integer.toHexString
(b[n] & 0XFF));
   if (stmp.length()==1)
hs=hs+"0"+stmp;
   else hs=hs+stmp;
   if (n   }
   return hs.toUpperCase();
   }
  
  }


2.5、Diffie-Hellman密钥一致协议

公开密钥密码体制的奠基人Diffie和Hellman所提出的"指数密钥一致协议"(Exponential Key Agreement Protocol),该协议不要求别的安全性为先决条件,允许两名用户在公开媒体上交换信息以生成"一致"的,可以共享的密钥。

在JCE的中实现用户alice生成DH类型的密钥对,如果长度用1024生成的时间请,推荐第一次生成后保存DHParameterSpec,以便下次使用直接初始化.使其速度加快。










System.out.println("ALICE: 产生 DH 对 ...");
  KeyPairGenerator aliceKpairGen
= KeyPairGenerator.getInstance("DH");
  aliceKpairGen.initialize(512);
  KeyPair aliceKpair
= aliceKpairGen.generateKeyPair();


  

alice生成公钥发送组bob byte[] alicePubKeyEnc =

aliceKpair.getPublic().getEncoded();

bob从alice发送来的公钥中读出DH密钥对的初始参数生成bob的DH密钥对,注意这一步一定要做,要保证每个用户用相同的初始参数生成的:


DHParameterSpec dhParamSpec =
((DHPublicKey)alicePubKey).getParams();
   KeyPairGenerator bobKpairGen =
KeyPairGenerator.getInstance("DH");
   bobKpairGen.initialize(dhParamSpec);
   KeyPair bobKpair =
bobKpairGen.generateKeyPair();




bob根据alice的公钥生成本地的DES密钥:


KeyAgreement bobKeyAgree =
KeyAgreement.getInstance("DH");
   bobKeyAgree.init
(bobKpair.getPrivate());
   bobKeyAgree.doPhase
(alicePubKey, true);
   SecretKey bobDesKey
= bobKeyAgree.generateSecret("DES");




bob已经生成了他的DES密钥,他现把他的公钥发给alice:


byte[] bobPubKeyEnc =
bobKpair.getPublic().getEncoded();




alice根据bob的公钥生成本地的DES密钥


KeyAgreement aliceKeyAgree =
KeyAgreement.getInstance("DH");
   aliceKeyAgree.init
(aliceKpair.getPrivate());
   aliceKeyAgree.doPhase
(bobPubKey, true);
   SecretKey aliceDesKey =
aliceKeyAgree.generateSecret("DES");




bob和alice能过这个过程就生成了相同的DES密钥。

常用API

Java.security.KeyPairGenerator 密钥生成器类

public static KeyPairGenerator getInstance(String algorithm)

throws NoSuchAlgorithmException

以指定的算法返回一个KeyPairGenerator 对象

参数: algorithm 算法名.如:原来是DSA,现在添加了 DiffieHellman(DH)

public void initialize(int keysize)

以指定的长度初始化KeyPairGenerator对象,如果没有初始化系统以1024长度默认设置

参数:keysize 算法位长.其范围必须在 512 到 1024 之间,且必须为 64 的倍数

注意:如果用1024生长的时间很长,最好生成一次后就保存,下次就不用生成了


public void initialize
(AlgorithmParameterSpec params)
  throws InvalidAlgorithmParameterException
  以指定参数初始化
  
  Javax.crypto.interfaces.DHPublicKey
  public DHParameterSpec getParams()
  返回
  Java.security.KeyFactory
  
  public static KeyFactory
getInstance(String algorithm)
  
  throws NoSuchAlgorithmException
  以指定的算法返回一个KeyFactory
  参数: algorithm 算法名:DSH,DH
  
  public final PublicKey
generatePublic(KeySpec keySpec)
  throws InvalidKeySpecException
  根据指定的key说明,
返回一个PublicKey对象
  
  Java.security.spec.X509EncodedKeySpec
  public X509EncodedKeySpec(byte[] encodedKey)
  根据指定的二进制编码的字串生成一个key的说明
  参数:encodedKey 二进制编码的字串
(一般能过PublicKey.getEncoded()生成)
  Javax.crypto.KeyAgreement
密码一至类
  
  public static final KeyAgreement
getInstance(Java.lang.String algorithm)
  throws Java.security.NoSuchAlgorithmException
  返回一个指定算法的KeyAgreement对象
  参数:algorithm 算法名,现在只能是DiffieHellman(DH)
  
  public final void init(Java.security.Key key)
  throws Java.security.InvalidKeyException
  用指定的私钥初始化
  参数:key 一个私钥
  
  public final Java.security.Key
doPhase(Java.security.Key key,
  boolean lastPhase)
  throws Java.security.InvalidKeyException,
  Java.lang.IllegalStateException
  用指定的公钥进行定位,lastPhase确定这是否是最后一个公钥,
对于两个用户的
  情况下就可以多次定次,最后确定
  参数:key 公钥
  lastPhase 是否最后公钥
  
  public final SecretKey
generateSecret(Java.lang.String algorithm)
  throws Java.lang.IllegalStateException,
  Java.security.NoSuchAlgorithmException,
  Java.security.InvalidKeyException
  根据指定的算法生成密钥
  参数:algorithm 加密算法(可用 DES,DESede,Blowfish)
  
  
  */
  import Java.io.*;
  import Java.math.BigInteger;
  import Java.security.*;
  import Java.security.spec.*;
  import Java.security.interfaces.*;
  import Javax.crypto.*;
  import Javax.crypto.spec.*;
  import Javax.crypto.interfaces.*;
  import com.sun.crypto.provider.SunJCE;
  
  public class testDHKey
{
  
  
   public static void main(String argv[])
{
   try {
   testDHKey my= new testDHKey();
   my.run();
   } catch (Exception e)
{
   System.err.println(e);
  
   }
   }
  
   private void run() throws Exception
{
   Security.addProvider
(new com.sun.crypto.provider.SunJCE());
  
   System.out.println("ALICE: 产生 DH 对 ...");
   KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance("DH");
   aliceKpairGen.initialize(512);
   KeyPair aliceKpair =
aliceKpairGen.generateKeyPair();
//生成时间长
  
   // 张三(Alice)生成公共密钥
alicePubKeyEnc 并发送给李四(Bob) ,
   //比如用文件方式,socket.....
   byte[] alicePubKeyEnc =
aliceKpair.getPublic().getEncoded();
  
   //bob接收到alice的编码后的公钥,
将其解码
   KeyFactory bobKeyFac =
KeyFactory.getInstance("DH");
   X509EncodedKeySpec x509KeySpec =
new X509EncodedKeySpec
(alicePubKeyEnc);
   PublicKey alicePubKey =
bobKeyFac.generatePublic(x509KeySpec);
   System.out.println
("alice公钥bob解码成功");
   // bob必须用相同的参数初始化的他的DH KEY对,所以要从Alice发给他的公开密钥,
   //中读出参数,再用这个参数初始化他的 DH key对
  
   //从alicePubKye中取alice初始化时用的参数
   DHParameterSpec dhParamSpec = ((DHPublicKey)alicePubKey).getParams();
   KeyPairGenerator bobKpairGen =
KeyPairGenerator.getInstance("DH");
   bobKpairGen.initialize(dhParamSpec);
   KeyPair bobKpair =
bobKpairGen.generateKeyPair();
   System.out.println
("BOB: 生成 DH key 对成功");
   KeyAgreement bobKeyAgree =
KeyAgreement.getInstance("DH");
   bobKeyAgree.init
(bobKpair.getPrivate());
  
  System.out.println
("BOB: 初始化本地key成功");
   //李四(bob) 生成本地的密钥 bobDesKey
   bobKeyAgree.doPhase
(alicePubKey, true);
   SecretKey bobDesKey =
bobKeyAgree.generateSecret("DES");
   System.out.println("BOB:
用alice的公钥定位本地key,
生成本地DES密钥成功");
   // Bob生成公共密钥
bobPubKeyEnc 并发送给Alice,
   //比如用文件方式,socket.....,
使其生成本地密钥
   byte[] bobPubKeyEnc =
bobKpair.getPublic().getEncoded();
   System.out.println
("BOB向ALICE发送公钥");
  
   // alice接收到
bobPubKeyEnc后生成bobPubKey
   // 再进行定位,
使aliceKeyAgree定位在bobPubKey
   KeyFactory aliceKeyFac =
KeyFactory.getInstance("DH");
   x509KeySpec =
new X509EncodedKeySpec(bobPubKeyEnc);
   PublicKey bobPubKey =
aliceKeyFac.generatePublic(x509KeySpec);
   System.out.println
("ALICE接收BOB公钥并解码成功");
  ;
   KeyAgreement aliceKeyAgree =
KeyAgreement.getInstance("DH");
   aliceKeyAgree.init
(aliceKpair.getPrivate());
   System.out.println
("ALICE: 初始化本地key成功");
  
   aliceKeyAgree.doPhase(bobPubKey, true);
   // 张三(alice)
生成本地的密钥 aliceDesKey
   SecretKey aliceDesKey =
aliceKeyAgree.generateSecret("DES");
   System.out.println("ALICE:
用bob的公钥定位本地key,
并生成本地DES密钥");
  
   if (aliceDesKey.equals(bobDesKey))
System.out.println("张三和李四的密钥相同");
   //现在张三和李四的本地的deskey是相同的所以,
完全可以进行发送加密,接收后解密,达到
   //安全通道的的目的
  
   /*
   * bob用bobDesKey密钥加密信息
   */
   Cipher bobCipher =
Cipher.getInstance("DES");
   bobCipher.init
(Cipher.ENCRYPT_MODE, bobDesKey);
   String bobinfo=
"这是李四的机密信息";
   System.out.println
("李四加密前原文:"+bobinfo);
   byte[] cleartext =
bobinfo.getBytes();
   byte[] ciphertext =
bobCipher.doFinal(cleartext);
  
   /*
   * alice用aliceDesKey密钥解密
   */
   Cipher aliceCipher =
Cipher.getInstance("DES");
   aliceCipher.init
(Cipher.DECRYPT_MODE, aliceDesKey);
   byte[] recovered =
aliceCipher.doFinal(ciphertext);
   System.out.println
("alice解密bob的信息:"+(new String(recovered)));
   if (!Java.util.Arrays.equals
(cleartext, recovered))
   throw new Exception
("解密后与原文信息不同");
   System.out.println
("解密后相同");
  
   }
  
  }


  

第3章 小结

在加密术中生成密钥对时,密钥对的当然是越长越好,但费时也越多,请从中从实际出发选取合适的长度,大部分例码中的密钥是每次运行就从新生成,在实际的情况中是生成后在一段时间保存在文件中,再次运行直接从文件中读入,从而加快速度。当然定时更新和加强密钥保管的安全性也是必须的。

(DVOL本文转自:中国DV传媒 http://www.dvol.cn)

欢迎关注微信公众账号:手机烟台(mYantai)

 

  上一篇:Asp程序错误详细说明例表
  下一篇:几个不太常用的HTML Tag (精华)
      更多...
::打印本页 ::      ::关闭窗口::


版权所有© 数码在线网站 DV OnLine©  鲁ICP备12016322号-1