[C++] 如何使用 Crypto++

2024 年 4 月 10 日 星期三(已编辑)
/ ,
9

阅读此文章之前,你可能需要首先阅读以下的文章才能更好的理解上下文。

本文使用环境

系统:windows 11
开发环境: vs2010

Crypto++ 功能介绍

Crypto 库是一个用c 编写的免费的密码类库,包括密码,消息认证代码,单向哈希函数,公钥密码系统,密钥协议方案和压缩压缩。

下载

官方下载地址

编译工程

  1. 下载解压后是一个工程目录,打开cryptest.sln工程(本文介绍静态库的编译和使用)
工程名说明
cryptdll生成cryptopp.dll动态库
dlltest测试cryptopp.dll
cryptlib生成cryptlib.lib静态库
cryptest测试cryptlib
  1. 构建 cryptlib 工程(注意和使用的目标工程相同的配置项,如:字符集、运行库等)
  2. 新建include文件和lib文件夹-在include文件夹下建立cryptopp目录。
  3. 将工程目录下所有.h的文件复制到include-cryptopp中
  4. 将构建后的cryptlib.lib(通常在工程Output下) 复制到 lib中

使用

  1. 进入使用的工程目录,将编译好的include 和 lib 文件夹,合并到项目中。
  2. 在vs中右键项目属性进行下面的调整(注意调整的环境和平台)
选项卡调整内容
属性配置-VC++目录-包含目录$(ProjectDir)\include;
属性配置-VC++目录-库目录$(ProjectDir)\lib;
属性配置-链接器-输入-附加依赖项cryptlib.lib;
  1. 自此完成配置

测试

#include <iostream>
#include <cryptopp/sha.h>
#include <cryptopp/hex.h>
std::string sha256(const std::string& message) {
    CryptoPP::SHA256 hash;
    std::string digest;
    CryptoPP::StringSource(message, true,
        new CryptoPP::HashFilter(hash,
            new CryptoPP::HexEncoder(
                new CryptoPP::StringSink(digest)
            )
        )
    );
    return digest;
}
int main() {
    std::string message = "Hello, world!";
    std::string hash = sha256(message);
    std::cout << "SHA256 Hash: " << hash << std::endl;
    return 0;
}
  • Loading...
  • Loading...
  • Loading...
  • Loading...
  • Loading...