java:
1 public static String SHA1(String decript) { 2 try { 3 MessageDigest digest = MessageDigest.getInstance("SHA-1"); 4 digest.update(decript.getBytes("UTF-8")); 5 byte[] messageDigest = digest.digest(); 6 StringBuilder hexString = new StringBuilder(); 7 for (byte message : messageDigest) { 8 String shaHex = Integer.toHexString(message & 0xFF); 9 if (shaHex.length() < 2) 10 hexString.append(0); 11 12 hexString.append(shaHex); 13 } 14 return hexString.toString().toLowerCase(); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 return ""; 19 }
c# :
1 /// <summary> 2 /// SHA1 加密,返回大写字符串 3 /// </summary> 4 /// <param name="content">需要加密字符串</param> 5 /// <returns>返回40位UTF8 大写</returns> 6 public static string SHA1(string content) 7 { 8 return SHA1(content, Encoding.UTF8).ToLower(); 9 } 10 /// <summary> 11 /// SHA1 加密,返回大写字符串 12 /// </summary> 13 /// <param name="content">需要加密字符串</param> 14 /// <param name="encode">指定加密编码</param> 15 /// <returns>返回40位大写字符串</returns> 16 public static string SHA1(string content, Encoding encode) 17 { 18 try 19 { 20 SHA1 sha1 = new SHA1CryptoServiceProvider(); 21 byte[] bytes_in = encode.GetBytes(content); 22 byte[] bytes_out = sha1.ComputeHash(bytes_in); 23 sha1.Dispose(); 24 25 var sb = new StringBuilder(); 26 foreach (byte b in bytes_out) 27 { 28 sb.Append(b.ToString("x2")); 29 } 30 //所有字符转为小写 31 return sb.ToString().ToLower(); 32 } 33 catch (Exception ex) 34 { 35 throw new Exception("SHA1加密出错:" + ex.Message); 36 } 37 }