Implementation example of Java add-density algorithm

xiaoxiao2021-03-06  41

Implementation example of Java add-density algorithm

content:

Chapter 1 Basics Chapter 2 Implementation Chapter 3 in Java Chapter 3 Sproducts

MD5 / SHA1, DSA, DESEDE / DES, DIFFIE-Hellman Using Wang Hui (ddxxk@21cn.com) July, Chapter 1 Basic Knowledge 1.1. Monolithic key cryptographic system is a traditional encryption algorithm It means that the sender of the information and the receiver jointly use the same key to decrypt. 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). 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 The MD5 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 "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 (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: DSA Chapter 2 implementation 2.1 in Java 2.1. Related Diffie-Hellman key agreements and DES programs require the support of 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 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) Calculation two summary is 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.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.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) // 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, 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 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 SIGNATureExceptionpublic Final Voi d update (byte [] 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 the signature, provided that initSign and update public final void initVerify (PublicKey publicKey) throws InvalidKeyException with the specified public key initialization parameters: publicKey validation using public key public final boolean verify (byte [] signature) throws SignatureException verify the signature is valid, provided that the initialization parameter has been 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 the user to MYPRIKEY.DAT to save the local // 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 symmetric algorithm first generates a key and saves (here, the code is not saved, can refer to the method in DSA) KeyGenerator.getInstance (Algorithm); SecretKey deskey = keygen.generateKey = keygen.generateKey (); Key Decoction (MyInfo), generated cipher, cipher, c1.get (algorithm); c1.init (cipher.encrypt_mode, deskey); byte [] cipherbyte = c1.dofinal (Myinfo.getBytes ()) Transport ciphertext and key, this article does not correspond to DSA ............... Use Key Decryption C1 = Cipher.GetInstance (Algorithm); c1.init (Cipher.Decrypt_Mode , design; byte [] clearbyte = c1.dofinal (cipherbyte); relative symmetry key usage is very simple, for JCE, support DES, DESEDE, BLOWFISH, three encryption, for keys, save each Transfer can 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, after adding JCE, in Instance, you can use the following parameters DES, DESEDE, BLOWFISH, HMACMD5, HMACSHA1 JAVAX.CRYPTO.CIPHER PA

Public Static Final Cipher GetInstance (Java.lang.String Transformation)

Throws java.security.nosuchalgorithmexception,

Nosuchpaddingexception

Returns a cipher object parameter for a specified method: Transformation method name (available with des, desilia, blowfish) public final void init (int / in) throws java.security.invalidKeyException initializes Cipher with the specified key and mode Object 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, the bunch of the bunch of the INPUT is returned. It is the OPMODE that returns the decryption or adding explanation by init: If there is Update before the implementation is executed, it is entirely processed for Updat and this INPUT. Otherwise, this 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.lendth () == 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 to pay attention to 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 can generate the same DES key over this process, which can be securely used in this basis to use API Java.Security.KeypairGenerator Key Generator GetInstance (String Algorithm) Throws NosuchalGorithMexception to specify Algorithm returns a keypairgenerator object parameter: Algorithm algorithm name. For example, the DIFFIEHELLMAN (DH) public void initialize (int keySize) initializes the keypairgenerator object in the specified length, if not initialization system is default the parameters by default at 1024 length : Keysize algorithm is long. The scope 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. DHPublicKeypublic DHParameterSpec getParams () returns java.security.KeyFactory public static KeyFactory getInstance (String algorithm) throws NoSuchAlgorithmException specified algorithm returns a KeyFactory parameters: algorithm algorithm name: DSH, DH public final PublicKey generatePublic (KeySpec keySpec) throws InvalidKeySpecException the specified Description key, returns a PublicKey objects java.security.spec.X509EncodedKeySpecpublic 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 Public Final Java.security.Key Dophas e (java.security.key, boolean lastpha) 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 you can set multiple times, and finally determine 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 specified Algorithm Generating Key Parameters: 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

// 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 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 Ddxxxk@21cn.com.

转载请注明原文地址:https://www.9cbs.com/read-72594.html

New Post(0)