Implementation example of Java add-density algorithm

xiaoxiao2021-03-06  88

JAVA encryption algorithm to realize the use cases http://www.chinaunix.net Author: ii Posted: 2003-02-08 10:48:32

Implementation case for Java add-to-relevancy algorithm (1) ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ --------------------------------- [author: Wang Hui Add time: 2001-10-23 9:04: 51] Source: www.ibm.com About the author Wang Hui ddxxkk@21cn.com 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. -------------------------------------------------- ----------------------- Chapter 1 Basic Knowledge 1.1. Monolithic key cryptographic system is a traditional encryption algorithm, refers to information The sender and the recipient 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). 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 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 (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 = "I The 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 certain manner to other Human Information (MyInfo) and Summary (Digesta) The other party can determine whether or not change or transfer normal java.security.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) // Two-line string {String HS = "" String stmp = ""; for (int N = 0; n

Initial one signature object, and use private key to sign Java.Security.Signature Signet = java.security.signature.getinstance ("DSA"); signet.initsign (MyPrikey); signet.update (); byte [] Signed = signet.sign (); saved 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 (); sending his public key information and signature to other users other users with his public key (Pubkey) and signature ( Signed) and Information (INFO) verify that the information is read in the 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 signetCheck = Java with public key and signature. Security.SIGNATURE.GETITINSTANCE ("DSA"); signetCheck.initverify (Pubkey); SignetCheck .Update (INFo.GetBytes ()); if (SignetCheck.verify) {system.out.println ("Normal");} Save the key to save and transfer in the way in the object stream, You can also be saved in the way. Note that import java.security.spec. * Import java.security. * Removes that the public key is encoded with X.509, the code code is as follows: Byte [] BobencodedPubkey = mypublic. the getEncoded (); // // generate encoded binary-coded transmission transcoding // the following code corresponding to the object key X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec (bobEncodedPubKey); KeyFactory keyFactory = KeyFactory.getInstance ( "DSA"); PublicKey bobPubKey = keyFactory.generatePublic (BobPubkeyspec); For Private Key, use PKCS # 8 encoding, with code as follows: Byte [] bpkcs = myprikey.getencoded ();

// // The following code transmitted binary coded transcoding key corresponding to the object PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec (bPKCS); KeyFactory keyf = KeyFactory.getInstance ( "DSA"); PrivateKey otherprikey = keyf.generatePrivate (priPKCS; 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) specified Length initialization Keypairgenerator object, if there is no initialization system with a 1024 length default setting parameter: Keysize algorithm bit is long. The range must be between 512 to 1024, and must be a multiple of 64 Public void Initialize (int key, secondom random) to specify Length initialization and random generator initialization Keypairgenerator object parameters: Keysize algorithm bit. The range must be between 512 to 1024, and must be a number of randomits of 64 Random (for Initialize (int keySize) using the default with machine public abstract KeyPair generateKeyPair () generates a new key pair java.security.KeyPair key return to the private public PublicKey getPublic () class public PrivateKey getPrivate () returns the public key signature java.security.Signature class public static signature getInstance (String algorithm Throws NosuchalgorithMexception Returns a specified algorithm Signatu The object parameter re algorithm: "DSA" public final void initSign (PrivateKey privateKey) throws InvalidKeyException with the specified private key initialization parameters: privateKey when performed with the private key signed 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 added to the signature information public final byte [] sign () throws SignatureException returns an array of signature, provided that initSign and update public final void initVerify (PublicKey publicKey) throws InvalidKeyException initialization parameters with the specified public key: public key authentication publicKey with public final boolean verify when (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 generated key // First step generation key pair, if you have already generated, this process can skip, talk to users myprikey.dat to be saved locally // Mypubkey.dat is published to other users IF (("MyPrikey.Dat"). EXISTS () == false) {if (generateKey () == false) {system.out.println "Generate Key Fall"); return;};} // Step 2, this user // read private key from the file, saved after a string is signed in a file (MyInfo.dat) / / And then send myinfo.dat to // In order to facilitate the digital signature, it is also available in the MyIfno.dat file, of course, 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.x509encode = java.security.spec.x509encodedKeyspec string myinfo = "This is my information"; // To sign the information // generate digital signature Java.Security.Signature Signet = java.security.signature.GetInstance ("DSA"); signet.initsign (MyInTBytes); signet.Update ()); Byte [] signed = signet.sign (); // 信息 信息 信息 ("Signed) =" Byte2HEX (Signed)); // Sign Information and Digital Signature stored in a file out java.io.ObjectOutputStream = 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 Failed") };

// Step 3 // Other people get the public key and file // other people in the public manner, check the file, if the file is successful, 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 [] 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) {system.out.println ("info =" info); System.out.Println ("Normal");} else system.out.println "Non-signature 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 (file, network, etc.) to other users, private key saved in local public boolean generateKey () {java.security.keypairgenerator keygen = java.security.Keypairgenera Tor.GetInstance ("DSA"); // securerandom secrand = new securerandom (); // secrand.setseed ("ttt". setbytes ()); // Initialization Random generator // Keygen.initialize (576, secrand) ; // Initialization Key Builder Keygen.initialize (512); Keypair Keys = Keygen.GenKeyPair (); // Keypair Keys = Keygen.GenerateKeyPair (); // Generate 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 Harmony"); 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

Related API KeyGenerator has explained in DSA, after adding JCE, in Instance, you can use the following parameters des, diede, blowfish, hmacmd5, hmacsha1 javax.crypto.cipher plus / decryption PUBLIC FINAL CIPHER GETITANCE (Java.lang.String Transformation) throws java.security.NoSuchAlgorithmException, NoSuchPaddingException Cipher process returns a specified object parameter: transformation method name (available DES, DESede, Blowfish) public final void init (int opmode, java.security.Key key) throws java.security.InvalidKeyException with the specified key and the object parameters Cipher mode initialization mode pmode (ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE, UNWRAP_MODE) key key public final byte [] doFinal (byte [] input) throws java.lang.IllegalStateException, IllegalBlockSizeException, BadPaddingException the input of the String, encoding processing, returning the binary string, is it to return to decryptic or add explanation by init OPMODE decision: If there is Update before execution, it is all handled for Updat and this INPUT, otherwise it is this INOUT content / * Security program DeSede / des test * / import java.security. *; import javax.crypto. *; public class testdes {public static vo ID 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, uses des, deside, blowfish string myinfo = "to encrypt information"; try {// Generate a key KeyGenerator keygen = keygenerator.getInstance (algorithm); secondkey deskey = keygen.generateKey (); // encryption system.out.println ("The binary of encrypted:" 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 ("decrypted 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) // Two-line system string {string hs = "; string stmp =" "; for (int N = 0; n

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 presents his public key to Alice, Byte [] Bobpubkeyenc = Bobkpair.getPublic (). GetENCODED (); Alice bob public key DES key generated based on the local decoded ,,,,,, 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 safely believed in this basis. public static KeyPairGenerator getInstance (String algorithm) throws NoSuchAlgorithmException specified algorithm returns a KeyPairGenerator object parameters: algorithm algorithm name such as: the original DSA, now adding DiffieHellman (DH) public void initialize (int keysize) to specify the length initialization KeyPairGenerator Object, if there is no initialization system with a 1024 length default setting parameter: Keysize algorithm is long. The 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 right, so from Alice to his public key, // parameters are read out, then this parameter initialization parameters used when DHParameterSpec dhParamSpec // alice initialization taken from his alicePubKye the DH key = ((DHPublicKey) alicePubKey) .getParams (); KeyPairGenerator bobKpairGen = KeyPairGenerator.getInstance ( "DH"); bobKpairGen.initialize (dhParamSpec); KeyPair bobKpair = bobKpairGen.generateKeyPair (); System.out.println ( "BOB: DH key to the successful generation"); 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: Positioning Local Key with Alice); // bob generates public key BobPubKeyenc and sends 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"); after receiving bobPubKeyEnc // alice generating 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 : Initialization Local Key Success "); AliceKeyagree.Dophase (Bobpubkey, true); // Zhang San (Alice) Generates Local Key AliceDeskey SecretKey AliceDeskey = AliceKeyAgree.generateSecret (" DES "); System.Out.println (" Alice : Position local Key with Bob, and generate local DES key "); if (alicedeskey.equals (bo BDeskey)) System.out.println ("Zhang Sanhe Li Si's key"); // Now Zhang San and Li Si's local Deskey is the same, so you can send encryption, decrypt, reach after receiving // // * * bob with BobDeskey key encryption information * / cipher bobcipher = copher.getinstance ("des"); bobcipher.init (cipher.encrypt_mode, boBDeskey); string bobinfo = "This is Li Si Confidential information "; system.out.println (" Li Sijia Pedicent original: " bobinfo); Byte [] clertext = bobinfo.getBytes (); byte [] ciphertext = bobcipher.dofinal (cleartext); / * * Alice Decrypts * / cipher alicecipher = cipher.getinstance ("des") with alicedeskey keys;

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

New Post(0)