MainActivity如下:
package cc.testmd5; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * 利用MD5判断两个字符串是否相同 * * MD5:消息摘要算法(Message Digest Algorithm) * MD5是常用的加密算法,常用于校验信息完整或者两次消息是否一致 * * 备注说明: * 1 hexadecimal 十六进制 * 2 注意方法:String java.lang.Integer.toHexString(int i) * Converts the specified integer into its hexadecimal string representation. * The returned string is a concatenation of characters from '0' to '9' and 'a' to 'f'. * 将整型转换为十六进制 * */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String firstMD5=getMD5("NBA"); String secondMD5=getMD5("NBA"); System.out.println("firstMD5="+firstMD5+",firstMD5.length()="+firstMD5.length()); System.out.println("secondMD5="+secondMD5+",secondMD5.length()="+secondMD5.length()); } private String getMD5(String string) { try { // Create MD5 Hash MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(string.getBytes()); byte messageDigestByteArray[] = messageDigest.digest(); if (messageDigestByteArray == null || messageDigestByteArray.length == 0) { return ""; } // Create hexadecimal String StringBuffer hexadecimalStringBuffer = new StringBuffer(); int length = messageDigestByteArray.length; for (int i = 0; i < length; i++){ hexadecimalStringBuffer.append(Integer.toHexString(0xFF & messageDigestByteArray[i])); } return hexadecimalStringBuffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试Android的MD5码" android:layout_centerInParent="true" /> </RelativeLayout>
时间: 2024-09-27 14:33:40