Android編程之MD5密碼編譯演算法執行個體分析_Android

來源:互聯網
上載者:User

本文執行個體分析了Android編程之MD5密碼編譯演算法。分享給大家供大家參考,具體如下:

Android MD5加密算與J2SE平台一模一樣,因為Android 平台支援 java.security.MessageDigest這個包。實際上與J2SE平台一模一樣。

演算法簽名:

複製代碼 代碼如下:
String getMD5(String val) throws NoSuchAlgorithmException

輸入一個String(需要加密的文本),得到一個加密輸出String(加密後的文本)

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();}

補充:Android MD5加密字串樣本

這裡將字串進行MD5加密,返回加密後的字串(實際上是該字串的報文摘要)。

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();}

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.