Implementation example of Java add-density algorithm
Chapter 1 Basic Knowledge
1.1. Monkey cryptographic system
The single key cryptograph is a traditional encryption algorithm that refers to the sender of the information and the recipient to add decryption using 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 summary
A message summary is a digital fingerprint for a 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
It is difficult to generate a message to the specified summary, which is reversed by the message to calculate the designated summary.
Representative: MD5 proposed by the US National Standard Technology Institute of SHA1 and MIT Ronald Rivest
1.3. Diffie-Hellman key consistent protocol
The key consistent protocol is a kind of thought of the founder Diffie and Hellman of the public key cryptosystem.
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 to solve key management problems, in their lacked work "New Direction", allowing information to exchange information through communication between unsafe media Secretly transmit 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 has sent this information (ie unrecognizable). ), But also ensure that the information packet is tampered with after the signature is subjected to (ie integrity). 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;
An abstract (digital fingerprint) output for generating a fixed length of any input message data
The summary can be easily calculated from the packet;
It is difficult to generate a message for the specified summary, and the message is counterproducted to 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 consistency and DES program requires 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 Abstract MD5 and SHA
Instructions:
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 Generate a KeypairGneerator instance 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 digital signature of the information (INFO) to generate a signature array Read private key from the file (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 use his public key (Pubkey) and Signed and Information (INFO) to verify whether it is signed by his signature Read into 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 Signature object and verify with the public key and signature Java.security.signature signetCheck = java.security.signature.getInstance ("DSA"); SignetCheck.Initverify (Pubkey); SignetCheck.Update (Info.getBytes ()); IF (SignetCheck.Verify (Signed)) {system.out.println ("Normal Signature"); For the storage of the key, this article is saved and transmitted in the way in which the object stream is saved, or it can be saved in the encoded manner. Note Import java.security.spec. * Import java.security. * Relaxing 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, this example code is 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 Returns a keypairgenerator object with the specified algorithm Parameters: Algorithm algorithm name. Such as: "DSA", "RSA" Public void Initialize (int keysize) Initialize the KeypairGenerator object with the specified length, if no initialization system is set by default 1024 length Parameters: Keysize algorithm is long. The range must be between 512 and 1024, and must be a multiple of 64 Public void Initialize (int Keysize, Securerandom Random) Initialize and random generator objects in the specified length, the keypairgenerator object Parameters: Keysize algorithm is long. The range must be between 512 and 1024, and must be a multiple of 64 Random A random source (for the initialize (int keysize) used by default with the machine Public Abstract Keypair GenerateKeyPair () Generate new key pairs Java.Security.KeyPAIR key Public privateKey getprivate () Returned to private key Public Publickey getPublic () Return to the public Java.security.signature signature class Public Static Signature GetInstance (String Algorithm) THROWS NOSUCHALGORITHMEXCEPTION Returns a Signature object for specifying algorithms Parameters Algorithm such as: "DSA" Public Final Void InInt (PrivateKey PrivateKey) Throws invalidKeyException Initialization with the specified private key Parameters: private key when using 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 Add information to be signed Public final byte [] SIGN () Throws SignatureException Returns the array of signatures, provided inIitSign and Update Public Final Void InitVerify (Publickey Publickey) Throws invalidKeyException Initialization with the specified public key Parameters: public key used when publickey verified Public final boolean verify (byte [] signature) Throws SignatureException Verify that the signature is valid, the premise is INITVERIFY initialization Parameters: 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 symmetrical algorithm First, it is generated, and it is saved (the code that is not saved here can refer to the method in the DSA) KeyGenerator Keygen = 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 in des, deside, blowfish) Public Final Void Init (int OPMode, 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 the decryption or addicted by INIT 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 The founder Diffie and Hellman proposed by the key cryptographic system (Exponential Key Agreement Protocol), which does not require other security prerequisites, allowing two users to exchange information on public media Generate "unanimous" and can share the key. 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 according to the public key of Bob ,,,,,,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 Returns a keypairgenerator object with the specified algorithm Parameters: Algorithm algorithm name. For example, it is DSA, now add Diffiehellman (DH) Public void Initialize (int keysize) Initialize the KeypairGenerator object with the specified length, if no initialization system is set by default 1024 length Parameters: Keysize algorithm is long. The range must be between 512 and 1024, and must be a multiple of 64 Note: If you use 1024 to grow long, it is best to save it once, and you will be saved next time. Public void Initialize (Algorithmparameterspec params) Throws invalidalgorithmparameterException Initialize with specified parameters Javax.crypto.interfaces.dhpublicKey Public dhparameterspec getparams () return Java.Security.KeyFactory Public Static KeyFactory GetInstance (String Algorithm) Throws NosuchalgorithMexception Returns a KeyFactory with the specified algorithm Parameters: Algorithm Algorithm Name: DSH, DH Public final publickey generatepublic (Keyspec Keyspec) Throws InvalidKeyspecexception Return a publickey object according to the specified key description Java.security.spec.x509encodedKeyspec Public x509encodedKeyspec (byte [] encodedkey) Generate a KEY instructions based on the specified binary coded string Parameters: EncodedKey binary encoded strings (generally able to generate publickey.getencoded ()) Javax.crypto.keyagreement password one to class Public Static Final Keyagreement GetInstance (java.lang.string algorithm) Throws java.security.nosuchalgorithmexception Returns a keyagreement object for a specified algorithm Parameters: Algorithm algorithm name, now only Diffiehellman (DH) Public Final Void Init (Java.Security.Key Key) Throws java.security.invalidKeyException Initialization with the specified private key Parameters: Key a private key Public final java.security.key dophase (Java.Security.Key Key, Boolean Lastphase) Throws java.security.invalidKeyException, java.lang.illegalStateException Locate with the specified public key, LastPhase determines if this is the last public key, for two users In the case, you can fix it multiple times, and finally determine Parameters: KEY public key LastPhase is last public key Public Final SecretKey GenerateSecret (java.lang.string algorithm) Throws java.lang.illegalStateException, Java.security.nosuchalgorithmexception, Java.security.invalidKeyException Generate a key according to the specified algorithm Parameters: AlgorithM Encryption Algorithm (available in 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 // Parameters used in Alice initialization from AlicePubkye DHParameterspec dhparamspec = (DHPUBLICKEY) AlicePubkey) .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 When the key is generated during the encryption, the key pair is of course, the longer the better, but the more time, please select the appropriate length from the actual departure, most of the key in most examples is every run. From the new generation, in the actual situation is generated, saved in the file for a while, and then runs directly from the file again to speed up the speed. Of course, the timing update and the security of the enhanced key storage tube are also necessary. About 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 Ddxxxk@21cn.com.