Demo:编码与加密
展示 Base64、SHA-1 兼容用途,以及返回实际长度的 AES-256-CBC 接口。
1. 示例内容
示例中的关键调用使用中文注释,并与仓库源码、CMake 目标和当前 API 保持一致。
2. 构建与运行
cmake --build build --target sttnet_crypto_encoding --parallel
./build/examples/sttnet_crypto_encoding3. 运行结果
./build/examples/sttnet_crypto_encoding预期:输出 Base64 编码和还原结果、SHA-1 十六进制文本、密文字节数及解密后的原文。
4. 完整源码
#include <sttnet.h>
#include <array>
#include <iostream>
#include <string>
#include <vector>
int main()
{
using stt::data::CryptoUtil;
using stt::data::EncodingUtil;
const std::string message="STTNet utility demo";
// Base64 是可逆编码,不是加密。非法编码输入会返回空字符串;
// 空输入同样返回空字符串。
const std::string base64=EncodingUtil::base64_encode(message);
std::cout << "base64: " << base64 << '\n';
std::cout << "decoded: " << EncodingUtil::base64_decode(base64) << '\n';
// SHA-1 仍可用于 RFC 6455 等协议兼容场景。
// SHA-1 仅用于兼容场景,不适用于密码存储、签名或新的安全设计。
std::string sha1Hex;
CryptoUtil::sha11(message,sha1Hex);
std::cout << "sha1: " << sha1Hex << '\n';
// AES-256-CBC 需要 32 字节密钥和 16 字节 IV。这里使用固定值只是为了
// 固定 IV 只用于复现实验;生产环境的 IV 需要不可预测,CBC 密文还需要单独
// 进行完整性认证,或者直接改用 AEAD 模式。
const std::array<unsigned char,32> key={
'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',
'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
const std::array<unsigned char,16> iv={
'a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9'};
// 为 PKCS#7 补位预留空间,并读取重载接口返回的实际输出长度。
// 不能靠猜测长度重建二进制结果。
std::vector<unsigned char> cipher(message.size()+EVP_MAX_BLOCK_LENGTH);
std::size_t cipherLength=0;
if(!CryptoUtil::encryptSymmetric(
reinterpret_cast<const unsigned char*>(message.data()),message.size(),
key.data(),iv.data(),cipher.data(),cipherLength))
return 1;
std::vector<unsigned char> plain(cipherLength);
std::size_t plainLength=0;
if(!CryptoUtil::decryptSymmetric(cipher.data(),cipherLength,key.data(),iv.data(),
plain.data(),plainLength))
return 2;
std::cout << "cipher bytes: " << cipherLength << '\n';
std::cout << "decrypted: "
<< std::string(reinterpret_cast<char*>(plain.data()),plainLength)
<< '\n';
return 0;
}