C++ 使用 SM4 加密字符串并 Base64 编码输出 (不使用密码库)

本文提供 C++ 代码示例,使用 SM4 加密算法和 Base64 编码算法对字符串进行加密和 Base64 编码,并封装成类。代码示例不依赖第三方密码库,并提供 SM4 和 Base64 算法的源码。

#include <iostream>
#include <cstring>
#include <string>
#include <cstdint>

// SM4加密算法源码
#include "sm4.h"

// Base64编码算法源码
#include "base64.h"

class SM4Encryptor {
public:
    SM4Encryptor(const std::string& key) {
        std::memcpy(m_key, key.c_str(), key.size());
        m_sm4.set_key(m_key);
    }

    std::string encrypt(const std::string& plaintext) {
        size_t length = plaintext.size();
        uint8_t* encrypted = new uint8_t[length];
        m_sm4.encrypt(plaintext.c_str(), length, encrypted);

        std::string base64Encoded = base64_encode(encrypted, length);
        delete[] encrypted;

        return base64Encoded;
    }

    std::string decrypt(const std::string& ciphertext) {
        size_t length;
        uint8_t* decoded = base64_decode(ciphertext, length);
        uint8_t* decrypted = new uint8_t[length];
        m_sm4.decrypt(decoded, length, decrypted);

        std::string plaintext(reinterpret_cast<char*>(decrypted), length);
        delete[] decrypted;
        delete[] decoded;

        return plaintext;
    }

private:
    SM4 m_sm4;
    uint8_t m_key[16];
};

int main() {
    std::string key = "0123456789abcdef"; // 16字节的密钥
    std::string plaintext = "123456";

    SM4Encryptor encryptor(key);
    std::string ciphertext = encryptor.encrypt(plaintext);

    std::cout << "Ciphertext: " << ciphertext << std::endl;

    std::string decryptedText = encryptor.decrypt(ciphertext);
    std::cout << "Decrypted text: " << decryptedText << std::endl;

    return 0;
}

你需要将 SM4 加密算法的源码放置在名为 sm4.h 的头文件中,Base64 编码算法的源码放置在名为 base64.h 的头文件中。

C++ 使用 SM4 加密字符串并 Base64 编码输出 (不使用密码库)

原文地址: https://www.cveoy.top/t/topic/pUBY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录