Home  >  Article  >  Java  >  Java four basic encryption algorithms

Java four basic encryption algorithms

高洛峰
高洛峰Original
2017-02-27 15:27:141331browse

Analysis of four basic encryption algorithms in Java

The simple java encryption algorithms are:

  1. BASE64 Strictly speaking, it belongs Encoding format, not encryption algorithm

  2. MD5(Message Digest algorithm 5, Message Digest Algorithm)

  3. SHA(Secure Hash Algorithm, Secure Hash Algorithm) Column algorithm)

  4. HMAC (Hash Message Authentication Code, hash message authentication code)

1. BASE64

Base64 is one of the most common encoding methods for transmitting 8-bit byte code on the Internet. You can check RFC2045~RFC2049, which has detailed specifications for MIME. Base64 encoding can be used to pass longer identification information in an HTTP environment. For example, in the Java Persistence system hibernate, Base64 is used to encode a long unique identifier (usually a 128-bit UUID) into a string, which is used as parameters 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 a URL (including hidden form fields). At this time, Base64 encoding is unreadable, that is, the encoded data will not be directly visible to the naked eye. (Source Baidu Encyclopedia)

java implementation code:

package com.cn.单向加密;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
BASE64的加密解密是双向的,可以求反解.
BASE64Encoder和BASE64Decoder是非官方JDK实现类。虽然可以在JDK里能找到并使用,但是在API里查不到。
JRE 中 sun 和 com.sun 开头包的类都是未被文档化的,他们属于 java, javax 类库的基础,其中的实现大多数与底层平台有关,
一般来说是不推荐使用的。 
BASE64 严格地说,属于编码格式,而非加密算法 
主要就是BASE64Encoder、BASE64Decoder两个类,我们只需要知道使用对应的方法即可。
另,BASE加密后产生的字节位数是8的倍数,如果不够位数以=符号填充。 
BASE64 
按照RFC2045的定义,Base64被定义为:Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式。
(The Base64 Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.) 
常见于邮件、http加密,截取http信息,你就会发现登录操作的用户名、密码字段通过BASE64加密的。
*/

public class BASE64 {
  /** 
   * BASE64解密 
   *  
   * @param key 
   * @return 
   * @throws Exception 
   */ 
  public static byte[] decryptBASE64(String key) throws Exception {  
    return (new BASE64Decoder()).decodeBuffer(key);  
  }  

  /** 
   * BASE64加密 
   *  
   * @param key 
   * @return 
   * @throws Exception 
   */ 
  public static String encryptBASE64(byte[] key) throws Exception {  
    return (new BASE64Encoder()).encodeBuffer(key);  
  } 

  public static void main(String[] args) {

   String str="12345678";

    try {
    String result1= BASE64.encryptBASE64(str.getBytes());
     System.out.println("result1=====加密数据=========="+result1);

     byte result2[]= BASE64.decryptBASE64(result1);
     String str2=new String(result2);
     System.out.println("str2========解密数据========"+str2);
  } catch (Exception e) {
    e.printStackTrace();
  }

  }

}

2. MD5

MD5 That is, Message-Digest Algorithm 5 (Message-Digest Algorithm 5), which is used to ensure complete and consistent information transmission. It is one of the hash algorithms widely used in computers (also translated as digest algorithm and hash algorithm). MD5 is generally implemented in mainstream programming languages. Computing data (such as Chinese characters) into another fixed-length value is the basic principle of the hash algorithm. The predecessors of MD5 include MD2, MD3 and MD4. Widely used in encryption and decryption technology, often used for file verification. check? No matter how big the file is, a unique MD5 value can be generated after MD5. For example, the current ISO verification is MD5 verification. how to use? Of course, the MD5 value is generated after passing the ISO through MD5. Friends who have downloaded Linux-ISO have generally seen an MD5 string next to the download link. It is used to verify whether the files are consistent.

java implementation:

package com.cn.单向加密;

import java.math.BigInteger;
import java.security.MessageDigest;
/*
MD5(Message Digest algorithm 5,信息摘要算法) 
通常我们不直接使用上述MD5加密。通常将MD5产生的字节数组交给BASE64再加密一把,得到相应的字符串
Digest:汇编
*/
public class MD5 {
  public static final String KEY_MD5 = "MD5";  

  public static String getResult(String inputStr)
  {
    System.out.println("=======加密前的数据:"+inputStr);
    BigInteger bigInteger=null;

    try {
     MessageDigest md = MessageDigest.getInstance(KEY_MD5);  
     byte[] inputData = inputStr.getBytes(); 
     md.update(inputData);  
     bigInteger = new BigInteger(md.digest());  
    } catch (Exception e) {e.printStackTrace();}
    System.out.println("MD5加密后:" + bigInteger.toString(16));  
    return bigInteger.toString(16);
  }

  public static void main(String args[])
  {
    try {
       String inputStr = "简单加密8888888888888888888";  
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}

MD5 algorithm has the following characteristics:

1. Compressibility: data of any length, The length of the calculated MD5 value is fixed.
2. Easy to calculate: It is easy to calculate the MD5 value from the original data.
3. Anti-modification: If any changes are made to the original data, even if only 1 byte is modified, the resulting MD5 value will be very different.
4. Weak anti-collision: Knowing the original data and its MD5 value, it is very difficult to find data with the same MD5 value (ie, forged data).
5. Strong anti-collision: It is very difficult to find two different data so that they have the same MD5 value.
The function of MD5 is to allow large-capacity information to be "compressed" into a confidential format (that is, to convert a byte string of any length into a hexadecimal number of a certain length) before signing the private key with digital signature software. string). In addition to MD5, the more famous ones include sha-1, RIPEMD and Haval.

3.SHA

Secure Hash Algorithm is mainly applicable to the digital signature algorithm (Digital Signature Standard DSS) defined in the Digital Signature Standard (DSS). Signature Algorithm DSA). For messages less than 2^64 bits in length, SHA1 produces a 160-bit message digest. This algorithm has been developed and improved by encryption experts over the years and has been increasingly perfected and widely used. The idea of ​​this algorithm is to receive a piece of plaintext and then convert it into a piece of (usually smaller) ciphertext in an irreversible way. It can also be simply understood as taking a string of input codes (called pre-mapping or information), and The process of converting them into a short-length, fixed-digit output sequence, that is, a hash value (also called a message digest or message authentication code). The hash function value can be said to be a "fingerprint" or "digest" of the plaintext, so the digital signature of the hash value can be regarded as the digital signature of the plaintext.

java implementation:

package com.cn.单向加密;

import java.math.BigInteger;
import java.security.MessageDigest;

/*
SHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应用中重要的工具,
被广泛地应用于电子商务等信息安全领域。虽然,SHA与MD5通过碰撞法都被破解了, 
但是SHA仍然是公认的安全加密算法,较之MD5更为安全*/
public class SHA {
   public static final String KEY_SHA = "SHA";  

  public static String getResult(String inputStr)
  {
    BigInteger sha =null;
    System.out.println("=======加密前的数据:"+inputStr);
    byte[] inputData = inputStr.getBytes();  
    try {
       MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA); 
       messageDigest.update(inputData);
       sha = new BigInteger(messageDigest.digest());  
       System.out.println("SHA加密后:" + sha.toString(32));  
    } catch (Exception e) {e.printStackTrace();}
    return sha.toString(32);
  }

  public static void main(String args[])
  {
    try {
       String inputStr = "简单加密";  
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}

Comparison of SHA-1 and MD5

Because of the two Both derived from MD4, SHA-1 and MD5 are very similar to each other. Correspondingly, their strengths and other characteristics are similar, but there are 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 brute force technology, the difficulty of generating any message whose digest is equal to a 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 against cryptanalysis: Due to the design of MD5, it is vulnerable to cryptanalysis attacks, while SHA-1 appears not to be vulnerable to such attacks.
l Speed: SHA-1 runs slower than MD5 on the same hardware.

4.HMAC

HMAC(Hash Message Authentication Code,散列消息鉴别码,基于密钥的Hash算法的认证协议。消息鉴别码实现鉴别的原理是,用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。使用一个密钥生成一个固定大小的小数据块,即MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。

java实现代码:

package com.cn.单向加密;
/*
HMAC 
HMAC(Hash Message Authentication Code,散列消息鉴别码,基于密钥的Hash算法的认证协议。
消息鉴别码实现鉴别的原理是,用公开函数和密钥产生一个固定长度的值作为认证标识,用这个标识鉴别消息的完整性。
使用一个密钥生成一个固定大小的小数据块,
即MAC,并将其加入到消息中,然后传输。接收方利用与发送方共享的密钥进行鉴别认证等。*/
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.cn.comm.Tools;

/** 
 * 基础加密组件 
 */ 
public abstract class HMAC {  
  public static final String KEY_MAC = "HmacMD5";  

  /** 
   * 初始化HMAC密钥 
   *  
   * @return 
   * @throws Exception 
   */ 
  public static String initMacKey() throws Exception {  
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);  
    SecretKey secretKey = keyGenerator.generateKey();  
    return BASE64.encryptBASE64(secretKey.getEncoded());  
  }  

  /** 
   * HMAC加密 :主要方法
   *  
   * @param data 
   * @param key 
   * @return 
   * @throws Exception 
   */ 
  public static String encryptHMAC(byte[] data, String key) throws Exception {  

    SecretKey secretKey = new SecretKeySpec(BASE64.decryptBASE64(key), KEY_MAC);  
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());  
    mac.init(secretKey);  
    return new String(mac.doFinal(data));  

  }  

  public static String getResult1(String inputStr)
  {
    String path=Tools.getClassPath();
    String fileSource=path+"/file/HMAC_key.txt";
    System.out.println("=======加密前的数据:"+inputStr);
    String result=null;
    try {
      byte[] inputData = inputStr.getBytes(); 
      String key = HMAC.initMacKey(); /*产生密钥*/ 
      System.out.println("Mac密钥:===" + key); 
      /*将密钥写文件*/
      Tools.WriteMyFile(fileSource,key);
      result= HMAC.encryptHMAC(inputData, key);
      System.out.println("HMAC加密后:===" + result); 
    } catch (Exception e) {e.printStackTrace();} 
    return result.toString();
  }

  public static String getResult2(String inputStr)
  {
    System.out.println("=======加密前的数据:"+inputStr);
     String path=Tools.getClassPath();
     String fileSource=path+"/file/HMAC_key.txt";
     String key=null;;
    try {
       /*将密钥从文件中读取*/
       key=Tools.ReadMyFile(fileSource);
       System.out.println("getResult2密钥:===" + key); 
    } catch (Exception e1) {
      e1.printStackTrace();}
    String result=null;
    try {
      byte[] inputData = inputStr.getBytes(); 
      /*对数据进行加密*/
      result= HMAC.encryptHMAC(inputData, key);
      System.out.println("HMAC加密后:===" + result); 
    } catch (Exception e) {e.printStackTrace();} 
    return result.toString();
  }

  public static void main(String args[])
  {
    try {
       String inputStr = "简单加密"; 
       /*使用同一密钥:对数据进行加密:查看两次加密的结果是否一样*/
       getResult1(inputStr); 
       getResult2(inputStr);

    } catch (Exception e) {
      e.printStackTrace();
    }

  }

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多Java 四种基本加密算法相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn