#include <openssl/evp.h>
#include <openssl/rand.h>
#include <iostream>

// 加密函数
void encryptSM4(const unsigned char *plaintext, int plaintextLength, const unsigned char *key, unsigned char *ciphertext, int *ciphertextLength) {
    EVP_CIPHER_CTX *ctx;
    int len;

    // 创建并初始化上下文
    ctx = EVP_CIPHER_CTX_new();
    EVP_EncryptInit_ex(ctx, EVP_sm4_ecb(), NULL, key, NULL);

    // 加密数据
    EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintextLength);
    *ciphertextLength = len;

    // 结束加密过程
    EVP_EncryptFinal_ex(ctx, ciphertext + len, &len);
    *ciphertextLength += len;

    // 释放上下文
    EVP_CIPHER_CTX_free(ctx);
}

// 解密函数
void decryptSM4(const unsigned char *ciphertext, int ciphertextLength, const unsigned char *key, unsigned char *plaintext, int *plaintextLength) {
    EVP_CIPHER_CTX *ctx;
    int len;

    // 创建并初始化上下文
    ctx = EVP_CIPHER_CTX_new();
    EVP_DecryptInit_ex(ctx, EVP_sm4_ecb(), NULL, key, NULL);

    // 解密数据
    EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertextLength);
    *plaintextLength = len;

    // 结束解密过程
    EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
    *plaintextLength += len;

    // 释放上下文
    EVP_CIPHER_CTX_free(ctx);
}

int main() {
    const unsigned char plaintext[] = "Hello, SM4!"; // 明文
    const unsigned char key[] = "0123456789abcdef"; // 128位密钥
    unsigned char ciphertext[256];
    unsigned char decryptedText[256];
    int ciphertextLength = 0;
    int decryptedLength = 0;

    // 加密
    encryptSM4(plaintext, sizeof(plaintext) - 1, key, ciphertext, &ciphertextLength);

    // 打印密文
    std::cout << "Ciphertext: ";
    for (int i = 0; i < ciphertextLength; ++i) {
        printf("%02x", ciphertext[i]);
    }
    std::cout << std::endl;

    // 解密
    decryptSM4(ciphertext, ciphertextLength, key, decryptedText, &decryptedLength);

    // 打印解密后的明文
    std::cout << "Decrypted Text: " << decryptedText << std::endl;

    return 0;
}
