常用的加密算法---數字摘要

數字摘要:

數字摘要也稱爲消息摘要,它是一個唯一對應一個消息或文本的固定長度的值,它是一個單向


Hash函數對消息進行計算產生的。



摘要生成的過程:待摘要串-----> Hash函數-----> 摘要


消息摘要的特點:


1.無論輸入的消息多長,計算出來的消息摘要的長度是固定的。例如:MD5 的爲128個比特位,SHA-1的爲


160個比特位;


2.一般只要輸入的消息不同,對其產生的摘要消息也是不相同的,相同的輸入必然會產生相同的摘要消息;


3.由於消息摘要並不包含原文的完整信息,因此只能進行正向的消息摘要,而無法從摘要中恢復出原來的消息


甚至根本不可能找到任何與原信息相關的消息。


1.MD5:

基於java的MD5算法的使用:

c4164c4a-5925-385a-b7bd-438d34474085.jpg

/**

 * 實現MD5的加密

 * 

 * @param con

 *   需要加密的字符串

 * @return

 * @throws Exception

 */

 private static byte[] testMD5(String con) throws Exception {

     MessageDigest md5 = MessageDigest.getInstance("MD5");

     byte[] bytes = md5.digest(con.getBytes("utf-8"));

     return bytes;

 }



2.SHA(摘要的信息長度160位  最安全的散列算法之一):

b8a0cd1d-26d1-3e31-bb9f-5d08e98ec704.jpg

 /**

  *SHA 散列安全算法

  * 

  * @param con 

  *             待加密的字符串

  * @return

  * @throws Exception

  */

  private static byte[] tstSHA1(String con) throws Exception {

     MessageDigest sha = MessageDigest.getInstance("SHA-1");

     byte[] bytes = sha.digest(con.getBytes("utf-8"));

     return bytes;

 }



3.十六進制編碼:

 /**

  * 16進制加密

  * 

  * @param bytes

  * @return

  */

 private static String bytes2hex(byte[] bytes) {

   StringBuilder hex = new StringBuilder();

   for (int i = 0; i < bytes.length; i++) {

      byte b = bytes[i];

      boolean negtive = false;

      if (b < 0) {

        negtive = true;

      }

      int inte = Math.abs(b);

      if (negtive)

      inte = inte | 0x80;

      String temp = Integer.toHexString(inte & 0xFF);

      if (temp.length() == 1) {

        hex.append("0");

      }

      hex.append(temp.toLowerCase());

      }

      return hex.toString();

   }

  /**

   * 16進制解密

   * 

   * @param hex

   * @return

   */

 private static byte[] hex2bytes(String hex) {

   byte[] bytes = new byte[hex.length() / 2];

   for (int i = 0; i < hex.length(); i = i + 2) {

      String subStr = hex.substring(i, i + 2);

      boolean negative = false;

      int inte = Integer.parseInt(subStr, 16);

      if (inte > 127) {

        negative = true;

      }

      if (inte == 128) {

        inte = -128;

      } else if (negative) {

        inte = 0 - (inte & 0x7F);

      }

      byte b = (byte) inte;

      bytes[i / 2] = b;

      }

      return bytes;

  }

4.Base64編碼:

 /**

  * base64 編碼

  * @param base64

  * @return

  * @throws IOException

  */

 private static byte[] base642byte(String base64) throws IOException {

    BASE64Decoder bs = new BASE64Decoder();

    return bs.decodeBuffer(base64); 

  }

 /**

  * base64 解碼

  * @param bytes

  * @return

  */

 private static String byte2base64(byte[] bytes) {

    BASE64Encoder bse = new BASE64Encoder();

    return bse.encode(bytes);

 }


  隨着數據化時代的到來,信息的安全性越來越成爲我們關注的問題,本期博客寫了一些基礎的加密算法,希望對大家有用。其他的加密算法我也會在後期的書寫中逐漸補上。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章