'programming/C_C++'에 해당되는 글 279건

  1. 2017.03.10 Base64Encode / Base64Decode - openssl

반응형


컴파일 :  gcc a.c -lcrypto -o a.out


a.c


#include <stdio.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <stdint.h>
#include <assert.h>

int main(int argc, char *argv[])
{
    char sPlainText[1024];
    char *base64_enc = NULL;

    char sBase64Text[1024];
    char *base64_dec = NULL;

    size_t nBase64DecLen;

    if (strcmp(argv[1], "e") == 0) {

        sprintf(sPlainText, "%s", argv[2]);

        fprintf(stdout, "encrypt original text: %s\n", sPlainText);

        Base64Encode(sPlainText, strlen(sPlainText), &base64_enc);

        fprintf(stdout, "encoded:%s\n", base64_enc);

    }
    else if(strcmp(argv[1], "d") == 0) {

        sprintf(sBase64Text, "%s", argv[2]);

        fprintf(stdout, "decrypt original text: %s\n", sBase64Text);

        Base64Decode(sBase64Text, &base64_dec, &nBase64DecLen);

        fprintf(stdout, "decoded:%s\n", base64_dec);

    }
    else {

        fprintf(stdout, "invalid argument\n");

        return -1;

    }

    return 0;

}

int Base64Encode(const unsigned char* buffer, size_t length, char** b64text)
{
    BIO *bio, *b64;
    BUF_MEM *bufferPtr;

    b64 = BIO_new(BIO_f_base64());
    bio = BIO_new(BIO_s_mem());
    bio = BIO_push(b64, bio);

    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
    BIO_write(bio, buffer, length);
    BIO_flush(bio);

    BIO_get_mem_ptr(bio, &bufferPtr);
    BIO_set_close(bio, BIO_NOCLOSE);
    BIO_free_all(bio);

    *b64text=(*bufferPtr).data;

    return 0;
}

size_t CalculateBase64DecodeLength(const char* b64input)
{

    size_t len = 0;
    size_t padding = 0;

    len = strlen(b64input);

    if (b64input[len-1] == '=' && b64input[len-2] == '=') {
        padding = 2;
    }
    else if (b64input[len-1] == '=') {
        padding = 1;
    }

    return (len*3)/4 - padding;
}

int Base64Decode(char* b64message, unsigned char** buffer, size_t* length)
{
    BIO *bio, *b64;
   
    int decodeLen = 0;

    decodeLen = CalculateBase64DecodeLength(b64message);

    *buffer = (unsigned char*)malloc(decodeLen + 1);

    (*buffer)[decodeLen] = '\0';

    bio = BIO_new_mem_buf(b64message, -1);
    b64 = BIO_new(BIO_f_base64());
    bio = BIO_push(b64, bio);

    BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);

    *length = BIO_read(bio, *buffer, strlen(b64message));

    assert(*length == decodeLen);
    BIO_free_all(bio);

    return 0;
}





반응형
Posted by 공간사랑
,