Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中 MD5 加密演算法的實作與應用解析

編輯:關於 Android 程式設計

本文透過實例,帶大家了解如何在 Android 平台上實作 MD5 加密演算法。

好消息是,Android 上的 MD5 加密寫法與傳統的 J2SE 平台幾乎完全相同,因為 Android 平台同樣支援 java.security.MessageDigest 這個套件,直接沿用即可。

演算法簽名如下:

 package com.tencent.utils; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 對外提供getMD5(String)方法 * @author randyjia * */ public class MD5 { public static String getMD5(String val) throws NoSuchAlgorithmException{ MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(val.getBytes()); byte[] m = md5.digest();//加密 return getString(m); } private static String getString(byte[] b){ StringBuffer sb = new StringBuffer(); for(int i = 0; i < b.length; i ++){ sb.append(b[i]); } return sb.toString(); } } 

這段程式的作用很直觀:傳入一段需要加密的文字,就能得到對應的加密結果。不過更實用的版本通常會把位元組陣列轉成十六進位字串,並可視需求截取部分字元作為摘要。以下是一個較完整的寫法:

 /* * MD5加密 */ private String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } //16位加密,從第9位到25位 return md5StrBuff.substring(8, 24).toString().toUpperCase(); } 

補充一個常見的 MD5 字串加密示例:將輸入的字串進行 MD5 運算,回傳的其實就是該字串的「訊息摘要」(Message Digest)。

 public static String md5(String string) { byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Huh, MD5 should be supported?", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh, UTF-8 should be supported?", e); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } 

需要提醒的是,MD5 屬於單向雜湊,並非可逆的加密,因此適合應用在密碼摘要比對等場景,而非需要還原的資料保護。希望本文所述能對大家的 Android 程式設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved