Java encryption decryption Full solution __java

Source: Internet
Author: User
Tags base64 decrypt flush md5 md5 digest reserved mozilla thunderbird asymmetric encryption

1 sha encryption:

Secure Hash Algorithm (Secure Hash Algorithm) is mainly applied to the Digital Signature Algorithm (Digital Signature Algorithm DSA) defined in the Digital Signature Standard (Digital Signature Standard DSS). For messages less than 2 ^ 64 bits long, SHA1 will generate a 160-bit message digest. After years of development and improvement by encryption experts, the algorithm has become increasingly perfect and is widely used. The idea of this algorithm is to receive a piece of plain text and then convert it into a (usually smaller) cipher text in an irreversible way, which can also be simply understood as taking a string of input codes (called pre-mapping or information), and The process of converting them into an output sequence with a short length and a fixed number of bits, that is, a hash value (also known as an information digest or information authentication code). The hash function value can be said to be a kind of "fingerprint" or "digest" of the plain text, so the digital signature of the hash value can be regarded as a digital signature of the plain text.

Secure Hash Algorithm (SHA) is a national standard FIPS PUB 180 issued by the National Institute of Standards and Technology. The latest standard has been updated to FIPS PUB 180-3 in 2008. It specifies the one-way hash algorithms SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. SHA-1, SHA-224 and SHA-256 are suitable for messages with a length not exceeding 2 ^ 64 binary bits. SHA-384 and SHA-512 are suitable for messages whose length does not exceed 2 ^ 128 binary bits. Hashing algorithm Hashing is the refinement of information, usually its length is much smaller than the information, and it is a fixed length. Hash with strong encryption must be irreversible, which means that through the hash result, no part of the original information can be derived. Any change in the input information, even if only one bit, will cause a significant change in the hash result, which is called the avalanche effect. Hashing should also be anti-collision, that is, two pieces of information with the same hash result cannot be found. Hash results with these characteristics can be used to verify whether the information has been modified. The one-way hash function is generally used to generate message digests, key encryption, etc. The common ones are: l MD5 (Message Digest Algorithm 5): is a one-way hash algorithm developed by RSA Data Security. l SHA (Secure Hash Algorithm): can generate a 160-bit value for any length of data operation; SHA-1 In 1993, the Secure Hash Algorithm (SHA) was proposed by the National Institute of Standards and Technology (NIST) as The Federal Information Processing Standard (FIPS PUB 180) was published; in 1995 a revised version of FIPS PUB 180-1 was released, commonly known as SHA-1. SHA-1 is based on the MD4 algorithm, and its design largely imitates MD4. It has become one of the most secure hashing algorithms recognized and is widely used. Principle SHA-1 is a data encryption algorithm. The idea of this algorithm is to receive a piece of plaintext and then convert it into a (usually smaller) ciphertext in an irreversible way, which can also be simply understood as taking a string of input Codes (called pre-mapping or information) and the process of converting them into an output sequence with a short length and a fixed number of bits, that is, a hash value (also known as an information digest or information authentication code). The safety of the one-way hash function is that the operation process of generating the hash value has a strong one-way. If a password is embedded in the input sequence, no one can generate the correct hash value without knowing the password, thus ensuring its security. SHA divides the input stream into 512 bits (64 bytes) per block, and produces 20 bytes of output called information authentication codes or message digests. The length of the input message of this algorithm is not limited, and the resulting output is a 160-bit message digest. The input is processed in 512-bit packets. SHA-1 is irreversible, anti-collision, and has a good avalanche effect. The digital signature can be realized through the hash algorithm. The principle of digital signature is to convert the plain text to be transmitted into a message digest through a function operation (Hash) (different plain text corresponds to different message digests). The plain text is transmitted to the recipient together, and the recipient decrypts and compares the new message digest generated by the received plain text with the message digest sent by the sender. If the comparison result is consistent, the plain text has not been changed. MAC (information authentication code) is a hash result, and part of the input information is a password. Only the participants who know this password can calculate and verify the validity of the MAC code again. Comparison of SHA-1 and MD5 Because both are derived from MD4, SHA-1 and MD5 are very similar to each other. Correspondingly, their strength is similar to other characteristics, but there are also the following differences: l Security against brute force attacks: The most significant and important difference is that the SHA-1 digest is 32 bits longer than the MD5 digest. Using the forced technique, the difficulty of generating any message whose digest is equal to the given message digest is an operation of the order of 2 ^ 128 for MD5, and an operation of the order of 2 ^ 160 for SHA-1. In this way, SHA-1 has greater strength against brute force attacks. l Security for cryptanalysis: Due to the design of MD5, it is susceptible to cryptanalysis attacks, and SHA-1 is not vulnerable to such attacks. l Speed: On the same hardware, SHA-1 runs slower than MD5.

JAVA has implemented two hash algorithms SHA-256 and SHA-512

Use java.security.MessageDigest to call the integrated Hash algorithm

Create an Encrypt object, and call SHA256 or SHA512 and pass in the text information to be encrypted to obtain two encrypted hash strings, SHA-256 and SHA-512, respectively.

To change to MD5 algorithm, modify the incoming parameter strType to "MD5" to get MD5 encryption function.
/ **
 * @file Encrypt.java
 * @date August 5, 2016
 * @version 3.4.1
 *
 * Copyright (c) 2013 Sihua Tech, Inc. All Rights Reserved.
 * /
package encrypt;
 
/ **
 *
 *
 * @author chengjian.he
 * @version 3.4, August 5, 2016 at 10:05:37 am
 * @since
 * /

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt
{

  / **
   * Incoming text content and returning SHA-256 string
   *
   * @param strText
   * @return
   * /
  public String SHA256 (final String strText)
  {
    return SHA (strText, "SHA-256");
  }

  / **
   * Incoming text content and returning SHA-512 string
   *
   * @param strText
   * @return
   * /
  public String SHA512 (final String strText)
  {
    return SHA (strText, "SHA-512");
  }

  / **
   * String SHA encryption
   *
   * @param strSourceText
   * @return
   * /
  private String SHA (final String strText, final String strType)
  {
    // return value
    String strResult = null;

    // Is it a valid string
    if (strText! = null && strText.length ()> 0)
    {
      try
      {
        // SHA encryption starts
        // Create an encryption object and pass in the encryption type
        MessageDigest messageDigest = MessageDigest.getInstance (strType);
        // Pass in the string to be encrypted
        messageDigest.update (strText.getBytes ());
        // get byte type result
        byte byteBuffer [] = messageDigest.digest ();

        // convert byte to string
        StringBuffer strHexString = new StringBuffer ();
        // traverse byte buffer
        for (int i = 0; i <byteBuffer.length; i ++)
        {
          String hex = Integer.toHexString (0xff & byteBuffer [i]);
          if (hex.length () == 1)
          {
            strHexString.append ('0');
          }
          strHexString.append (hex);
        }
        // get the result
        strResult = strHexString.toString ();
      }
      catch (NoSuchAlgorithmException e)
      {
        e.printStackTrace ();
      }
    }

    return strResult;
  }
  
  public static void main (String args []) {
Encrypt ey = new Encrypt ();
System.out.println (ey.SHA ("ILoveYou", "MD5")); // 62accaf23ac9a73c0b28765b7dfaf75a
  }
}


2 Base64

Base64 is one of the most common encoding methods used to transmit 8Bit byte codes on the network. You can check RFC2045 ~ RFC2049, which has detailed specifications of MIME. Base64 encoding can be used to transfer longer identification information in the HTTP environment. For example, in the Hibernate Java Persistence system, Base64 is used to encode a long unique identifier (typically a 128-bit UUID) into a string that is used as a parameter in HTTP forms and HTTP GET URLs. In other applications, it is often necessary to encode binary data into a form suitable for placement in URLs (including hidden form fields). At this time, using Base64 encoding is unreadable, that is, the encoded data will not be directly seen by the human eye.

However, the standard Base64 is not suitable for direct transmission in the URL, because the URL encoder will change the "/" and "+" characters in the standard Base64 into the form of "% XX", and these "%" signs It needs to be converted again when it is stored in the database, because the "%" sign has been used as a wildcard in ANSI SQL. To solve this problem, an improved Base64 encoding for URLs can be used, which not only fills the '=' sign at the end, but also changes the "+" and "/" in the standard Base64 to "-" and "_" respectively ", Which avoids the conversions required in URL encoding and decoding and database storage, avoids the increase in the length of encoded information in this process, and unifies the format of object identifiers in databases, forms, and so on. There is also an improved Base64 variant for regular expressions, which changes "+" and "/" to "!" And "-", because "+", "*" and the "" used earlier in IRCu ["And"] "may have special meanings in regular expressions. In addition, there are some variants that change "+ /" to "_-" or "._" (used as an identifier name in a programming language) or ".-" (used for Nmtoken in XML) or even "_" : "(For Name in XML). Other applications Mozilla Thunderbird and Evolution use Base64 to protect email passwords. Base64 is also often used as a simple "encryption" to protect certain data, and real encryption is usually cumbersome. Spammers use Base64 to avoid anti-spam tools, because those tools usually do not translate Base64 messages. In LDIF files, Base64 is used As an encoding string.

/ **
 * @file Base64.java
 * @date August 5, 2016
 * @version 3.4.1
 *
 * Copyright (c) 2013 Sihua Tech, Inc. All Rights Reserved.
 * /
package encrypt;

import java.io.UnsupportedEncodingException;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/ **
 *
 *
 * @author chengjian.he
 * @version 3.4, August 5, 2016 at 10:32:23 AM
 * @since Yeexun 3.4
 * /

public class Base64 {
// encryption
public String getBase64 (String str) {
byte [] b = null;
String s = null;
try {
b = str.getBytes ("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace ();
}
if (b! = null) {
s = new BASE64Encoder (). encode (b);
}
return s;
}

// decrypt
public String getFromBase64 (String s) {
byte [] b = null;
String result = null;
if (s! = null) {
BASE64Decoder decoder = new BASE64Decoder ();
try {
b = decoder.decodeBuffer (s);
result = new String (b, "utf-8");
} catch (Exception e) {
e.printStackTrace ();
}
}
return result;
}
The
public static void main (String args []) {
Base64 b6 = new Base64 ();
System.out.println (b6.getBase64 ("ILoveYou"));
System.out.println (b6.getFromBase64 (b6.getBase64 ("ILoveYou")));
}
}

SUxvdmVZb3U =
ILoveYou

3 Base64Encoder

The encryption and decryption of Base64 has always used the sun.misc.BASE64Encoder / BASE64Decoder class of BASE64Encoder and BASE64Decoder under the sun.misc package. This personal class is an internal method of the sun company, and has not been exposed in the java api. It is not in the category of the JDK standard library, but it is included in the JDK and can be used directly.


/ **
 * @file Base64Encoder.java
 * @date August 5, 2016
 * @version 3.4.1
 *
 * Copyright (c) 2013 Sihua Tech, Inc. All Rights Reserved.
 * /
package encrypt;
 
/ **
 *
 *
 * @author chengjian.he
 * @version 3.4, August 5, 2016 at 10:44:22 AM
 * @since Yeexun 3.4
 * /
public class Base64Encoder {
    public static String getBASE64 (String s) {
        if (s == null)
            return null;
        return (new sun.misc.BASE64Encoder ()). encode (s.getBytes ());
    }
    // Decode and decrypt the BASE64 encoded string s
    public static String getFromBASE64 (String s) {
        if (s == null)
            return null;
        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder ();
        try {
            byte [] b = decoder.decodeBuffer (s);
            return new String (b);
        } catch (Exception e) {
            return null;
        }
    }
    public static String mTOa (Object ming) {
        return Base64Encoder.getBASE64 (Base64Encoder.getBASE64 (Base64Encoder.getBASE64 ((String) ming))));
    }
    public static String aTOm (String an) {
        return Base64Encoder.getFromBASE64 (Base64Encoder.getFromBASE64 (Base64Encoder.getFromBASE64 (an)));
    }
    public static void main (String [] args) {
        String a = mTOa ("100000.89" .toString ());
          System.out.println (a); // Encryption
          System.out.println (aTOm (a)); // Decrypt
    }
}




4 RSA


The RSA public key encryption algorithm was proposed by Ron Rivest, Adi Shamir, and Leonard Adleman in 1977. It was first announced in 1987, when all three of them worked at MIT. RSA is composed of the three letters of the last name of the three of them. RSA is currently the most influential public key encryption algorithm. It can resist most cryptographic attacks known so far. It has been recommended by ISO as a public key data encryption standard. Today only a short RSA key can be broken by a brute force method. As of 2008, there is no reliable way to attack the RSA algorithm in the world. As long as the length of the key is long enough, the information encrypted with RSA cannot actually be broken. But today, with distributed computing and quantum computer theory becoming more mature, RSA encryption security has been challenged. The RSA algorithm is based on a very simple number theory fact: it is very easy to multiply two large prime numbers, but it is extremely difficult to factorize the product, so the product can be publicly used as an encryption key. Disadvantages Edit 1) It is very troublesome to generate the key, which is limited by the prime number generation technology, so it is difficult to achieve one password at a time. 2) Security. The security of RSA depends on the factorization of large numbers, but it does not theoretically prove that the difficulty of deciphering RSA is equivalent to the difficulty of factorizing large numbers. Moreover, most people in the cryptography community tend to factorize not NP problems. Nowadays, people can decompose large prime numbers with more than 140 decimal digits, which requires the use of longer keys and slower speed. In addition, people are actively looking for ways to attack RSA, such as choosing ciphertext attacks, the average attacker is Disguise a piece of information (Blind) and let the entity with the private key sign it. Then, after calculation, you can get the information it wants. In fact, the attack utilizes the same weakness, that is, the fact that the power retains the input multiplication structure: (XM) d = Xd * Md mod n As mentioned earlier, this inherent problem comes from the public key The most useful feature of the cryptosystem-everyone can use the public key. But this problem cannot be solved algorithmically. There are two main measures: one is to use a good public key agreement to ensure that the entity does not decrypt information arbitrarily generated by other entities during the work process, and does not sign information that it knows nothing about; One is to never sign a random document sent by a stranger. When signing, first use the One-Way Hash Function to hash the document, or use a different signature algorithm at the same time. In addition to using the common modulus, people also try to use some decryption index or φ (n) and other attacks. 3) The speed is too slow, because the RSA packet length is too large, in order to ensure security, n must also be at least 600 bits, so that The operation cost is very high, especially the speed is slow, which is several orders of magnitude slower than the symmetric cryptographic algorithm; and with the development of large number decomposition technology, this length is still increasing, which is not conducive to the standardization of data formats. The SET (Secure Electronic Transaction) protocol requires CA to use a 2048-bit key, and other entities use a 1024-bit key. For speed issues, people use a combination of single and public key passwords. The advantages and disadvantages are complementary: the single key password is fast, people use it to encrypt longer files, and then use RSA to encrypt the file key Solves the key distribution problem of single-key passwords.
/ **
 * @file RSATool.java
 * @date August 5, 2016
 * @version 3.4.1
 *
 * Copyright (c) 2013 Sihua Tech, Inc. All Rights Reserved.
 * /
package encrypt;
 
/ **
 *
 *
 * @author chengjian.he
 * @version 3.4, August 5, 2016 at 10:51:35 am
 * @since Yeexun 3.4
 * /
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

public class RSATool {

public static void makekeyfile (String pubkeyfile, String privatekeyfile)
throws NoSuchAlgorithmException, FileNotFoundException, IOException {
// The KeyPairGenerator class is used to generate public and private key pairs and generate objects based on the RSA algorithm
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance ("RSA");
// Initialize the key pair generator, the key size is 1024 bits
keyPairGen.initialize (1024);
// Generate a key pair and save it in keyPair
KeyPair keyPair = keyPairGen.generateKeyPair ();

// get the private key
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate ();

// get the public key
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic ();

// Generate private key
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (
privatekeyfile));
oos.writeObject (privateKey);
oos.flush ();
oos.close ();

oos = new ObjectOutputStream (new FileOutputStream (pubkeyfile));
oos.writeObject (publicKey);
oos.flush ();
oos.close ();

System.out.println ("make file ok!");
}

/ **
*
* @param k
* @param data
* @param encrypt
* 1 encryption 0 decryption
* @return
* @throws NoSuchPaddingException
* @throws Exception
* /
public static byte [] handleData (Key k, byte [] data, int encrypt)
throws Exception {

if (k! = null) {

Cipher cipher = Cipher.getInstance ("RSA");

if (encrypt == 1) {
cipher.init (Cipher.ENCRYPT_MODE, k);
byte [] resultBytes = cipher.doFinal (data);
return resultBytes;
} else if (encrypt == 0) {
cipher.init (Cipher.DECRYPT_MODE, k);
byte [] resultBytes = cipher.doFinal (data);
return resultBytes;
} else {
System.out.println ("parameters must be: 1 encryption 0 decryption");
}
}
return null;
}

public static void main (String [] args) throws Exception {

String pubfile = "d: /temp/pub.key";
String prifile = "d: /temp/pri.key";

makekeyfile (pubfile, prifile);

ObjectInputStream ois = new ObjectInputStream (new FileInputStream (pubfile));
RSAPublicKey pubkey = (RSAPublicKey) ois.readObject ();
ois.close ();

ois = new ObjectInputStream (new FileInputStream (prifile));
RSAPrivateKey prikey = (RSAPrivateKey) ois.readObject ();
ois.close ();

// Use public key encryption
String msg = "~ O (∩_∩) O Haha ~";
String enc = "UTF-8";

// Use public key encryption and private key decryption
System.out.println ("Original:" + msg);
byte [] result = handleData (pubkey, msg.getBytes (enc), 1);
System.out.println ("Encryption:" + new String (result, enc));
byte [] deresult = handleData (prikey, result, 0);
System.out.println ("Decryption:" + new String (deresult, enc));

msg = "Oh";
// Use private key to encrypt public key to decrypt
System.out.println ("Original:" + msg);
byte [] result2 = handleData (prikey, msg.getBytes (enc), 1);
System.out.println ("Encryption:" + new String (result2, enc));
byte [] deresult2 = handleData (pubkey, result2, 0);
System.out.println ("Decryption:" + new String (deresult2, enc));

}
}
make file ok!
Original: ~ O (∩_∩) O Haha ~
Encryption: �A N� ډ B����������������ʇ������U

5 AES symmetric encryption
Encryption technology can be divided into symmetric and asymmetric.

Symmetric encryption and decryption, that is, the same key is used for encryption and decryption. Commonly used symmetric encryption technologies include DES, AES, etc.

Instead of asymmetric technology, different keys are used for encryption and decryption. Commonly used asymmetric encryption technologies include RSA, etc.

 

Why is there asymmetric encryption and decryption technology?

Suppose such a scenario that A sends a message to B, but does not want to send it in plain text, so it needs to encrypt the message. If symmetric encryption technology is used, then the same secret key is used for encryption and decryption. Unless B has Know the secret key of A, and save it. Only then can you decrypt the message sent by A.

Since the symmetric technology has only one secret key, the management of the secret key is a very troublesome problem. The birth of the asymmetric technology solves this problem. Asymmetric encryption and decryption use different secret keys, and the secret key pair There is a one-to-one correspondence, that is, the ciphertext encrypted with A's private key can only be decrypted with A's public key.

In this case, everyone has two secret keys, the private key and the public key. The private key is only known to you and cannot be told to others. The public key is public and everyone can know

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.