安卓下如何进行MD5加密以及SHA1加密

这是MD5加密的方法

public class ToMd {

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));  //安卓中自带的加密
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        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();        //16进制转换
    }

}

这是SHA1加密的方法

public class Sha1 {
 
    public static String getsha1(String str) {
      if(str==null){
          return null;
      }else {
        try {
            MessageDigest messageDigest=MessageDigest.getInstance("SHA-1");  
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    return null;
    }

    private static String getFormattedText(byte[] bytes) {
        String des="";
        String tmp=null;
        for (int i=0;i<bytes.length;i++) {
                   tmp=(Integer.toHexString(bytes[i] & 0xFF));
                   if (tmp.length()==1) {
                       des+="0";
                   }
                   des+=tmp;
               }
               return des;
    }
}

这两个方法都是用这个方法     MessageDigest messageDigest=MessageDigest.getInstance("SHA-1");        messageDigest.update(str.getBytes());

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

     得到相应的字节流 然后进行16进制转换

你可能感兴趣的:(MD5,加密,安卓,SHA1)