package com.example.myapi.md5;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import com.example.myapi.R;import android.app.Activity;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MD5Activity extends Activity implements OnClickListener{ private Button btn_md5; protected void onCreate(android.os.Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.md5); btn_md5 = (Button)findViewById(R.id.md5_btn); btn_md5.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.md5_btn: Toast.makeText(this, getMD5Str("123456"), Toast.LENGTH_LONG).show();// getMD5Str("123456"); Log.e("md5", getMD5Str("123456")); break; } }; /** * MD5加密 * @param str 转换前的字符串 * @return 转换后的字符串 */ private String getMD5Str(String str) { MessageDigest messageDigest = null; try { //返回实现指定摘要算法的 MessageDigest对象 例如:MD5、SHA算法 messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); //重置MessageDigest对象 messageDigest.update(str.getBytes("UTF-8"));//指定byte数组更新 } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //完成哈希算法,完成后 MessageDigest对象被设为初始状态,而且该方法只能调用一次 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(); return md5StrBuff.toString(); } }