分享

HMAC_SHA1和SHA1的区别

 java_laq小馆 2014-02-28

HMAC_SHA1和SHA1的区别

1577人阅读 评论(2) 收藏 举报

一直以为HMAC_SHA1和SHA1没有任何区别,直到现在才发现它俩不是完全一样的。

HMAC的百度百科解释:

“HMAC是密钥相关的哈希运算消息认证码(Hash-based Message Authentication Code),HMAC运算利用哈希算法,以一个密钥和一个消息为输入,生成一个消息摘要作为输出。”

可以看出,HMAC是需要一个密钥的。所以,HMAC_SHA1也是需要一个密钥的,而SHA1不需要。

以下是两种算法在java中的实现:

如下方法是使用sha1计算一个文件的摘要,不需要密钥,有点类似于md5,注意这句:

  1. MessageDigest.getInstance("SHA-1"); //传的是SHA-1  
  1. public static String sha1Digest(String filename) {  
  2.     InputStream fis = null;  
  3.     byte[] buffer = new byte[Constants.BUFFER_SIZE];  
  4.     int numRead = 0;  
  5.     MessageDigest sha1;  
  6.     try {  
  7.         fis = new FileInputStream(filename);  
  8.         sha1 = MessageDigest.getInstance("SHA-1");  
  9.         while ((numRead = fis.read(buffer)) > 0) {  
  10.             sha1.update(buffer, 0, numRead);  
  11.         }  
  12.         return toHexString(sha1.digest());  
  13.     } catch (Exception e) {  
  14.         System.out.println("error");  
  15.         return null;  
  16.     } finally {  
  17.         try {  
  18.             if (fis != null) {  
  19.                 fis.close();  
  20.             }  
  21.         } catch (IOException e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.     }  
  25. }  

如下方法是使用hmacsha1计算字符串的签名,需要一个密钥,一般用来作服务器端的签名验证。
  1. Constants.APP_SECRET  

注意这句:

  1. Mac.getInstance("HmacSHA1");//传的是HmacSHA1  
  1. private static byte[] getHmacSHA1(String src)  
  2.         throws NoSuchAlgorithmException, UnsupportedEncodingException,  
  3.         InvalidKeyException {  
  4.     Mac mac = Mac.getInstance("HmacSHA1");  
  5.     SecretKeySpec secret = new SecretKeySpec(  
  6.             Constants.APP_SECRET.getBytes("UTF-8"), mac.getAlgorithm());  
  7.     mac.init(secret);  
  8.     return mac.doFinal(src.getBytes());  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多