public static final String encodeBy32BitMD5(String source) {
return encrypt(source, false);
}
static final String encrypt(String source, boolean is16bit) {
if (TextUtils.isEmpty(source)) {
return null;
}
String encryptedStr = null;
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
encryptedStr = convertToHexString(digester.digest(source
.getBytes("utf-8")));
if (is16bit) {
encryptedStr = encryptedStr.substring(8, 24);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encryptedStr;
}
static final String convertToHexString(byte data[])
{
/*下面这种算法导致只有31位存在缺陷*/
// StringBuffer strBuffer = new StringBuffer();
//
// for (int i = 0; i < data.length; i++) {
//
// strBuffer.append(Integer.toHexString(0xff & data[i]));
// }
// return strBuffer.toString();
/********************此处才是正解*****************/
int i;
StringBuffer buf = new StringBuffer();
for (int offset = 0; offset < data.length; offset++)
{
i = data[offset];
if (i < 0)
{
i += 256;
}
if (i < 16)
{
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
return buf.toString();
}
附带小常识:
string.substring(int startIndex, int endIndex) 的返回值为 startIndex <= 返回值 < endIndex,因此返回字符串的:length = endIndex - startIndex
即string"0123456".substring(3,6) 结果为:345