您的位置:首页 > 其它

Andriod之SHA-256,MD5加密字符串

2016-01-07 15:30 225 查看
package com.example.testsha;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class StringEncrypt {

/**

* 对字符串加密,加密算法使用MD5,SHA-1,SHA-256,默认使用SHA-256

*

* @param strSrc 要加密的字符串

* @param encName 加密类型

* @return

*/

public static String Encrypt(String strSrc, String encName) {

MessageDigest md = null;

String strDes = null;

byte[] bt = strSrc.getBytes();

try {

if (encName == null || encName.equals("")) {

encName = "SHA-256";

}

md = MessageDigest.getInstance(encName);

md.update(bt);

strDes = bytes2Hex(md.digest()); // to HexString

} catch (NoSuchAlgorithmException e) {

return null;

}

return strDes;

}

public static String bytes2Hex(byte[] bts) {

String des = "";

String tmp = null;

for (int i = 0; i < bts.length; i++) {

tmp = (Integer.toHexString(bts[i] & 0xFF));

if (tmp.length() == 1) {

des += "0";

}

des += tmp;

}

return des;

}

}

/**

* 将字符串转成MD5值

* @param string

* @return

*/

public static String stringToMD5(String string) {

byte[] hash;

try {

hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

return null;

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

return null;

}

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

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: