MD5 and SHA1 encryption examples in Android development

Source: Internet
Author: User
Tags md5 md5 encryption sha1 sha1 encryption stringbuffer


First, let's share the functions of MD5 and SHA1 encryption.

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 Encryption Instance
public static string Encrypttosha (string info) {
byte[] Digesta = null;
try {
Get a SHA-1 message digest
MessageDigest alga = messagedigest.getinstance ("SHA-1");
Add information to calculate a summary
Alga.update (Info.getbytes ());
Get the summary
Digesta = Alga.digest ();
catch (NoSuchAlgorithmException e) {
E.printstacktrace ();
}
Convert a summary to 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.