-------------åèä¸------------------
JAVAå å¯ç®æ³çå®ç°ç¨ä¾
对象
åæ° algorithm å¦:"DSA"
public final void initSign(PrivateKey privateKey)
throws InvalidKeyException
ç¨æå®çç§é¥åå§å
åæ°:privateKey æè¿è¡ç¾åæ¶ç¨çç§é¥
public final void update(byte data)
throws SignatureException
public final void update(byte[] data)
throws SignatureException
public final void update(byte[] data, int off, int len)
throws SignatureException
æ·»å è¦ç¾åçä¿¡æ¯
public final byte[] sign()
throws SignatureException
è¿åç¾åçæ°ç»,åææ¯initSignåupdate
public final void initVerify(PublicKey publicKey)
throws InvalidKeyException
ç¨æå®çå
¬é¥åå§å
åæ°:publicKey éªè¯æ¶ç¨çå
¬é¥
public final boolean verify(byte[] signature)
throws SignatureException
éªè¯ç¾åæ¯å¦ææ,åææ¯å·²ç»initVerifyåå§å
åæ°: signature ç¾åæ°ç»
*/
import java.security.*;
import java.security.spec.*;
public class testdsa {
public static void main(String[] args) throws java.security.NoSuchAlgorithmException,java.lang.Exception {
testdsa my=new testdsa();
my.run();
}
public void run()
{
//æ°åç¾åçæå¯é¥
//第ä¸æ¥çæå¯é¥å¯¹,å¦æå·²ç»çæè¿,æ¬è¿ç¨å°±å¯ä»¥è·³è¿,对ç¨æ·æ¥è®²myprikey.datè¦ä¿åå¨æ¬å°
//èmypubkey.datç»åå¸ç»å
¶å®ç¨æ·
if ((new java.io.File("myprikey.dat")).exists()==false) {
if (generatekey()==false) {
System.out.println("çæå¯é¥å¯¹è´¥");
return;
};
}
//第äºæ¥,æ¤ç¨æ·
//ä»æ件ä¸è¯»å
¥ç§é¥,对ä¸ä¸ªå符串è¿è¡ç¾ååä¿åå¨ä¸ä¸ªæ件(myinfo.dat)ä¸
//并ä¸åæmyinfo.datåéåºå»
//为äºæ¹ä¾¿æ°åç¾åä¹æ¾è¿äºmyifno.datæ件ä¸,å½ç¶ä¹å¯åå«åé
try {
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream("myprikey.dat"));
PrivateKey myprikey=(PrivateKey)in.readObject();
in.close();
// java.security.spec.X509EncodedKeySpec pubX509=new java.security.spec.X509EncodedKeySpec(bX509);
//java.security.spec.X509EncodedKeySpec pubkeyEncode=java.security.spec.X509EncodedKeySpec
String myinfo="è¿æ¯æçä¿¡æ¯"; //è¦ç¾åçä¿¡æ¯
//ç¨ç§é¥å¯¹ä¿¡æ¯çææ°åç¾å
java.security.Signature signet=java.security.Signature.getInstance("DSA");
signet.initSign(myprikey);
signet.update(myinfo.getBytes());
byte[] signed=signet.sign(); //对信æ¯çæ°åç¾å
System.out.println ("signed(ç¾åå
容)="+byte2hex(signed));
//æä¿¡æ¯åæ°åç¾åä¿åå¨ä¸ä¸ªæ件ä¸
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream("myinfo.dat"));
out.writeObject(myinfo);
out.writeObject(signed);
out.close();
System.out.println("ç¾å并çææ件æå");
}
catch (java.lang.Exception e) {
e.printStackTrace();
System.out.println("ç¾å并çææ件失败");
};
//第ä¸æ¥
//å
¶ä»äººéè¿å
Œ
±æ¹å¼å¾å°æ¤æ·çå
¬é¥åæ件
//å
¶ä»äººç¨æ¤æ·çå
¬é¥,对æ件è¿è¡æ£æ¥,å¦ææå说ææ¯æ¤ç¨æ·åå¸çä¿¡æ¯.
//
try {
java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream("mypubkey.dat"));
PublicKey pubkey=(PublicKey)in.readObject();
in.close();
System.out.println(pubkey.getFormat());
in=new java.io.ObjectInputStream(new java.io.FileInputStream("myinfo.dat"));
String info=(String)in.readObject();
byte[] signed=(byte[])in.readObject();
in.close();
java.security.Signature signetcheck=java.security.Signature.getInstance("DSA");
signetcheck.initVerify(pubkey);
signetcheck.update (info.getBytes());
if (signetcheck.verify(signed)) {
System.out.println("info="+info);
System.out.println("ç¾åæ£å¸¸");
}
else System.out.println("éç¾åæ£å¸¸");
}
catch ( java.lang.Exception e) {e.printStackTrace();};
}
//çæä¸å¯¹æ件myprikey.datåmypubkey.dat---ç§é¥åå
¬é¥,
//å
¬é¥è¦ç¨æ·åé(æ件,ç½ç»çæ¹æ³)ç»å
¶å®ç¨æ·,ç§é¥ä¿åå¨æ¬å°
public boolean generatekey()
{
try {
java.security.KeyPairGenerator keygen=java.security.KeyPairGenerator.getInstance("DSA");
// SecureRandom secrand=new SecureRandom();
// secrand.setSeed("tttt".getBytes()); //åå§åéæºäº§çå¨
// keygen.initialize(576,secrand); //åå§åå¯é¥çæå¨
keygen.initialize(512);
KeyPair keys=keygen.genKeyPair();
// KeyPair keys=keygen.generateKeyPair(); //çæå¯é¥ç»
PublicKey pubkey=keys.getPublic();
PrivateKey prikey=keys.getPrivate();
java.io.ObjectOutputStream out=new java.io.ObjectOutputStream(new java.io.FileOutputStream("myprikey.dat"));
out.writeObject(prikey);
out.close();
System.out.println("åå
¥å¯¹è±¡ prikeys ok");
out=new java.io.ObjectOutputStream (new java.io.FileOutputStream("mypubkey.dat"));
out.writeObject(pubkey);
out.close();
System.out.println("åå
¥å¯¹è±¡ pubkeys ok");
System.out.println("çæå¯é¥å¯¹æå");
return true;
}
catch (java.lang.Exception e) {
e.printStackTrace();
System.out.println("çæå¯é¥å¯¹å¤±è´¥");
return false;
};
}
public String byte2hex(byte[] b)
{
String hs="";
String stmp="";
for (int n=0;n<b.length;n++)
{
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+":";
}
return hs.toUpperCase();
}
}
2.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());
ä¼ éå¯æåå¯é¥,æ¬æ没æç¸åºä»£ç å¯åèDSA
.............
ç¨å¯é¥è§£å¯å¯æ
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<b.length;n++)
{
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (n<b.length-1 ) hs=hs+":";
}
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("解å¯åç¸å");
}
}
åèèµæï¼http://liyanboss.javaeye.com/?page=3&show_full=true