首页 > 代码库 > Java之 SHA1 与MD5加密

Java之 SHA1 与MD5加密

一、SHA1加密 

 1 /* 2      * SHA1加密,结果为小写 3      */ 4     public static String SHA1(String decript) { 5         try { 6             MessageDigest digest = java.security.MessageDigest 7                     .getInstance("SHA-1"); 8             digest.update(decript.getBytes()); 9             byte messageDigest[] = digest.digest();10             // Create Hex String11             StringBuffer hexString = new StringBuffer();12             // 字节数组转换为 十六进制 数13             for (int i = 0; i < messageDigest.length; i++) {14                 String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);15                 if (shaHex.length() < 2) {16                     hexString.append(0);17                 }18                 hexString.append(shaHex);19             }20             return hexString.toString();21 22         } catch (NoSuchAlgorithmException e) {23             e.printStackTrace();24         }25         return "";26     }

二、MD5加密

 1 /** 2      * MD5加密 3      */ 4     public String md5s(String plainText) { 5         String str = ""; 6         try { 7             MessageDigest md = MessageDigest.getInstance("MD5"); 8             md.update(plainText.getBytes()); 9             byte b[] = md.digest();10 11             int i;12 13             StringBuffer buf = new StringBuffer("");14             for (int offset = 0; offset < b.length; offset++) {15                 i = b[offset];16                 if (i < 0)17                     i += 256;18                 if (i < 16)19                     buf.append("0");20                 buf.append(Integer.toHexString(i));21             }22             str = buf.toString();23             System.out.println("result: " + buf.toString());// 32位的加密24         } catch (NoSuchAlgorithmException e) {25             e.printStackTrace();26         }27         return str;28     }