Android MD5 and SHA1 encryption instances

Source: Internet
Author: User
Tags sha1 encryption

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;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.