Chapter 1 Basic Know 1.1. Monolithic cryptographic system Monocatical system is a traditional encryption algorithm that refers to the sender of the information and the recipient 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 password system is the US DES 1.2. Message Abstract A message summary is a digital fingerprint of a data block. That is, a block of any length is calculated, generating a unique finger (for SHA1 is a 20-byte binary array). The message summary has 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 counterproducting the specified summary representative: US National Standard Technology Research Institute The MD5 1.3. Diffie-Hellman key consistent protocol key consistent protocol is a kind of idea that the Diffie-Hellman key consistent protocol is made by the founder Diffie and Hellman of the public key cryptographic system. Prerequisites, allow two users to exchange information on public media to generate "uniform", can share key representatives: Index Key Agreement Protocol 1.4. Asymmetric Algorithm and Public Key System 1976, DITTIE and Hellman provide a key exchange protocol to solve key management problems, in their own text, "New Direction of Cryptography", allows for exchange of information, securely in unsafe media Transmit a 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' surname 1.5. Digital Signature So-called Digital Signature is the information sender with its private key to extract from the biocated packet (or number) Fingerprints) Perform RSA algorithm operation to ensure that senders cannot rely on this information (ie, unrecognizable), and ensure that the information packet is tampered with after the signature is labeled (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 (Hash function). The special requirements for these haveh functions are: Accepted input messages have no length limit; for any input packets Data Generate Fixed Summary (Digital Fingerprint) Output From the packet energy to easily calculate a summary; it is difficult to generate a message to the specified summary, and the message is inverted to the designated summary; two different messages are difficult Generate the same summary representative: DSA Chapter 2 implementation 2.1 in Java 2. Related Diffie-Hellman key consistent protocols and DES programs require the support of the JCE tool library, you can go to http://java.sun.com/security/index .html download JCE and install it.
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 How to Use: First Generate a MessageDigest class, determine the calculation method java.security.MessageDigest alga = java.security.MessageDigest.getInstance ("SHA-1"); Add to make calculations Abstract Information Alga.Update (Myinfo.getBytes ()); calculates a summary Byte [] Digesta = alga.digest (); send it to other people your information and some other people to initialize, add information, and finally The comparison summary is the same algb.isequal (Digesta, Algb.Digest ()) Related AIP Java.Security.MessageDigest class Static GetInstance (String Algorithm) Returns a MessageDigest object, which implements the specified algorithm parameter: algorithm name, such as SHA-1 or MD5 Void Update (Byte Input) Void Update (Byte [] Input, INT Offset, INT LEN Add information to perform calculation summary Byte [] Digest () completes the calculation, return to the calculated summary (For MD5 is 16 bits, SHA is 20) vid reset () reset static boolean ISEqual (byte [] Digesta, Byte [] Digestb) Calculator two summary of the same 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.sec urity.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 one in a middle to others (MyInfo) and summary (Digesta) The other party can determine whether or not to change or transfer normal java.security.MessageDigest algb = java.security.MessageDigest.getInstance ("SHA-1"); algb.Update ()); 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) // Two-line system 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) } 2.3. Digital Signing DSA For a user to first generate his key pair, and save generate a keypairgenerator instance java.security.keypairgenerator keygenerator.GetInstance ("DSA"); if set The random generator initializes Securerandom secrand = new secondom (); SECRAND.SETSEED ("ttt" .GetBytes ()); // Initialization Random generator keygen.initialize (512, secrand); // Initialization key Generator Otherwise, Keygen.initialize (512); Generates Key Public Key Pubkey and Private Key PriKey KeyPAIR (); // Generate Key Group Publickey Pubkey = Keys.getPublic (); privateKey priKey = keys.getPrivate (); Save in MyPrikey.dat and MyPubkey.dat, so that the next time is not generated (generating key pair time is long java.io.ObjectOutstream 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.write Object (Pubkey); Out.close (); uses his private key (PRIKEY) to digital signature of the information (INFO) 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.close (); initial one signature object, and use private key Signature Java.Security.Signature Signet = java.security.signature.getInstance ("DSA"); signet.initsign (MyPrikey); signet.Update ()); Byte [] sign = 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 his public key information and signature to other users other users with his public key (Pubkey ) And signature (INFO) verify that the information is read into public key java.io.ObjectInputStream in = new java.io.ObjectInputStream ("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 java.security.signature with 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 "); Note The following public key is encoded with X.509. Example code is as follows: byte [] bobencodedpubkey = mypublic.Getencoded (); // Generate encoded // Transfer binary encoding // The following code conversion encoding is the corresponding KEY object X509EncodedKeyspec BobPubkeyspec = New X509EncodedKeyspec (Bobe ncodedPubKey); KeyFactory keyFactory = KeyFactory.getInstance ( "DSA"); PublicKey bobPubKey = keyFactory.generatePublic (bobPubKeySpec); Private key is used for PKCS # 8 encoding, for example, the following code: byte [] bPKCS = myprikey.getEncoded (); // // the following code transmitted binary coded transcoding to PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec (bPKCS) corresponding to the object key; KeyFactory keyf = KeyFactory.getInstance ( "DSA"); PrivateKey otherprikey = keyf.generatePrivate (priPKCS8); common API java. Security.Keypairgenerator Key Generator Class PUBLICTIC Keypairgenerator GetInstance (String Algorithm) THROWS NOSUCHALGORITHMEXCEPTION Returns a KeypairGenerator object parameter in the specified algorithm: Algorithm algorithm name. Such as: "DSA", "RSA"
Public Void Initialize initializes the keypairgenerator object at a specified length. (int Keysize, Securerandom Random) with the specified length initialization and random generator object parameters: Keysize algorithm is long. The scope must be between 512 and 1024, and must be a multiple of 64 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 public key java.security. signature signature class public static signature getInstance (String algorithm) throws NoSuchAlgorithmException returns a specified algorithm signature algorithm object parameters such as: when "DSA" public final void initSign (privateKey privateKey) throws InvalidKeyException initialization parameter with the specified private key used to sign the rivateKey private 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 Signaturee xception returns an array signature, provided that the public key public final boolean verify when using throws InvalidKeyException ublicKey verification public key initialization parameters specified initSign and update public final void initVerify (PublicKey publicKey) (byte [] signature) throws SignatureException verify that the signature effective, 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 generated key // First step generation key pair, if it has been generated, This process can skip and talk to the user. MyPrikey.dat To save on // and mypubkey.dat is published to other users IF ((New java.dat "). EXISTS () == false) {if (generateKey () ==
False) {system.out.println ("Generate Key Pass"); Return;};} // Step 2, this user // read private key from the file, saved after a string is signed One file (MyInfo.dat) / / and then send MyInfo.dat to the myiFno.dat file in order to facilitate the digital signature, of course, Try {java.io.ObjectInputStream in = New Java can also be sent separately. .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 message"; // // information to be signed with the private Key pair information generates digital signature java.security.signature signet = java.security.signature.getinstance ("DSA"); signet.initsign (MyPrikey); signet.Update ()); Byte [] Signed = SIGNET . Sign (); // Signature information for information System.out.Println ("Signed) =" Byte2HEX (Signed)); // Save information and digital signature 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.o Ut.println ("Signature and Generate File Success");} catch (java.lang.exception e) {E.PrintStackTrace (); system.out.println ("Signature and Generate File Failure");}; // Three steps // Other people get the public key and file // other people in public ways to check the public key, check the file, if the success story 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 = () in.readObject (); byte [] sign = (Byte []) in .readObject (); in.close (); java.security.sisature 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 ");} else system.out.println (" Non-signed 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 saved in local public Boolean GenerateKey () {try {java.security.KeyPairGenerator keygen = java.security.KeyPairGenerator.getInstance ( "DSA"); // SecureRandom secrand = new SecureRandom (); // secrand.setSeed ( "tttt" .getBytes ()); // Initialize the random generator // Keygen.Initialize (576, secrand); // Initialization key generator Keygen.initialize (512); keypair keys = keygen.GenKeyPair (); // Keypair Keys = keygen.generateKeyPair () ; // key group generation 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 PRI Keys 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 failed "); 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 symmetric algorithm first generates a key and saves (here, the code that is not saved, can refer to the method in DSA) KeyGenerator.getinstance (algorithm); secondkey deskey = keygen.generateKey Using a key to MYINFO, generating cipher (c1.getinstance); c1.init (cipher.encrypt_mode, deskey); byte [] cipherbyte = c1.dofinal (Myinfo.getBytes ))); Transfer ciphertext and keys, there is no corresponding code for DSA ............... Use Key Decryption C1 = Cipher.GetInstance (Algorithm); c1.init (Cipher) .Decrypt_mode, deskey); byte [] clearbyte = c1.dofinal (cipherbyte); relatively symmetric key use is very simple, for JCE, support DES, DESEDE, BLOWFISH, three encryption for key Save each transfer can use the object stream or use binary code. spec.SecretKeySpec (desEncode, Algorithm); SecretKey mydeskey = destmp; API KeyGenerator correlation has been described in the DSA, after adding the JCE instance the following parameters can feed DES, DESede, Blowfish, HmacMD5, HmacSHA1 javax.crypto.Cipher encryption / decryption Public static final cipher getinstance (java.lang.string transformation) throws java.security.nosuchalgorithmexception , NoSuchPaddingException Returns the specified method a Cipher object parameter: transformation method name (available DES, DESede, Blowfish) public final void init (int opmode, java.security.Key key) throws java.security.InvalidKeyException mode with the specified key and Cipher object is initialized parameter mode pmode (ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE, UNWRAP_MODE) key key public final byte [] doFinal (byte [] input) throws java.lang.IllegalStateException, IllegalBlockSizeException, BadPaddingException of string within the input, encoding processing, Returns the two-string of the process, is it to return to decryptic or add explanation by init to OPMODE decision: If there is Update before execution, it is handled for Updat and this INPUT, otherwise it is this inout / * security Program DeSede / Des Test * / Import Java.security. *; Import Javax.crypto. *; Public Class Testdes {PUBLIC VOID Main (String [] args) {testdes my = new testdes (); my (); mY.Run ();
} Public void run () {// Add a new security algorithm, if you use JCE to add it in Security.AddProvider (new com.sun.crypto.provider.sunjce ()); string algorithm = "des"; ////// Define the encryption algorithm, available DES, DESEDE, BLOWFISH STRINFO = "To encrypt information"; try {// generate key keygenerator keygen = keygenerator.getInstance (algorithm); secondkey design; // encryption systemKey (); // encryption system .out.println ("Two-in-bits before encryption:" byte2hex (MyInfo.getBytes ()))); system.out.println ("Information before encryption: myinfo); cipher c1 = copher.getInstance (Algorithm ); c1.init (cipher.encrypt_mode, deskey); Byte [] cipherbyte = c1.dofinal (Myinfo.getBytes ()); System.out.Println ("Encrypted binary:" Byte2HEX (Cipherbyte)) ; // Decryption C1 = Cipher.GetInstance (Algorithm); c1.init (Cipher.Decrypt_mode, deskey); byte [] Clearbyte = C1.Dofinal (Cipherbyte); System.out.Println ("Decouveling Bit): " byte2hex (clearbyte)); system.out.println (" Decryption information: " (new string (clearbyte)));} catch (java.security.nosuchalgorithmexception e1) {E1.PrintStackTrace ();} catch (javax.crypto.nosuchpaddingexception E2) {E2.PrintStackTrace ();} catch (java.lang.exception E3) {E3.Prints TackTrace ();}} public string Byte2HEX (BYTE [] b) // Two-line-made 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) ();}} 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, allow two users to exchange information on the public media to generate "consistent", can share the key.
Implementing the user alice to generate a DH type key pair in JCE, if the length is generated with 1024, it is recommended to save DHParameterspec after the first generation is used for the next time to use direct initialization. Make it speed SYSTEM.OUT.PRINTLN "ALICE: generating DH of ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance ( "DH"); aliceKpairGen.initialize (512); KeyPair aliceKpair = aliceKpairGen.generateKeyPair (); alice generate a 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 to pay attention to this step must be done, to ensure each user the same initial parameters generated DHParameterSpec dhParamSpec = ((DHPublicKey) alicePubKey) .getParams (); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance ( "DH"); bobKpairGen.initialize (dhParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair (); bob the alice local public key generated DES key KeyAgreement bobKeyAgree = KeyAgreement.getInstance ( "DH"); bobKeyAgree.init (bobKpair.getPrivate ()); bobKeyAgree.doPhase (alicePubKey, true); SecretKey bobDesKey = bobKeyAgree.generateSecret ( " "); Bob has generated his DES key, he has sent his public key to Alice, byte [] Bobpubkeyenc = Bobkpair.getpublic (). GetENCODED (); Alice generates local DES according to Bob Key ,,,,,, decoded Key Agreement aliceKeyAgree = KeyAgreement.getInstance ( "DH"); aliceKeyAgree.init (aliceKpair.getPrivate ()); aliceKeyAgree.doPhase (bobPubKey, true); SecretKey aliceDesKey = aliceKeyAgree.generateSecret ( "DES"); bob, and this too can alice the same process is generated DES key, we can secure channel can be used to generate API java.security.KeyPairGenerator key class public static KeyPairGenerator getInstance (String algorithm) on the basis of such throws NoSuchAlgorithmException a specified algorithm returns KeyPairGenerator object Parameters: Algorithm algorithm name. Such as: It turns out that DiffieHellman (DH) public void initialize is initialized to initialize the KeypairGenerator object in the specified length, and if there is no initialization system, the parameter is set by the 1024 length: the Keysize algorithm is long. Its range must be between 512 and 1024,
And must be a multiple of 64 Note: If you grow up with 1024, it is best to generate once, then save it, next time you don't have to generate the public voidalgorithmparameterException invalidalgorithmparameterException to initialize javax.crypto.interfaces. DHPublicKey public DHParameterSpec getParams () returns java.security.KeyFactory public static KeyFactory getInstance (String algorithm) throws NoSuchAlgorithmException a specified algorithm returns KeyFactory parameters: algorithm algorithm name SH, DH public final PublicKey generatePublic (keySpec keySpec) throws InvalidKeySpecException the specified Description key, returns a PublicKey objects java.security.spec.X509EncodedKeySpec public X509EncodedKeySpec (byte [] encodedKey) according to the instructions specified by the parameter string generated key is a binary-coded: encodedKey binary coded string (generally through PublicKey.getEncoded () generation) javax.crypto.KeyAgreement password to a class public static final KeyAgreement getInstance (java.lang.String algorithm) throws java.security.NoSuchAlgorithmException returns a specified algorithm KeyAgreement object parameters: 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 positions with the specified public key, LastPhase determines if this is the last public key, for two users We can set multiple times in the case, to finalize the parameters: key public lastPhase whether the last public key 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 ignition.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: generating DH of ..."); KeyPairGenerator aliceKpairGen = KeyPairGenerator.getInstance ( "DH"); AlicekPairgen.initialize (512); keypair alicekpair = alicekpairgen.generateKeyPair (); // Generate time length // Zhang San (Alice) Generates a public key AlicePubkeyenc and sent to Li Si (Bob), // Ways, socket ..... byte [] alicepubkeyenc = alicekpair.getpublic (). GetENCODED (); // bob receives the public key after Alice, decoding itFactory BobkeyFac = KeyFactory.getInstance ("DH "); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec (alicePubKeyEnc); PublicKey alicePubKey = bobKeyFac.generatePublic (x509KeySpec); System.out.println (" alice bob public key decoding success "); // bob must be initialized with the same parameters of his DH key is correct, so read the parameters from the public key from Alice, and then initialize his DH Key to use this parameter to use the parameter DHPARAMEC DHPARAMSPEC = ((( DHPUBLICKEY) alicePubKey) .getParams (); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance ( "DH"); bobKpairGen.initialize (dhParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair (); System.out.println ( "BOB: DH key generation success" Keyagreement Bobkeyagree = Keyagreement.GetInstance ("DH"); BobKeyagree.init (Bobkpair.getPrivate ()); System.out.Println ("Bob: Initialization Local Key Success"); // Li Si (BOB) Generate local Key BOBDESKEY BOBKEYAGREE.DOPHASE (ALICEPKKEY, TRUE); Secretkey BobDeskey = Bobkeyagree.GenerateSecret ("DES"); system.out.println ("Bob: Positioning Local Key with Alice) );
// Bob generates a public key BobpubKeyenc and sent to Alice, //, such as file mode, socket ....., make it generated local key BYTE [] bobpubkeyenc = bobkpair.getpublic (). GetENCoded (); system. out.println ( "BOB ALICE sends public key"); // alice generated after receiving bobPubKeyEnc bobPubKey // then positioned so aliceKeyAgree positioned bobPubKey KeyFactory aliceKeyFac = KeyFactory.getInstance ( "DH"); x509KeySpec = new X509EncodedKeySpec (bobPubKeyEnc); PublicKey bobPubKey = aliceKeyFac.generatePublic (x509KeySpec); System.out.println ( "ALICE BOB received public key and decodes successfully");; KeyAgreement aliceKeyAgree = KeyAgreement.getInstance ( "DH"); aliceKeyAgree.init (aliceKpair .getPrivate ()); System.out.println ( "ALICE: initialize the local key successfully"); aliceKeyAgree.doPhase (bobPubKey, true); // Joe Smith (Alice) to generate a local key aliceDesKey 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 San and Li Si's key is the same "); // Now Zhang San and Li Si's local deskey is the same, so it is fully able to send encryption, decrypt, decrypt, to the destination to // security channel / * * Bob Encrypt information with BobDeskey key * / cipher bobcipher = copher.getinstance ("des"); bobcipher.init ( Cipher.encrypt_mode, bobdeskey); string bobinfo = "This is the confidential information of Li Si"; System.out.Println ("Li Sijia Pedicent:" bobinfo); Byte [] Cleartext = Bobinfo.getBytes (); byte [] ciphertext = bobCipher.doFinal (cleartext); / * * alice with aliceDesKey decrypting * / 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 (Cleartext, Recovered) Throw new Exception ("Differentiate the information different from the original information"); System.out.Println ("Decouveling");