Implementation case of JAVA encryption algorithm

xiaoxiao2021-03-05  21

Object

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 the 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 key, this article does not have the corresponding code can be referred 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 decryption or addiction

Note: If there is Update before the execution of this method, it is all handled for Updat and this INPUT, otherwise it is the content of this inout.

/ *

Safety program DESEDE / DES test

* /

Import java.security. *;

Import javax.crypto. *;

Public class testdes {

Public static void main (String [] args) {

Testdes my = new testdes ();

my.run ();

}

Public void run () {

// Add new security algorithm, if you use JCE to add it in

Security.addProvider (new com.sun.crypto.provider.sunjce ());

String algorithm = "des"; // Defines an encryption algorithm, available in des, despede, blowfish

String myinfo = "Information to encrypt";

Try {

/ / Generate a key

KeyGenerator Keygen = keygenerator.getinstance (algorithm);

SecretKey deskey = keygen.generateKey (); // encryption

System.out.Println ("" Two-in-bits before encryption: " byte2hex (Myinfo.getBytes ())));

System.out.println ("Information before encryption:" myinfo);

Cipher C1 = Cipher.getInstance (Algorithm);

C1.INIT (cipher.encrypt_mode, deskey);

Byte [] cipherbyte = c1.dofinal (Myinfo.getBytes ());

System.out.println ("Encrypted Bit:" Byte2HEX (Cipherbyte));

// Decryption

C1 = Cipher.GetInstance (Algorithm);

C1.INIT (Cipher.Decrypt_mode, deskey);

Byte [] Clearbyte = c1.dofinal (cipherbyte);

System.out.println ("Decoupted Bit:" Byte2HEX (Clearbyte));

System.out.println ("Decoupted information:" (New String (Clearbyte));

}

Catch (java.security.nosuchalgorithmexception e1) {e1.printStackTrace ();

Catch (javax.crypto.nosuchpaddingexception E2) {e2.printstacktrace ();

Catch (java.lang.exception e3) {E3.PrintStackTrace ();

}

Public string byte2hex (byte [] b) // binary stream string

{

String HS = "";

String stmp = "";

For (int N = 0; n

{

STMP = (java.lang.integer.tohexstring (b [n] & 0xff);

IF (stmp.length () == 1) HS = HS "0" STMP;

ELSE HS = HS STMP;

IF (n

}

Return hs.touppercase ();

}

}

2.5. Diffie-Hellman key consistent protocol

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 parameter with the specified algorithm: Algorithm algorithmname: 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.

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

New Post(0)