栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android编程之MD5加密算法实例分析

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android编程之MD5加密算法实例分析

本文实例分析了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;
 
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();
}
}

结束

 
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程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/163972.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号