4.10.6 SHA1摘要算法
uuid的名字生成器使用了SHA1摘要算法,这是一个很重要的密码学算法,可以将任意长度的文本压缩成一个只有20字节(160位)的独一无二的摘要,被广泛地应用于防篡改、身份鉴定等安全认证领域。
sha1算法位于名字空间boost::uuids::detail,使用时需要包含头文件<boost/ uuid/sha1.hpp>,它的类摘要如下。
- class sha1
- {
- public:
- typedef unsigned int(&digest_type)[5];
- sha1();
- void reset();
-
- void process_byte(unsigned char byte);
- void process_block(void const* bytes_begin, void const* bytes_end);
- void process_bytes(void const* buffer, size_t byte_count);
-
- void get_digest(digest_type digest);
- };
sha1类的用法很简单,使用成员函数process_byte()、process_block()和process_bytes()以不同的方式把数据"喂"给sha1对象,当输入所有数据后用get_digest()获得计算出的摘要值。
示范sha1用法的代码如下:
- #include <boost/uuid/sha1.hpp>
- using namespace boost::uuids::detail;
- int main()
- {
- sha1 sha; //sha1对象
-
- char *szMsg = "a short message"; //用于摘要的消息
- sha.process_byte(0x10); //处理一个字节
- sha.process_bytes(szMsg, strlen(szMsg)); //处理多个字节
- sha.process_block(szMsg, szMsg + strlen(szMsg));
-
- unsigned int digest[5]; //摘要的返回值
- sha.get_digest(digest); //获得摘要
- for (int i = 0; i < 5 ; ++i)
- {
- cout << hex << digest[i]; //16进制输出
- }
- }