设为首页 加入收藏

TOP

4.10.6 SHA1摘要算法
2013-10-07 15:02:12 来源: 作者: 【 】 浏览:75
Tags:4.10.6 SHA1 摘要 算法

4.10.6  SHA1摘要算法

uuid的名字生成器使用了SHA1摘要算法,这是一个很重要的密码学算法,可以将任意长度的文本压缩成一个只有20字节(160位)的独一无二的摘要,被广泛地应用于防篡改、身份鉴定等安全认证领域。

sha1算法位于名字空间boost::uuids::detail,使用时需要包含头文件<boost/ uuid/sha1.hpp>,它的类摘要如下。

  1. class sha1  
  2. {  
  3. public:  
  4.     typedef unsigned int(&digest_type)[5];  
  5.     sha1();  
  6.     void reset();  
  7.  
  8.     void process_byte(unsigned char byte);  
  9.     void process_block(void const* bytes_begin, void const* bytes_end);  
  10.     void process_bytes(void const* buffer, size_t byte_count);  
  11.  
  12.     void get_digest(digest_type digest);  
  13. };  

sha1类的用法很简单,使用成员函数process_byte()、process_block()和process_bytes()以不同的方式把数据"喂"给sha1对象,当输入所有数据后用get_digest()获得计算出的摘要值。

示范sha1用法的代码如下:

  1. #include <boost/uuid/sha1.hpp> 
  2. using namespace boost::uuids::detail;  
  3. int main()  
  4. {  
  5.     sha1 sha;                                       //sha1对象  
  6.  
  7.     char *szMsg = "a short message";                //用于摘要的消息  
  8.     sha.process_byte(0x10);                         //处理一个字节  
  9.     sha.process_bytes(szMsg, strlen(szMsg));        //处理多个字节  
  10.     sha.process_block(szMsg, szMsg + strlen(szMsg));  
  11.  
  12.     unsigned int digest[5];                         //摘要的返回值  
  13.     sha.get_digest(digest);                         //获得摘要  
  14.     for (int i = 0; i < 5 ; ++i)  
  15.     {  
  16.         cout << hex << digest[i];                   //16进制输出  
  17.     }  
  18. }  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇4.11.1 BOOST_STRINGIZE 下一篇4.10.5 与字符串的转换

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: