AndroidプログラミングのMD 5暗号化アルゴリズムの実例分析
本論文の例はAndroidプログラミングのMD 5暗号化アルゴリズムを解析した。皆さんに参考にしてあげます。具体的には以下の通りです。
Android MD 5暗号化はJ 2 SEプラットフォームと同じです。Androidプラットフォームはjava.security.Message Digestというパッケージをサポートしています。実はJ 2 SEプラットフォームと同じです。
アルゴリズムの署名:
ここで文字列をMD 5に暗号化し、暗号化された文字列を返します。
Android MD 5暗号化はJ 2 SEプラットフォームと同じです。Androidプラットフォームはjava.security.Message Digestというパッケージをサポートしています。実はJ 2 SEプラットフォームと同じです。
アルゴリズムの署名:
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 MD 5暗号化文字列例ここで文字列をMD 5に暗号化し、暗号化された文字列を返します。
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プログラムの設計に役に立ちます。