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

Android 字串轉 MD5 的實作與常用字串處理技巧

編輯:關於 Android 程式設計

MD5 是常見的字串摘要應用,例如登入密碼雜湊、資料校驗等。本文提供一個可直接使用的 StringUtils 工具類,把任意字串轉成 32 位元十六進位的 MD5 值,並示範位元組陣列與十六進位字串互轉的寫法。

實作重點在於:先用 MessageDigest 取得 MD5 摘要的位元組,再逐位元組轉成兩位十六進位字串拼接,最後查表對應 0–f 的字元。

public class StringUtils { public static String MD5Encode(String origin) { String resultString = null; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance("MD5"); resultString = byteArrayToHexString(md.digest(resultString.getBytes())); } catch (Exception ex) { } return resultString; } public static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for (int i = 0; i < b.length; i++) { resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (n < 0) n = 256 + n; int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}; }

使用時只要呼叫 StringUtils.MD5Encode("要加密的字串") 就能得到對應的 MD5 值。需要留意的是,MD5 已不適合存放敏感憑證,正式環境建議改用加鹽 SHA-256 等更安全的雜湊方式。

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