后端砖头

C语言操作openssl

2021-10-09  本文已影响0人  何亮hook_8285

C语言调用OpenSSL加解密

md5加密

#include <openssl/md5.h>

void Md5Demo(){
    //定义md5存储长度
    unsigned char digest[MD5_DIGEST_LENGTH];
    //加密的字符串
    char string[] = "happy";
    //调用OPENSSL md5加密函数
    MD5((unsigned char*)&string, strlen(string), (unsigned char*)&digest);
    //定义存储加密后字符粗
    char mdString[33];
    for(int i = 0; i < 16; i++){
        //将加密字符串写入mdString变量中
        sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);
    }
    //打印
    cout << mdString << endl;
}

sha1加密

#include <openssl/sha.h>

void Sha1Demo(){
    //定义加密字符串
    const unsigned char data[] = "Hello, world!";
    //获取字符串长度
    size_t length = sizeof(data);
    //SHA长度
    unsigned char hash[SHA_DIGEST_LENGTH];
    //调用OPENSSL sha1加密
    SHA1(data, length, hash);

    //定义存储加密变量
    char mdString[SHA_DIGEST_LENGTH];

    for(int i = 0; i < (SHA_DIGEST_LENGTH/2) - 1; i++){
        sprintf(&mdString[i*2], "%02x", (unsigned int)hash[i]);
    }

    cout << mdString << endl;
}

base64 编码

#include <openssl/bio.h>
#include <openssl/evp.h>

char * base64Encode(const char *buffer, int length, bool newLine)
{
    BIO *bmem = NULL;
    BIO *b64 = NULL;
    BUF_MEM *bptr;

    b64 = BIO_new(BIO_f_base64());
    if (!newLine) {
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    }
    bmem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bmem);
    BIO_write(b64, buffer, length);
    BIO_flush(b64);
    BIO_get_mem_ptr(b64, &bptr);
    BIO_set_close(b64, BIO_NOCLOSE);

    char *buff = (char *)malloc(bptr->length + 1);
    memcpy(buff, bptr->data, bptr->length);
    buff[bptr->length] = 0;
    BIO_free_all(b64);

    return buff;
}

base64 解码

#include <openssl/bio.h>
#include <openssl/evp.h>

// base64 解码
char * base64Decode(char *input, int length, bool newLine)
{
    BIO *b64 = NULL;
    BIO *bmem = NULL;
    char *buffer = (char *)malloc(length);
    memset(buffer, 0, length);
    b64 = BIO_new(BIO_f_base64());
    if (!newLine) {
        BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    }
    bmem = BIO_new_mem_buf(input, length);
    bmem = BIO_push(b64, bmem);
    BIO_read(bmem, buffer, length);
    BIO_free_all(bmem);

    return buffer;
}

调用base64编解码

bool newLine = false;
string input = "Hello World!";

char * encode = base64Encode(input.c_str(), input.length(), newLine);
char * decode = base64Decode(encode, strlen(encode), newLine);

cout << "Base64 Encoded : " << encode << endl;
cout << "Base64 Decoded : " << decode << endl;

sha256加密

string  sha256(const string str)
{
    char buf[2];
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str.c_str(), str.size());
    SHA256_Final(hash, &sha256);
    std::string newString = "";
    for(int i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(buf,"%02x",hash[i]);
        newString = newString + buf;
    }
    return newString;
}
上一篇下一篇

猜你喜欢

热点阅读