Android MD5 and SHA1 encryption instances
// After searching for a long time, many encryption results on the Internet were incorrect. Finally, Baidu added my own modification to solve the problem.
Public class MD5 {
Private static String key = "a6U & 1 $ Ip [Jr/sed] Rfvn = O> Mz +} lXN * %-gLcGD | 0 ";
// MD5 encryption instance
Public static String getMD5 (String str) throws NoSuchAlgorithmException {
MessageDigest md5 = null;
Try {
Md5 = MessageDigest. getInstance ("MD5 ");
} Catch (Exception e ){
E. printStackTrace ();
Return "";
}
Char [] charArray = str. toCharArray ();
Byte [] byteArray = new byte [charArray. length];
For (int I = 0; I <charArray. length; I ++ ){
ByteArray [I] = (byte) charArray [I];
}
Byte [] md5Bytes = md5.digest (byteArray );
StringBuffer hexValue = new StringBuffer ();
For (int I = 0; I <md5Bytes. length; I ++ ){
Int val = (int) md5Bytes [I]) & 0xff;
If (val <16 ){
HexValue. append ("0 ");
}
HexValue. append (Integer. toHexString (val ));
}
Return hexValue. toString ();
}
Public static String byte2hex (byte [] B ){
String hs = "";
String stmp = "";
For (int n = 0; n <B. length; n ++ ){
Stmp = (java. lang. Integer. toHexString (B [n] & 0XFF ));
If (stmp. length () = 1 ){
Hs = hs + "0" + stmp;
} Else {
Hs = hs + stmp;
}
}
Return hs;
}
// SHA1 encrypted instance
Public static String encryptToSHA (String info ){
Byte [] digesta = null;
Try {
// Obtain a message digest for SHA-1.
MessageDigest alga = MessageDigest. getInstance ("SHA-1 ");
// Add the information for calculating the summary
Alga. update (info. getBytes ());
// Obtain the summary
Digesta = alga. digest ();
} Catch (NoSuchAlgorithmException e ){
E. printStackTrace ();
}
// Convert the Digest into a string
String rs = byte2hex (digesta );
Return rs + key;
}
}