Java encryption and decryption algorithm

Source: Internet
Author: User

Generally, the encryption algorithm is simple and efficient, the key is short, the encryption and decryption speed is fast, and deciphering is extremely difficult. This article introduces
Use of MD5/sha1, DSA, desede/DES, and Diffie-Hellman.

Chapter 4 Basic Knowledge

1.1. Single-key password system

The single-key cryptography system is a traditional encryption algorithm, which means that the sender and receiver of the information use the same key for encryption and decryption.

Generally, the encryption algorithm is simple and efficient, the key is short, the encryption and decryption speed is fast, and deciphering is extremely difficult. However, encryption security relies on the security of key custody. It is a serious problem to securely transmit and keep keys on public computer networks, in addition, the key security is also a problem in the case of multiple users.

The single-key password system represents des in the United States.

1.2. Message Summary

A message digest is a digital fingerprint of a data block. Calculate a data block of any length and generate a unique fingerprint (for sha1, a 20-byte binary array ).

The message digest has two basic attributes:

  • It is difficult for two different packets to generate the same abstract.
  • It is difficult to generate a message for a specified digest, and the specified digest is calculated by the corresponding digest.

Representatives: sha1 of the National Institute of Standards and Technology and MD5 proposed by Ronald Rivest of the Massachusetts Institute of Technology

1.3.
Diffie-Hellman Key consistency Protocol

The key consistency protocol is an idea proposed by Diffie and Hellman, the founders of the public key cryptography system.

Prerequisites: two users are allowed to exchange information on the public media to generate a "consistent" and shared key.

Representative: exponential Key Agreement Protocol)

1.4. asymmetric algorithms and public key systems

1976
In order to solve the key management problem, dittie and Hellman proposed a key exchange protocol, it is allowed to exchange information between two parties on insecure media and transmit secret keys securely. On the basis of this new idea, an asymmetric key cryptography system (public key cryptography) emerged soon. In the public key system, encryption keys are different from decryption keys. They can be used by anyone who makes them public. The decryption keys are only known to the decrypted. They are called public keys (
And private key ).

Among all public key cryptography systems so far, RSA is the most famous and most widely used one. The RSA public key cryptography system was proposed by Professor R. Rivest, A. Shamir, and L. Adleman in 1977. The name of RSA is the first letter from the three inventors.

1.5. Digital Signature

The so-called digital signature means that the information sender uses its private key to perform RSA algorithm operations on the feature data (or digital fingerprint) extracted from the transmitted message, to ensure that the sender is not allowed to deny the information that has been sent (that is, non-repudiation), and to ensure that the information message is tampered with (that is, integrity) at the end of the signature ). After receiving the message, the message receiver can use the sender's public key to verify the digital signature.

Digital fingerprints that play an important role in digital signatures are generated by a special hash function. The special requirements for these hash functions are:

  1. The received input message data has no length limit;
  2. Generate a fixed-length Digest (digital fingerprint) Output for any input message data
  3. The Digest can be easily calculated from the message;
  4. It is difficult to generate a message for a specified digest, and the specified digest is calculated by the message;
  5. It is difficult for two different packets to generate the same abstract.

 

Chapter 1 implementation in Java

2.1. Related

Diffie-Hellman Key consistency protocol and des program requires support from the JCE tool library, can be to the http://java.sun.com/security/index.html

Download and install JCE. Simple installation: Copy all contents in jce1.2.1/lib
In % java_home %/lib/EXT, if the ext directory is not created, add jce1_2_1.jar and sunjce_provider.jar to classpath. For more details, see the relevant user manual.

2.2. Use of message digest MD5 and Sha

Usage:

First, generate a messagedigest class to determine the calculation method.

Java. Security. messagedigest
Alga = java. Security. messagedigest. getinstance ("SHA-1 ");

Add the information of the digest to be calculated

Alga. Update (myinfo. getbytes ());

Calculate the abstract

Byte [] digesta = alga. Digest ();

Your information and summary sent to others

Other people initialize with the same method, add information, and finally compare the summary.

Algb. isequal (digesta, algb. Digest ())

Related AIP

Java. Security. messagedigest class

Static getinstance (string algorithm)

Returns a messagedigest object that implements the specified algorithm.

Parameter: algorithm name, such as SHA-1 or MD5

Void Update (byte input)

Void Update (byte [] input)

Void Update (byte [] input, int offset, int Len)

Add the information of the digest to be calculated

Byte [] Digest ()

After the calculation is completed, return the computed Summary (for MD5, 16 bits, and Sha, 20 bits)

Void reset ()

Reset

Static Boolean isequal (byte [] digesta, byte [] digestb)

Whether the two abstracts are 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 information abstract is:" + byte2hex (digesta ));
// Send your information (myinfo) and digest (digesta) to other users in a certain way to determine whether the information is changed or transmitted normally
Java. Security. messagedigest algb = java. Security. messagedigest. getinstance ("SHA-1 ");
Algb. Update (myinfo. getbytes ());
If (algb. isequal (digesta, algb. Digest ())){
System. Out. println ("information check is normal ");
}
Else
{
System. Out. println ("different abstract ");
}
}
Catch (Java. Security. nosuchalgorithmexception ex ){
System. Out. println ("invalid Digest algorithm ");
}
}
Public String byte2hex (byte [] B) // two-line conversion string
{
String HS = "";
String stmp = "";
For (INT n = 0; n <B. length; n ++)
{
Stmp = (Java. Lang. Integer. tohexstring (B [N] & 0xff ));
If (stmp. Length () = 1) HS = HS + "0" + stmp;
Else HS = HS + stmp;
If (n <B. Length-1) HS = HS + ":";
}
Return HS. touppercase ();
}
}

 

2.3. Digital Signature DSA

  1. A user must first generate his/her key pair and save them separately.

    Generate a keypairgenerator instance

    Java. Security. keypairgenerator keygen = java. Security. keypairgenerator. getinstance ("DSA ");
    If the random generator is set, it will be initialized using the phase code.
    Securerandom secrand = new securerandom ();
    Secrand. setseed ("tttt". getbytes (); // initialize the random Generator
    Keygen. initialize (512, secrand); // initialize the key generator
    Otherwise
    Keygen. initialize (512 );
    Generate the Public Key pubkey and private key prikey
    Keypair keys = keygen. generatekeypair (); // generate a key group
    Publickey pubkey = keys. getpublic ();
    Privatekey prikey = keys. getprivate ();
    Save them in myprikey. dat and mypubkey. dat, so that they will not be generated next time.
    (It takes a long time to generate a key pair.
    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 ();
  2. Use his private key (prikey) to digitally sign the information he has confirmed (Info) to generate a signature Array

    Read a private key from a file)

    Java. Io. objectinputstream in = new java. Io. objectinputstream (New java. Io. fileinputstream ("myprikey. dat "));
    Privatekey myprikey = (privatekey) in. readobject ();
    In. Close ();
    Initialize a 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 the information and signature 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 public key information and signature to other users.
  3. Other users use his/her public key, signature, and info to verify whether the information is signed by him/her.

    Read 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();

    Initialize a signature object and use the public key and signature for verification.
    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 ");}

    This document uses Object streams to save and transmit keys. You can also use encoding to save keys.
    import
    java.security.spec.*
    import java.security.*

    The rest is described as follows:

    • The Public Key is X.509 encoded. The example code is as follows:

      Byte [] bobencodedpubkey = mypublic. getencoded (); // generate the Encoding
      // Transfer binary encoding
      // The following code is converted to the corresponding key object.
      X509encodedkeyspec bobpubkeyspec = new x509encodedkeyspec (bobencodedpubkey );
      Keyfactory = keyfactory. getinstance ("DSA ");
      Publickey bobpubkey = keyfactory. generatepublic (bobpubkeyspec );
    • The private key is encoded with PKCS #8. The example code is as follows:
      Byte [] bpkcs = myprikey. getencoded ();
      // Transfer binary encoding
      // The following code is converted to the corresponding key object.
      Pkcs8encodedkeyspec pripkcs8 = new pkcs8encodedkeyspec (bpkcs );
      Keyfactory keyf = keyfactory. getinstance ("DSA ");
      Privatekey otherprikey = keyf. generateprivate (pripkcs8 );
  4. Common APIs

    Java. Security. keypairgenerator key generator class
    Public static keypairgenerator
    Getinstance (string algorithm) throws nosuchalgorithmexception

    Returns a keypairgenerator object using the specified algorithm.
    Parameter: algorithm name, for example, "DSA", "RSA"

    Public void initialize (INT keysize)

    Initializes the keypairgenerator object with the specified length. if the system is not initialized, the default value is 1024.

    Parameter: the length of the keysize algorithm. The value range must be between 512 and 1024 and must be a multiple of 64.

    Public void initialize (INT keysize, securerandom random)

    Initialize the keypairgenerator object with the specified length and random Generator
    Parameter: the length of the keysize algorithm. The value range must be 512 to 1024.
    And must be a multiple of 64
    Random uses the default Random Device for the source of a random bit (for initialize (INT keysize)

    Public abstract keypair generatekeypair ()
    Generate new key pair

    Java. Security. keypair key pair class
    Public privatekey getprivate ()
    Return Private Key

    Public publickey getpublic ()
    Return Public Key

    Java. Security. Signature Class
    Public static signature getinstance (string
    Algorithm) throws nosuchalgorithmexception
    Returns the signature object of a specified algorithm.
    Parameters
    Algorithm: "DSA"

    Public final void initsign (privatekey)
    Throws
    Invalidkeyexception
    Initialize with the specified Private Key
    Parameter: private key used for privatekey Signature

    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 the information to be signed

    Public final byte [] Sign ()
    Throws signatureexception

    Returns an array of Signatures provided that initsign and update

    Public final void initverify (publickey)
    Throws
    Invalidkeyexception
    Initialize with the specified public key
    Parameter: public key used for publickey Verification

    Public final Boolean verify (byte [] signature)
    Throws signatureexception

    Verify that the signature is valid only when initverify is initialized.
    Parameter: 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 ()
    {
    // Generate a key using a digital signature
    // The first step is to generate a key pair. If the key pair has been generated, this process can be skipped. for users, myprikey. dat must be saved locally.
    // While mypubkey. dat is released to other users
    If (New java. Io. File ("myprikey. dat"). exists () = false ){
    If (generatekey () = false ){
    System. Out. println ("generate key pair failed ");
    Return;
    };
    }
    // Step 2: This User
    // Read the private key from the file, sign a string, and save it in a file (myinfo. dat)
    // And send myinfo. dat again
    // For convenience, the digital signature is also put into the myifno. dat file. Of course, you can also send them 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"; // The information to be signed
    // Use the private key to generate a digital signature
    Java. Security. Signature signet = java. Security. Signature. getinstance ("DSA ");
    Signet. initsign (myprikey );
    Signet. Update (myinfo. getbytes ());
    Byte [] signed = signet. Sign (); // digital signature of information
    System. Out. println ("signed (Signature content) =" + byte2hex (Signed ));
    // Save the 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. Out. println ("signature and file generation succeeded ");
    }
    Catch (Java. Lang. Exception e ){
    E. printstacktrace ();
    System. Out. println ("failed to sign and generate file ");
    };
    // Step 3
    // Others obtain the public key and file of the user in public Mode
    // Check the file with the public key of the user. If the file is successfully published by the 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-signature normal ");
    }
    Catch (Java. Lang. Exception e) {e. printstacktrace ();};
    }
    // Generate a pair of files myprikey. dat and mypubkey. dat --- private key and public key,
    // Send the Public Key (file, network, and other methods) to other users. The private key is stored locally.
    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); // initialize the 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 ("key pair generated successfully ");
    Return true;
    }
    Catch (Java. Lang. Exception e ){
    E. printstacktrace ();
    System. Out. println ("failed to generate the key pair ");
    Return false;
    };
    }
    Public String byte2hex (byte [] B)
    {
    String HS = "";
    String stmp = "";
    For (INT n = 0; n <B. length; n ++)
    {
    Stmp = (Java. Lang. Integer. tohexstring (B [N] & 0xff ));
    If (stmp. Length () = 1) HS = HS + "0" + stmp;
    Else HS = HS + stmp;
    If (n <B. Length-1) HS = HS + ":";
    }
    Return HS. touppercase ();
    }
    }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.