MD5 / SHA1, DSA, DESEDE / DES, DIFFIE-HELLMAN
Wang Hui (ddxxkk@21cn.com) July 2001
Chapter 1 Basic Knowledge
1.1. Monolithic code system The single key cryptosystem is a traditional encryption algorithm that refers to the sender of the information and the receiver to decrypt the same key to use the same key.
Typically, the encryption algorithm used is simple and efficient, the key is short, the reinprint is fast, and the decipherment is extremely difficult. However, the encrypted security relies on the security of the key storage, which is safely transmitted and kept on the disclosed computer network is a severe problem, and if the keys for keys for the keys are also a problem if the keys in the case of multiple users.
The representative of the single key cryptograph is DES in the United States.
1.2. Message Abstract A message summary is a digital fingerprint for a data block. That is, a block of any length is calculated, generating a unique finger (for SHA1 is a 20-byte binary array).
There are two basic properties:
Two different messages are difficult to generate the same summary to generate a message for the specified summary, and the packet is counterproductive to the designated summary representative: the US National Standard Technology Research Institute of SHA1 and Massachi Institute of Technology Ronald Radest MD5 proposed
1.3. Diffie-Hellman key consistent protocol key consistent protocol is a kind of thought of the founder Diffie and Hellman of the public key cryptography.
Prerequisites, allow two users to exchange information on public media to generate "consistent", can share keys
Representative: Index Key Consistent Protocol (Exponential Key Agreement Protocol)
1.4. Asymmetric algorithm and public key system In 1976, DITTIE and Hellman proposed a key exchange protocol in their text, in their text, in the text of their laid-based work "New Direction", allowed Secure media exchange information by communication, securely transmitting the secret key. On the basis of this new idea, an asymmetric key cryptographic system, that is, public key cryptosystem. In the public key system, the encryption key is different from the decryption key, the encrypted key is only the public, no one can use; the decryption key only has the decryption person. They are called public keys and a private key.
In all public key cryptographic systems so far, the RSA system is the most famous and most use. The RSA public key cryptographic system is proposed by R.Rivest, A.Shamir and L.Adleman Jun Professor in 1977. The name of RSA is the first letter from the three inventors of the inventor.
1.5. Digital Signature The so-called digital signature is that the information sender performs RSA algorithm operation from the feature data (or digital fingerprint) extracted from the transmitted message to ensure that the sender cannot rely on the information ( That is, it is not worthless), and it is also ensured that the information packet is tampered with (ie, completeness) after the signature. When the information recipient receives the message, you can verify the digital signature with the sender's public key.
The digital fingerprints in digital signatures are generated by a special hash function (haveh function), and the special requirements for these haveh functions are:
Accepted input message data has no length limit; a summary (digital fingerprint) output for any input message data is generated (digital fingerprint) output from packets can easily calculate a summary; it is difficult to generate a message to the specified summary, but by the message Inverted the specified summary; two different messages are difficult to generate the same summary
Representative: DSA
Chapter 2 Realization in Java
2.1. Related Diffie-Hellman key consistent protocols and DES programs require support for the JCE tool library, you can download JCE to http://java.sun.com/security/index.html and install. Simple installation copies all the content under jAVA_HOME / lib / ext of JCE1.2.1 / lib, if there is no EXT directory to establish it, add JCE1_2_1.jar and SunJCE_Provider.jar to classpath, more detailed description, please see User Manual 2.2. Message Summary MD5 and SHA usage method:
First, use a MessageDigest class to determine how calculation methods
Java.security.MessageDigest alga = java.security.MessageDigest.GetInstance ("SHA-1");
Add information to make calculation summary
Alga.Update (Myinfo.getBytes ());
Summary
Byte [] Digesta = alga.digest ();
Send to others your information and summary
Others initialize, add information, and finally perform the same sum.
Algb.isequal (Digesta, Algb.digest ())
Related AIP
Java.security.MessageDigest class
Static GetInstance (String Algorithm)
Returns a MessageDigest object that implements the specified algorithm
Parameters: algorithm name, such as SHA-1 or MD5
Void Update (Byte Input)
Void update (byte [] input)
Void update (byte [] Input, int offset, int LEN
Add information to make calculation summary
Byte [] Digest ()
Complete the calculation, return to the calculated summary (16 digits for MD5, SHA is 20)
Void reset ()
Reset
Static Boolean ISEqual (byte [] Digesta, Byte [] Digestb)
Did the different summary
Code:
Import java.security. *;
Public class mydigest {
Public static void main (String [] args) {
MYDIGEST my = new mydigest ();
my.testDigest ();
}
Public void testdigest ()
{
Try {
String myinfo = "My Test Information";
//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 ("This summary is:" Byte2Hex (Digesta));
// Pass in a middle method to other people (MyInfo) and summary (Digesta) each other can determine if the change or transmission is normal
Java.security.MessageSt algb = java.security.MessageDigest.getInstance ("SHA-1");
Algb.Update (Myinfo.getBytes ());
IF (algb.isequal (digesta, algb.digest ())) {
System.out.println ("Information Check Normal");
}
Else
{
System.out.println ("Summary is not the same");
}
}
Catch (java.security.nosuchalgorithmexception ex) {
System.out.println ("illegal abstract algorithm");
}
}
Public string byte2hex (byte [] b) // binary stream string
{
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. Digital signature DSA For a user to first generate his key pair, and save a keypairgenerator instance separately Java.security.keypairgenerator keygen = java.security.keypairgenerator.getInstance ("DSA"); If the set random generator is initialized with the phase code Securerandom secrand = new securerandom (); SECRAND.SETSEED ("TTTT" .GetBytes ()); // Initialize the random generator Keygen.Initialize (512, secrand); // Initialization key generator otherwise Keygen.initialize (512); Generate key public key Pubkey and private key Prikey Keypair Keys = keygen.generateKeyPair (); // Generate a key group Publickey Pubkey = Keys.getPublic (); PrivateKey PriKey = keys.getprivate (); Save in MyPrikey.dat and MyPubkey.dat, so that you will not be generated next time. (Generating key pairs longer 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 (); Use his private key (PRIKEY) to perform digital signature to generate a signature array read from the file to private key (PriKey) Java.io.objectInputStream in = new java.io.ObjectInputStream (New java.io.fileinputStream ("MyPrikey.dat"); PrivateKey myprikey = (privatekey) in.readObject (); In.Close (); Initial Signature object, and sign the information with the private key Java.security.signature signet = java.security.signature.getInstance ("DSA"); signet.initsign (MyPrikey); Signet.Update (MyInfo.getBytes ()); BYTE [] SIGNED = Signet.sign (); Save information and signatures in a file (MyInfo.dat) Java.io.objectOutputStream out = new java.io.ObjectOutputStream (New java.io.fileoutputstream ("MyInfo.dat")); Out.writeObject (MyInfo); Out.writeObject (Signed); Out.close (); Send the information and signatures of his public key to other users Other users verify if the public key and signature (Signed) and information (INFO) are read into the public key java.io.ObjectInputStream in = new java.io.ObjectInputStream (New Java). IO.FileinputStream ("MyPubkey.dat")); publickey Pubkey = (publickey) in.readObject (); in.close (); Read Signature and Information in = New Java.io.ObjectInputStream (New Java.io.fileInputStream ("MyInfo.dat"); string info = (string) in.readObject (); byte [] signed = (byte []) in.readObject (); in .close (); initial one signature object, and public key and signature verification java.security.Signature signetcheck = java.security.Signature.getInstance ( "DSA"); signetcheck.initVerify (pubkey); signetcheck.update (info.getBytes ()); if (signetcheck.verify (signed )) {System.out.println ("Signature Normal");} Save the key for the key is saved and transferred in the way with object flow, or can be saved in the encoded manner. Note To Import Java.security.SPEC * Import java.security. * Remove the following Public key is encoded with X.509, with an example code as follows: Byte [] BobencodedPubkey = mypublic.getencoded (); // Generate Coding // Transfer binary encoding // The following code conversion is encoded as the corresponding KEY object X509EncodedKeyspec BobPubkeyspec = New X509EncodedKeyspec (BobencodedPubkey); KeyFactory KeyFactory = KeyFactory.GetInstance ("DSA"); Publickey Bobpubkey = KeyFactory.Generatepublic (Bobpubkeyspec); For Private Key, use PKCS # 8 encoding, with an example code as follows: Byte [] bpkcs = myprikey.getencoded (); // Transfer binary encoding // The following code conversion is encoded as the corresponding KEY object PKCS8ENCODEDKEYSPEC Pripkcs8 = New PKCS8ENCODEDKEYSPEC (BPKCS); KeyFactory keyf = keyfactory.getInstance ("DSA"); privateKey OtherPrikey = keyf.generateprivate (Pripkcs8); Common API java.security.KeyPairGenerator key generator class public static KeyPairGenerator getInstance (String algorithm) throws NoSuchAlgorithmException a specified algorithm returns KeyPairGenerator object Parameters: algorithm, such as algorithm name:. "DSA", "RSA" public void initialize (int Keysize initializes the keypairgenerator object with the specified length, if there is no initialization system with a 1024 length default setting parameter: Keysize algorithm is long. The range must be between 512 to 1024, and must be a multiple of 64 Public void Initialize (int Keysize, Securerandom Random) Initialize and random generator in the specified length generator object parameters: Keysize algorithm is long. Its range must be between 512 to 1024, and must be 64 multiples random a random source (for Initialize (int Keysize) using default randomizer public abstract KeyPair generateKeyPair () generates a new key return private key pair java.security.KeyPair public PublicKey getPublic class public PrivateKey getPrivate () () returns the class public key signature public static java.security.Signature signature getInstance (String algorithm) throws NoSuchAlgorithmException returns a specified algorithm signature algorithm object parameters such as: "DSA" public final void initSign (privateKey privateKey) throws InvalidKeyException with the specified private key initialization parameters: privateKey when the private key used to sign public Final Void Update (Byte Data) THROWS SIGNATUREXCEPTIONPUBLIC FINAL VOID UPDATE (B yte [] data) throws SignatureExceptionpublic final void update (byte [] data, int off, int len) throws SignatureException added to the signature information public final byte [] sign () throws SignatureException Returns an array of signature, provided that initSign and updatepublic final initialization parameter with the specified public void initVerify (PublicKey publicKey) throws InvalidKeyException: public final boolean verify the public key used to verify the time publicKey (byte [] signature) throws SignatureException verify whether the signature is valid, provided that the parameters have been initialized initVerify: signature signature array * / 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 () { // Digital signature generating key // The first step generation key pair, if you have already generated, this process can skip, talk to users myprikey.dat to be saved locally // and mypubkey.dat is released to other users IF ("" "" "). EXISTS () == false { IF (generateKey () == false) { System.out.println ("Generate Key Pass"); Return; } } // Step 2, this user // Read the private key from the file, saved in a file (MyInfo.dat) after signing a string / / And then send myinfo.dat to go out // In order to facilitate the digital signature, it is also available in the MyIfno.dat file, of course, can also be sent separately. 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 = "This is my information"; // to sign the information // Generate digital signatures with private key Java.security.signature signet = java.security.signature.getInstance ("DSA"); Signet.initsign (MyPrikey); Signet.Update (MyInfo.getBytes ()); Byte [] signed = signet.sign (); // Digital signature for information System.out.println ("Signed" = " Byte2HEX (Signed)); // Save information and digital signatures in a file 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 ("Signature and Generate File Success"); } Catch (java.lang.exception e) { E.PrintStackTrace (); System.out.println ("Signature and Generate File Failure"); } //third step // Other people get the public key and files of this house through the public approach // Others use this household name, check the file, if the message is successful, is the information released by this user. // 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 ("Normal Signature"); } Else System.out.println ("Non-Sign Normal"); } Catch (java.lang.exception e) {E.PrintStackTrace (); } / / Generate a pair of file MyPrikey.dat and mypubkey.dat --- private key and public key, / / Public key to send (files, networks, etc.) to other users, private key is stored locally Public boolean generateKey () { Try { Java.security.keypairgenerator keygen = java.security.keypairgenerator.getInstance ("DSA"); // Securerandom secrand = new securerandom (); // secrand.setseed ("ttt" .getbytes ()); // Initialization Random Generator // Keygen.Initialize (576, secrand); // Initialization key generator Keygen.initialize (512); Keypair Keys = keygen.genkeypair (); // Keypair Keys = keygen.generateKeyPair (); // Generate a key group 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 ("Write Object Prikeys OK); OUT = New java.io.ObjectOutputStream (New java.io.fileoutputstream ("mypubkey.dat"); Out.writeObject (Pubkey); Out.close (); System.out.println ("Write Object Pubkeys OK"); System.out.Println ("Generate Key Pair Success"); Return True; } Catch (java.lang.exception e) { E.PrintStackTrace (); System.out.println ("Generate Key Pair Failure"); Return False; } } 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.4. DeSede / DES symmetry algorithm first generates a key and saves (here, there is no saved code, reference to methods in DSA) keygenerator.getinstance (Algorithm); SecretKey deskey = keygen.generateKey (); Use the key to MYINFO to generate cipherbert Cipher C1 = Cipher.getInstance (Algorithm); C1.INIT (cipher.encrypt_mode, deskey); Byte [] cipherbyte = c1.dofinal (Myinfo.getBytes ()); Transfer ciphertext and keys, this article does not correspond to DSA ........... Decryption with key C1 = Cipher.GetInstance (Algorithm); C1.INIT (Cipher.Decrypt_mode, deskey); Byte [] Clearbyte = c1.dofinal (cipherbyte); Relatively speaking, the use of symmetrical keys is very simple, for JCE, support DES, DESEDE, BLOWFISH three encryption For the saving of the key, the transmission can be used to use the object stream or use binary encoding. The relevant reference code is as follows. SecretKey deskey = keygen.generateKey (); Byte [] desencode = deskey.getencoded (); Javax.crypto.spec.secretkeyspec destmp = new javax.crypto.spec.secretKeyspec (Desencode, Algorithm); SecretKey mydeskey = destmp; Related API KeyGenerator has explained in DSA, and after adding JCE, you can enter the following parameters. DES, DESEDE, BLOWFISH, HMACMD5, HMACSHA1 Javax.crypto.cipher plus / decryption Public Static Final Cipher GetInstance (Java.lang.String Transformation) Throws java.security.nosuchalgorithmexception, Nosuchpaddingexception Returns a Cipher object of a specified method Parameters: Transformation method name (available des, dresse, blowfish) public final void init (int ipmode, java.security.key key) throws java.security.invalidKeyException Initialize the Cipher object with the specified key and mode Parameters: OPMODE mode (Encrypt_Mode, Decrypt_Mode, Wrap_Mode, unwrap_mode) Key key Public final byte [] DOFINAL (Byte [] Input) Throws java.lang.illegalStateException, IllegalblocksizeException, BadpAddingException For the string within the input, encoding processing, return the bunch of bunction, is the OPMODE decision to return to decryption or addiction Note: If there is Update before the execution of this method, it is all handled for Updat and this INPUT, otherwise it is the content of this inout. / * Safety program DESEDE / DES test * / Import java.security. *; Import javax.crypto. *; Public class testdes { Public static void main (String [] args) { Testdes my = new testdes (); my.run (); } Public void run () { // Add new security algorithm, if you use JCE to add it in Security.addProvider (new com.sun.crypto.provider.sunjce ()); String algorithm = "des"; // Defines an encryption algorithm, available in des, despede, blowfish String myinfo = "Information to encrypt"; Try { / / Generate a key KeyGenerator Keygen = keygenerator.getinstance (algorithm); SecretKey deskey = keygen.generateKey (); //encryption System.out.Println ("" Two-in-bits before encryption: " byte2hex (Myinfo.getBytes ()))); System.out.println ("Information before encryption:" myinfo); Cipher C1 = Cipher.getInstance (Algorithm); C1.INIT (cipher.encrypt_mode, deskey); Byte [] cipherbyte = c1.dofinal (Myinfo.getBytes ()); System.out.println ("Encrypted Bit:" Byte2HEX (Cipherbyte)); // Decryption C1 = Cipher.GetInstance (Algorithm); C1.INIT (Cipher.Decrypt_mode, deskey); Byte [] Clearbyte = c1.dofinal (cipherbyte); System.out.println ("Decoupted Bit:" Byte2HEX (Clearbyte)); System.out.println ("Decoupted information:" (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) // binary stream string { 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 key consistent protocol Open Key Cryptographic System's Founder Diffie and Hellman's "Exponential Key Agreement Protocol, the protocol does not require other security prerequisites, allowing two Name users exchange information on public media to generate "uniform", can share keys. In JCE implementation user alice generates a DH type key pair, if the length is generated with 1024, it is recommended to save DHParameterspec after the first generation is generated so that the next use direct initialization. Make it speed System.out.println ("Alice: DH ..."); Keypairgenerator alicekpairgen = keypairgenerator.getInstance ("DH"); Alicekpairgen.Initialize (512); Keypair alicekpair = alicekpairgen.generateKeyPair (); Alice generates public key transmission group BOB BYTE [] alicepubkeyenc = alicekpair.getpublic (). getENCODED (); Bob reads the initial parameters of the DH key pair from the public key sent from Alice to generate BOB DH key pairs Note that this step must be done, to ensure that each user is generated with the same initial parameters DHParameterspec dhparamspec = ((DHPUBLICKEY) AlicePubkey) .getparams (); Keypairgenerator Bobkpairgen = Keypairgenerator.getInstance ("DH"); Bobkpairgen.Initialize (DHPARAMSPEC); Keypair Bobkpair = bobkpairgen.generateKeyPair (); Bob generates a local DES key according to the public key of Alice Keyagreement Bobkeyagree = Keyagreement.GetInstance ("DH"); Bobkeyagree.init (Bobkpair.getPriVate ()); Bobkeyagree.dophase (AlicePubkey, true); SecretKey Bobdeskey = Bobkeyagree.generateSecret ("DES"); Bob has already generated his DES key, he is now sent to Alice, BYTE [] BobpubKeyenc = Bobkpair.getPublic (). getENCODED (); Alice generates a local DES key based on Bob's public key ,,,,,, decoding Keyagreement AliceKeyagree = Keyagreement.GetInstance ("DH"); AliceKeyagree.init (AlicekPair.getPriVate ()); AliceKeyagree.Dophase (Bobpubkey, true); SecretKey Alicedeskey = AliceKeyagree.generateSecret ("DES"); Bob and Alice will have the same DES key for this process, and secure the security letter in this basis. Common API java.security.KeyPairGenerator key generator class public static KeyPairGenerator getInstance (String algorithm) throws NoSuchAlgorithmException a specified algorithm returns KeyPairGenerator object Parameters: algorithm, such as algorithm name: originally DSA, now add a Diffie-Hellman (DH) Public void initialize (int keySize) initializes the KeypairGenerator object at a specified length, and if there is no initialization system with a 1024 length default setting parameter: Keysize algorithm is long. The range must be between 512 to 1024, and must be a multiple of 64 Note: If It is very long to grow with 1024, and it is best to save it once. Next time you don't have it. Public void initialize (Algorithmparameterspec params) Throws invalidalgorithmparameterException initializes specified parameters Javax.crypto.interfaces.dhpublicKeyPublic dhparameterspec getparams () Returns Java.Security.KeyFactory Public Static KeyFactory GetInstance (String Algorithm) THROWS NOSUCHALGORITHMEXCEPTION Returns a KeyFactory parameter in the specified algorithm: Algorithm algorithm name: DSH, DH Public Final Publickey GeneratePublic (Keyspec Keyspec) THROWS INVALIDKEYSPECEXCEPTION Returns a publickey object according to the specified Key java.security.spec.X509EncodedKeySpecpublic X509EncodedKeySpec (byte [] encodedKey) Description Argument generate a key according to the specified binary code string: encodedKey binary coded string (generally through PublicKey.getEncoded () generation) javax.crypto. Keyagreement password one to class Public Static Final Keyagreement GetInstance (Java.lang.String Algorithm) THROWS JAVA.SECURITY.NOSUCHALGORITHMEXCEPTION Returns a keyagreement object parameter for specifying algorithms: Algorithm algorithm name, now only Diffiehellman (DH) Public final void init (java.security.key key) throws java.security.invalidKeyException parameters with the specified private key: KEY a private key public final java.security.Key doPhase (java.security.Key key, boolean lastPhase) throws java.security.InvalidKeyException, java.lang.IllegalStateException positioned with the specified public key, lastPhase is determined whether this is the last public key, for in the case of two users can set multiple times, the last parameter to determine: whether the public key public lastPhase last public final SecretKey generateSecret (java.lang.String algorithm) throws java.lang.IllegalStateException, java.security.NoSuchAlgorithmException, Java.security.invalidKeyException Generates key parameters according to the specified algorithm: Algorithm Encryption 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 (); // generation time // Zhang San (Alice) Generates a public key AlicePubkeyenc and sent to Li Si (BOB), // For example, use file mode, socket ..... BYTE [] alicepubkeyenc = alicekpair.getpublic (). getENCODED (); // Bob receives the public key after Alice encoding, decoding it KeyFactory Bobkeyfac = KeyFactory.GetInstance ("DH"); X509EncodedKeyspec x509keyspec = new x509encodedKeyspec (alicepubkeyenc); Publickey alicepubkey = bobkeyfac.generatepublic (x509keyspec); System.out.println ("Alice public key BOB decoding success"); // Bob must initialize his DH Key pair with the same parameters, so you have to send him a public key from Alice. / / Read the parameters, then initialize his DH Key pair with this parameter // Parameter DHPARAMESPEC DHPARAMSPEC = (DHPUBLICKEY) AlicePubkey when the AlicePubkye is initialized from AlicePubkye .GetParams (); Keypairgenerator Bobkpairgen = Keypairgenerator.getInstance ("DH"); Bobkpairgen.Initialize (DHPARAMSPEC); Keypair Bobkpair = bobkpairgen.generateKeyPair (); System.out.println ("Bob: Generate DH Key to Success"); Keyagreement Bobkeyagree = Keyagreement.GetInstance ("DH"); Bobkeyagree.init (Bobkpair.getPriVate ()); System.out.println ("Bob: Initialization Local Key Success"); // Li Si (BOB) Generates Local Key BOBDeskey Bobkeyagree.dophase (AlicePubkey, true); SecretKey Bobdeskey = Bobkeyagree.generateSecret ("DES"); System.out.println ("Bob: Locate Local KEY with Alice, generate local DES key success"); // bob generates a public key BobPubKeyenc and sent to Alice, // For example, use file mode, socket ....., make it generated local key BYTE [] BobpubKeyenc = Bobkpair.getPublic (). getENCODED (); System.out.Println ("Bob to Alice Send Public Key"); // Alice receives BobPubKeyenc to generate BobPubkey / / To position again, so AliceKeyAgree is positioned in BobPubkey KeyFactory AliceKeyFAC = KeyFactory.GetInstance ("DH"); X509keyspec = new x509encodedKeyspec (BobpubKeyenc); Publickey Bobpubkey = AliceKeyFac.GeneratePublic (x509keyspec); System.out.println ("Alice Receives BOB Public Key and Decoding Success"); ; Keyagreement AliceKeyagree = Keyagreement.GetInstance ("DH"); AliceKeyagree.init (AlicekPair.getPriVate ()); System.out.println ("Alice: Initialization Local Key Success"); AliceKeyagree.Dophase (Bobpubkey, true); // 张 张 三 代 代 代 代 代 代 代 a SecretKey Alicedeskey = AliceKeyagree.generateSecret ("DES"); System.out.println ("Alice: Local KEY with BOB, and generate local DES key"); IF (alicedeskey.equals (bobdeskey)) system.out.println ("Zhang Sanhe Li Si's key is the same"); // Now Zhang San and Li Si's local deskey is the same, so it can be used to send encryption, decrypt after receiving, reach / / The purpose of the security channel / * * Bob encrypts information with BOBDESKEY key * / Cipher bobcipher = cipher.getinstance ("des"); bobcipher.init (cipher.encrypt_mode, boBDeskey); String Bobinfo = "This is the confidential information of Li Si"; System.out.println ("Li Sijia Pedicent Original:" Bobinfo); Byte [] cleArtext = Bobinfo.getBytes (); Byte [] ciphertext = BobCIpher.dofinal (Cleartext); / * * Alice decrypts with AlicEdeskey key * / Cipher alicecipher = cipher.getinstance ("des"); AliceCIpher.init (Cipher.Decrypt_mode, alicedeskey); Byte [] Recovered = AliceCIPHER.DOFINAL (CIPHERTEXT); System.out.println ("Alice Decryption BOB Information:" (New String (Recovered)); IF (! java.util.arrays.equals (cleautext, recovered)) Throw new Exception ("Differentiate the information information after decryption"); System.out.println ("Decryption after Decryption"); } } Chapter 3 Small junction When the key is generated during the encryption, the key pair is of course, but the more time, the more time, please select the appropriate length from the actual start, most of the key in most examples is Every time you run, you will be generated in the actual situation. After you save it in your file, you will run directly from the file again, thereby speeding up. Of course, the timing update and the security of the enhanced key storage tube are also necessary. About the author Wang Hui, with eight years of programming and system management experience, the language used is C and Java programming languages. At present, a programmer in Shenzhen, using C and Java to program the DB2 database. You can contact you through http://www-900.cn.ibm.com/developerWorks/cn/java/l-security/ddxxxkk@21cn.com .