Java encryption and decryption algorithm MD5/SHA1,DSA

Source: Internet
Author: User
Tags decrypt sha1


usually, the encryption algorithm used is simple and efficient, the key is short, the encryption and decryption speed is fast, the decoding is extremely difficult. This article describes the use of Md5/sha1,dsa,desede/des,diffie-hellman.


Chapter 1. Basic knowledge



1.1. Single-Key cryptosystem



Single-key cryptosystem is a traditional encryption algorithm, which means that the sender and receiver of the information together use the same key for encryption and decryption.



Usually, the encryption algorithm used is simple and efficient, the key is short, the encryption and decryption speed is fast, the decoding is extremely difficult. But the security of encryption depends on the security of key storage, it is a serious problem to transfer and keep the key securely on the public computer network, and if the security of the key is a problem in multi-user case.



The single-key cryptosystem is represented by Des in the United States.



1.2. Message Digest



A message digest is a digital fingerprint of a block of data. That is, a data block of any length is computed, producing a unique fingerprint (for SHA1, a 20-byte binary array is produced).



The message digest has two basic properties:


    • Two different messages difficult to generate the same digest
    • It is difficult to generate a message for the specified digest, and the message is inferred from the specified digest


Representative: SHA1 of the American National Institute of Standards and Technology and MIT Ronald Rivest proposed MD5



1.3. Diffie-hellman Key-Consistent protocol



Key agreement is an idea proposed by the founders of public Key Cryptosystem Diffie and Hellman.



Prerequisites, allowing two users to exchange information on public media to generate a "consistent", shared key



Rep: Exponential key agreement (exponential key agreement Protocol)



1.4. Asymmetric algorithms and public-key systems



In 1976, Dittie and Hellman in order to solve key management problems, in their groundbreaking work "new Direction of cryptography", a key exchange protocol is proposed, which allows the exchange of information between two communicating parties on unsecured media and the safe transmission of secret keys. On the basis of this new idea, the asymmetric key cryptosystem, the public key cryptosystem, is soon appearing. In the public key system, the encryption key is different from the decryption key, and the encryption key is available to everyone, and the decryption key is known only to the decrypted person. They are called public keys and secret keys (private key), respectively.



The RSA system is the most famous and most used one in all public key cryptography systems so far. The RSA public Key Cryptography system was presented by R.rivest, A.shamir and L.adleman in 1977. RSA's name is the first letter from the last names of the three inventors.



1.5. Digital signature



The so-called digital signature is the information sender with its private key to extract from the message of the feature data (or digital fingerprint) of the RSA algorithm operation, to ensure that the sender can not deny that the information has been sent (that is, non-repudiation), but also to ensure that the information message after the signature has been tampered with (that is, integrity). When the message receiver receives the message, it can authenticate the digital signature with the sender's public key.



Digital fingerprinting, which plays an important role in digital signatures, is generated by a special hash function (hash function), and the special requirements for these hash functions are:


    1. There is no length limit for the input message data received;
    2. Generates a fixed-length digest (digital fingerprint) output for any input message data
    3. The summary can be easily calculated from the message;
    4. It is difficult to generate a message for the specified digest, and the specified digest is extrapolated from the message;
    5. Two different messages difficult to generate the same digest


Representative: DSA





Chapter 2. Implementation in JAVA






2.1. Related



Diffie-hellman key agreement and DES programs require the support of the JCE tool Library and can be downloaded to http://java.sun.com/security/index.html for JCE and installed. Simple installation to copy all the contents under the Jce1.2.1\lib to%java_home%\lib\ext, if there is no ext directory to build their own, and then add Jce1_2_1.jar and Sunjce_provider.jar to classpath inside, See the user Manual for more detailed instructions



2.2. Message digest use of MD5 and Sha



How to use:



First, a MessageDigest class is generated to determine the calculation method



Java.security.MessageDigest alga=java.security.messagedigest.getinstance ("SHA-1");



Add information to calculate a summary



Alga.update (Myinfo.getbytes ());



Calculate a summary



Byte[] Digesta=alga.digest ();



Send to other people your information and summary



Other people initialize with the same method, add information, and finally make a comparison summary is the same



Algb.isequal (Digesta,algb.digest ())



Related AIP



Java.security.MessageDigest class



Static getinstance (String algorithm)



Returns a MessageDigest object that implements the specified algorithm



Parameters: 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 information to calculate a summary



Byte[] Digest ()



Complete the calculation, return the computed summary (for MD5 is 16 bits, SHA is 20 bits)



void Reset ()



Reset



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



Is the same as two summaries of the effect



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("The summary of this information is:"+byte2hex(digesta));
      //Transfer your information (myinfo) and digest (digesta) to others through a certain method, the other party can judge whether the change or transmission is normal
      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("The summary is not the same");
         }
   }
   catch (java.security.NoSuchAlgorithmException ex) {
     System.out.println("Illegal 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. For a user to first generate his key pair, and separately save


    Generate a Keypairgenerator instance


    java.security.KeyPairGenerator keygen=java.security.KeyPairGenerator.getInstance("DSA");
         If the random generator is set, initialize it with 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 key public key pubkey and private key prikey
           KeyPair keys=keygen.generateKeyPair(); //Generate 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 the 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();  Out.close (); 
  2. Use his private key (Prikey) to digitally sign the information he confirms to produce a signed array
  3. Read the private key from the file (Prikey)

    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 his public key information and signature to other users
    
  4. Other users use his public key (PubKey) and signature (signed) and information (info) to verify that the information is signed by him


    Read-In Public key
    java.io.ObjectInputStream in=new java.io.ObjectInputStream(new java.io.FileInputStream("mypubkey.dat"));
    PublicKey pubkey=(PublicKey)in.readObject(); 
    in.close();



    Read in signatures and messages
    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, validated with public key and signature
    java.security.Signature signetcheck=java.security.Signature.getInstance("DSA");
    signetcheck.initVerify(pubkey); 
    signetcheck.update(info.getBytes()); 
    if (signetcheck.verify(signed)) { System.out.println("签名正常");}



    For the preservation of keys this article is stored and transmitted in the form of object flow, and can also be stored in an encoded manner. Note to
    import java.security.spec.* 
    import java.security.*



    The following instructions


    • The public key is encoded with the code as follows:
    • byte[] bobEncodedPubKey=mypublic.getEncoded(); //Generate code
          //Transmit binary code
          //The following code is converted to the corresponding key object
          X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
          KeyFactory keyFactory = KeyFactory.getInstance("DSA");
          PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
       
    • For private key is encoded with PKCS#8, the sample code is as follows:
      byte[] bPKCS=myprikey.getEncoded();
         //Transmit binary code
         //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);
      
  5. Common APIs


    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: "DSA", "RSA"



    public void Initialize (int keysize)



    Initializes the Keypairgenerator object at the specified length if the system is not initialized with 1024-length default settings



    Parameters: KeySize algorithm bit length. The range must be between 512 and 1024 and must be a multiple of 64



    public void Initialize (int keysize, SecureRandom random)
    Initializes the Keypairgenerator object with the specified length initialization and random generator
    Parameters: KeySize algorithm bit length. The range must be between 512 and 1024 and must be a multiple of 64
    Random bit source (for initialize (int keysize) uses the default with machine



    Public abstract KeyPair Generatekeypair ()
    Generate a new key pair



    Java.security.KeyPair Key Pair Class
    Public Privatekey getprivate ()
    Return private key



    Public PublicKey getpublic ()
    Return public key



    Java.security.Signature Signature Class
    public static Signature getinstance (String algorithm) throws NoSuchAlgorithmException
    Returns a Signature object for the specified algorithm
    Parameters algorithm such as: "DSA"



    Public final void Initsign (Privatekey privatekey)
    Throws InvalidKeyException
    Class with the specified private key.
    Parameter: Privatekey the private key used for signing



    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 you want to sign



    Public final byte[] sign ()
    Throws Signatureexception
    Returns an array of signatures, provided that initsign and update



    Public final void Initverify (PublicKey publickey)
    Throws InvalidKeyException
    Class with the specified public key.
    Parameter: PublicKey the public key used for authentication



    Public Final Boolean verify (byte[] signature)
    Throws Signatureexception
    Verifies that the signature is valid, provided that it has been initverify 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()
  {
  //Digital signature generation key
  //The first step is to generate a key pair. If it has already been generated, this process can be skipped. For users, myprikey.dat should be saved locally
  //And 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;
          };
        }
//The second step, this user
//Read in the private key from the file, sign a string and save it in a file (myinfo.dat)
//And then send out myinfo.dat
//In order to facilitate the digital signature is also put into 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"; //The information to be signed
  //Use the private key to generate a digital signature on the information
  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(signed 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("Sign and generate file successfully");
  }
  catch (java.lang.Exception e) {
    e.printStackTrace();
    System.out.println("Signing and generating file failed");
  };
  //third step
  //Others get the public key and file of this user through public means
  //Others use the public key of this user to check the file. If it succeeds, it means that it 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("Signature is normal");
  }
  else System.out.println("Non-signed normal");
  }
  catch (java.lang.Exception e) {e.printStackTrace();};
  }
  //Generate a pair of files myprikey.dat and mypubkey.dat---private key and public key,
  //The public key needs to be sent (file, network, etc.) to other users, and 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 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 successfully");
   return true;
  }
  catch (java.lang.Exception e) {
   e.printStackTrace();
   System.out.println("Failed to generate 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();
    }
}
2.4. DESede/DES Symmetric Algorithm
First generate the key and save it (the saved code is not here, please refer to the method in DSA)
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
SecretKey deskey = keygen.generateKey();
Use the key to encrypt the plaintext (myinfo) and generate the ciphertext (cipherByte)
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
byte[] cipherByte=c1.doFinal(myinfo.getBytes());
Transmit ciphertext and key, there is no corresponding code in this article, please refer to DSA
.............
Use the key to decrypt the ciphertext
c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
byte[] clearByte=c1.doFinal(cipherByte);
Relatively speaking, the use of symmetric keys is very simple. For JCE, there are three encryption methods: DES, DESede, and Blowfish.
For the preservation of the key, the object stream or binary code can be used for each transmission. 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 been explained in DSA, after adding JCE, you can enter the following parameters in instance
DES, DESede, Blowfish, HmacMD5, HmacSHA1
javax.crypto.Cipher encryption/decryption device
public static final Cipher getInstance(java.lang.String transformation)
                                throws java.security.NoSuchAlgorithmException,NoSuchPaddingException
Return a Cipher object with a specified method
Parameters: transformation method name (available DES, DESede, 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
The string in the input is encoded, and the processed binary string is returned. Whether to return the decrypted text or add the solution text is determined by the opmode at init
Note: If there is update before the execution of this method, it will process all updat and this input, otherwise it will be 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 a new security algorithm, if you use JCE, you must add it
 Security.addProvider(new com.sun.crypto.provider.SunJCE());
String Algorithm="DES"; //Define the encryption algorithm, available DES, DESede, Blowfish
String myinfo="The information to be encrypted";
   try {
   //Generate key
   KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
   SecretKey deskey = keygen.generateKey();
   //Encryption
   System.out.println("The binary string 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 binary string:"+byte2hex(cipherByte));
   //Decrypt
   c1 = Cipher.getInstance(Algorithm);
   c1.init(Cipher.DECRYPT_MODE,deskey);
   byte[] clearByte=c1.doFinal(cipherByte);
   System.out.println("Decrypted binary string:"+byte2hex(clearByte));
   System.out.println("Decrypted 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 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.5. Diffie-Hellman key agreement agreement
The "Exponential Key Agreement Protocol" (Exponential Key Agreement Protocol) proposed by Diffie and Hellman, the founders of public key cryptosystems, does not require

Java Cryptographic decryption algorithm MD5/SHA1,DSA



Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

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.