linux cc++ 使用sm4加密字符串123456并使用加密后的值做base64输出给出加密解密的代码给出实现代码
以下是一个使用sm4加密字符串并进行base64输出的示例代码:
#include <iostream>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/sm4.h>
#include <string.h>
std::string base64_encode(const unsigned char* input, int length) {
BIO* bmem, *b64;
BUF_MEM* bptr;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO_write(b64, input, length);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
std::string output(bptr->data, bptr->length);
BIO_free_all(b64);
return output;
}
std::string base64_decode(const char* input, int length) {
BIO* b64, *bmem;
char* buffer = (char*)malloc(length);
memset(buffer, 0, length);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input, length);
bmem = BIO_push(b64, bmem);
BIO_set_flags(bmem, BIO_FLAGS_BASE64_NO_NL);
BIO_read(bmem, buffer, length);
std::string output(buffer);
free(buffer);
BIO_free_all(bmem);
return output;
}
std::string sm4_encrypt(const std::string& plaintext) {
unsigned char key[16] = "0123456789ABCDEF";
unsigned char iv[16] = "0123456789ABCDEF";
unsigned char ciphertext[100];
int ciphertext_len;
EVP_CIPHER_CTX* ctx;
ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_sm4_ecb(), NULL, key, iv);
EVP_EncryptUpdate(ctx, ciphertext, &ciphertext_len, (const unsigned char*)plaintext.c_str(), plaintext.length());
EVP_EncryptFinal_ex(ctx, ciphertext + ciphertext_len, &ciphertext_len);
EVP_CIPHER_CTX_free(ctx);
std::string output = base64_encode(ciphertext, ciphertext_len);
return output;
}
std::string sm4_decrypt(const std::string& ciphertext) {
unsigned char key[16] = "0123456789ABCDEF";
unsigned char iv[16] = "0123456789ABCDEF";
unsigned char decryptedtext[100];
int decryptedtext_len;
std::string decoded_ciphertext = base64_decode(ciphertext.c_str(), ciphertext.length());
EVP_CIPHER_CTX* ctx;
ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_sm4_ecb(), NULL, key, iv);
EVP_DecryptUpdate(ctx, decryptedtext, &decryptedtext_len, (unsigned char*)decoded_ciphertext.c_str(), decoded_ciphertext.length());
EVP_DecryptFinal_ex(ctx, decryptedtext + decryptedtext_len, &decryptedtext_len);
EVP_CIPHER_CTX_free(ctx);
std::string output((char*)decryptedtext);
return output;
}
int main() {
std::string plaintext = "123456";
std::string encrypted_text = sm4_encrypt(plaintext);
std::cout << "Encrypted Text: " << encrypted_text << std::endl;
std::string decrypted_text = sm4_decrypt(encrypted_text);
std::cout << "Decrypted Text: " << decrypted_text << std::endl;
return 0;
}
请确保你的系统已经安装了OpenSSL库,并将源文件保存为sm4_example.cpp,然后使用以下命令进行编译:
g++ sm4_example.cpp -o sm4_example -lcrypto
运行编译后的可执行文件sm4_example,你将会得到加密后的字符串和解密后的字符串的输出
原文地址: https://www.cveoy.top/t/topic/ibNq 著作权归作者所有。请勿转载和采集!