Base64 digest calculation using openssl

I am trying to figure out how to encode the following openssl commands:

Scenario:

Subject: Base64 encoded file value (b64.txt)

Base64 encoded file sha1 file (exactly 20 bytes sha1 digest of this file).

Problem: I need to check with program C if the given digest for the file is correct.

My method:

  • First I tried openssl commands to check the digest before writing the code. Here is how I did it.
  • First, I decoded this base64 file, and then found the file sha1 file.

I was not sure why I never got the 20byte value as a result. And from trial and error only worked:

On a Linux system, I did the following:

  • base64 -d b64.txt > dec.out (dec.out is a combination of text and binary (inaudible) text)
  • openssl dgst -sha1 -binary dec.out > sha1.bin (I discovered the digest in binary form, assuming dec.out as binary input)
  • base64 sha1.bin > sha1.b64 (encoding the result of sha1 in base64)

Now my sha1.b64 gave a 20 byte digest that was the same as me.

First of all, I would like to know if the sequence of commands is correct, and if there are simpler ways to do this.

Also, with EVP_Digest * how to program this (I mean, what file input format is listed in them?)

Please clarify.

thank

+3
source share
1 answer

This sequence of commands looks correct. You can simplify it by using shell redirection instead of temporary files:

base64 -d b64.txt | openssl dgst -sha1 -binary | base64

To do the same in C using the OpenSSL library, you can use abstraction BIOfor a good effect:

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

int main(int argc, char *argv[])
{
    BIO *bio_in, *b64, *md, *bio_out;
    char buf[1024];
    char mdbuf[EVP_MAX_MD_SIZE];
    int mdlen;

    /* setup input BIO chain */
    bio_in = BIO_new_fp(stdin, BIO_NOCLOSE);

    b64 = BIO_new(BIO_f_base64());
    bio_in = BIO_push(b64, bio_in);

    md = BIO_new(BIO_f_md());
    BIO_set_md(md, EVP_sha1());
    bio_in = BIO_push(md, bio_in);

    /* reading through the MD BIO calculates the digest */
    while (BIO_read(bio_in, buf, sizeof buf) > 0)
        ;

    /* retrieve the message digest */
    mdlen = BIO_gets(md, mdbuf, sizeof mdbuf);

    /* setup output BIO chain */
    bio_out = BIO_new_fp(stdout, BIO_NOCLOSE);

    b64 = BIO_new(BIO_f_base64());
    bio_out = BIO_push(b64, bio_out);

    /* write out digest */
    BIO_write(bio_out, mdbuf, mdlen);
    BIO_flush(bio_out);

    BIO_free_all(bio_in);
    BIO_free_all(bio_out);

    return 0;
}

base64 stdin SHA1 base64 stdout.

+1

Source: https://habr.com/ru/post/1792176/


All Articles