Home  >  Article  >  Java  >  Share several encryption algorithms commonly used in Java (four types)

Share several encryption algorithms commonly used in Java (four types)

高洛峰
高洛峰Original
2017-01-24 11:35:251178browse

Symmetric encryption algorithm is an earlier encryption algorithm with mature technology. In the symmetric encryption algorithm, the data sender processes the plaintext (original data) and encryption key (mi yue) together with a special encryption algorithm, turning them into complex encrypted ciphertext and sending them out. After the recipient receives the ciphertext, if he wants to decipher the original text, he needs to use the key used for encryption and the inverse algorithm of the same algorithm to decrypt the ciphertext in order to restore it to readable plaintext. In the symmetric encryption algorithm, only one key is used. Both the sender and the receiver use this key to encrypt and decrypt the data. This requires the decryptor to know the encryption key in advance.

Simple java encryption algorithms are:

BASE Strictly speaking, it is an encoding format, not an encryption algorithm
MD (Message Digest algorithm, message digest algorithm)
SHA( Secure Hash Algorithm, secure hash algorithm)
HMAC (Hash Message Authentication Code, hash message authentication code)

The first one. BASE

Base is the most popular one on the network One of the common encoding methods used to transmit Bit byte code, you can check RFC~RFC, which has detailed specifications of MIME. Base encoding can be used to convey longer identification information in an HTTP environment. For example, in the Java Persistence system Hibernate, Base is used to encode a long unique identifier (usually a -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, Base 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.BASEDecoder;
import sun.misc.BASEEncoder;
/*
BASE的加密解密是双向的,可以求反解.
BASEEncoder和BASEDecoder是非官方JDK实现类。虽然可以在JDK里能找到并使用,但是在API里查不到。
JRE 中 sun 和 com.sun 开头包的类都是未被文档化的,他们属于 java, javax 类库的基础,其中的实现大多数与底层平台有关,
一般来说是不推荐使用的。
BASE 严格地说,属于编码格式,而非加密算法
主要就是BASEEncoder、BASEDecoder两个类,我们只需要知道使用对应的方法即可。
另,BASE加密后产生的字节位数是的倍数,如果不够位数以=符号填充。
BASE
按照RFC的定义,Base被定义为:Base内容传送编码被设计用来把任意序列的位字节描述为一种不易被人直接识别的形式。
(The Base Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.)
常见于邮件、http加密,截取http信息,你就会发现登录操作的用户名、密码字段通过BASE加密的。
*/
public class BASE {
  /**
   * BASE解密
   *
   * @param key
   * @return
   * @throws Exception
   */
  public static byte[] decryptBASE(String key) throws Exception {
    return (new BASEDecoder()).decodeBuffer(key);
  }
  /**
   * BASE加密
   *
   * @param key
   * @return
   * @throws Exception
   */
  public static String encryptBASE(byte[] key) throws Exception {
    return (new BASEEncoder()).encodeBuffer(key);
  }
  public static void main(String[] args) {
   String str="";
    try {
    String result= BASE.encryptBASE(str.getBytes());
     System.out.println("result=====加密数据=========="+result);
     byte result[]= BASE.decryptBASE(result);
     String str=new String(result);
     System.out.println("str========解密数据========"+str);
  } catch (Exception e) {
    e.printStackTrace();
  }
  }
}

The second type. MD

MD is Message-Digest Algorithm (information-digest algorithm), 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). MD has been 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 MD are MD, MD and MD. Widely used in encryption and decryption technology, often used for file verification. check? No matter how big the file is, a unique MD value can be generated after MD. For example, the current ISO calibration is MD calibration. how to use? Of course, the MD value is generated after ISO is passed through MD. Generally, friends who have downloaded linux-ISO have seen the MD 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;
/*
MD(Message Digest algorithm ,信息摘要算法)
通常我们不直接使用上述MD加密。通常将MD产生的字节数组交给BASE再加密一把,得到相应的字符串
Digest:汇编
*/
public class MD {
  public static final String KEY_MD = "MD";
  public static String getResult(String inputStr)
  {
    System.out.println("=======加密前的数据:"+inputStr);
    BigInteger bigInteger=null;
    try {
     MessageDigest md = MessageDigest.getInstance(KEY_MD);
     byte[] inputData = inputStr.getBytes();
     md.update(inputData);
     bigInteger = new BigInteger(md.digest());
    } catch (Exception e) {e.printStackTrace();}
    System.out.println("MD加密后:" + bigInteger.toString());
    return bigInteger.toString();
  }
  public static void main(String args[])
  {
    try {
       String inputStr = "简单加密";
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

MD algorithm has the following characteristics:

, Compressibility: data of any length can be calculated The MD value lengths are all fixed.
. Easy to calculate: It is easy to calculate the MD value from the original data.
. Anti-modification: If any changes are made to the original data, even if only a single byte is modified, the resulting MD value will be very different.
, Weak anti-collision: Knowing the original data and its MD value, it is very difficult to find data with the same MD value (ie, forged data).
, Strong anti-collision: It is very difficult to find two different data so that they have the same MD value.

The function of MD is to allow large-capacity information to be "compressed" into a confidential format before signing the private key with digital signature software (that is, converting a byte string of any length into a certain length of sixteen hexadecimal digit string). In addition to MD, the more famous ones include sha-, RIPEMD and Haval.

The third type.SHA

Secure Hash Algorithm is mainly applicable to the Digital Signature Algorithm DSA defined in the Digital Signature Standard DSS. . For messages less than ^ bits in length, SHA produces a one-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与MD通过碰撞法都被破解了,
但是SHA仍然是公认的安全加密算法,较之MD更为安全*/
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());
    } catch (Exception e) {e.printStackTrace();}
    return sha.toString();
  }
  public static void main(String args[])
  {
    try {
       String inputStr = "简单加密";
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Comparison between SHA- and MD

Because both are exported by MD, SHA- and MD are very similar to each other. Correspondingly, their strengths and other characteristics are similar, but there are the following differences:

Security against brute force attacks: The most significant and important difference is that the SHA-digest is longer than the MD digest. Using brute force techniques, the difficulty of generating any message whose digest is equal to a given message digest is an operation of the order of magnitude for MD, and an operation of the order of magnitude for SHA-. This way, SHA- has greater strength against brute force attacks.

Security against cryptanalysis: Due to the design of MD, it is vulnerable to cryptanalysis attacks, while SHA- appears to be less vulnerable to such attacks.

Speed: SHA- runs slower than MD on the same hardware.

The fourth type.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 = "HmacMD";
  /**
   * 初始化HMAC密钥
   *
   * @return
   * @throws Exception
   */
  public static String initMacKey() throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
    SecretKey secretKey = keyGenerator.generateKey();
    return BASE.encryptBASE(secretKey.getEncoded());
  }
  /**
   * HMAC加密 :主要方法
   *
   * @param data
   * @param key
   * @return
   * @throws Exception
   */
  public static String encryptHMAC(byte[] data, String key) throws Exception {
    SecretKey secretKey = new SecretKeySpec(BASE.decryptBASE(key), KEY_MAC);
    Mac mac = Mac.getInstance(secretKey.getAlgorithm());
    mac.init(secretKey);
    return new String(mac.doFinal(data));
  }
  public static String getResult(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 getResult(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("getResult密钥:===" + key);
    } catch (Exception e) {
      e.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 = "简单加密";
       /*使用同一密钥:对数据进行加密:查看两次加密的结果是否一样*/
       getResult(inputStr);
       getResult(inputStr);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

   

以上内容是小编给大家分享的Java常用几种加密算法(四种),希望大家喜欢。

更多分享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