Skip to content

Commit

Permalink
md5: use OpenSSL 1.1.0+ API
Browse files Browse the repository at this point in the history
  • Loading branch information
mmatuska committed Oct 18, 2023
1 parent 68cb3cb commit 14d90d8
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions src/md5.c
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

#include "cpdup.h"

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

typedef struct MD5Node {
struct MD5Node *md_Next;
Expand Down Expand Up @@ -257,13 +257,14 @@ md5_check(const char *spath, const char *dpath)
static char *
md5_file(const char *filename, char *buf)
{
unsigned char digest[MD5_DIGEST_LENGTH];
unsigned char digest[EVP_MAX_MD_SIZE];
static const char hex[] = "0123456789abcdef";
MD5_CTX ctx;
EVP_MD_CTX *ctx;
unsigned char buffer[4096];
struct stat st;
off_t size;
int fd, bytes, i;
int fd, bytes;
unsigned int i, md_len;

fd = open(filename, O_RDONLY);
if (fd < 0)
Expand All @@ -273,7 +274,11 @@ md5_file(const char *filename, char *buf)
goto err;
}

MD5_Init(&ctx);
ctx = EVP_MD_CTX_new();
if (!EVP_DigestInit_ex(ctx, EVP_md5(), NULL)) {
fprintf(stderr, "Unable to initialize MD5 digest.\n");
exit(1);
}
size = st.st_size;
bytes = 0;
while (size > 0) {
Expand All @@ -283,7 +288,10 @@ md5_file(const char *filename, char *buf)
bytes = read(fd, buffer, size);
if (bytes < 0)
break;
MD5_Update(&ctx, buffer, bytes);
if (!EVP_DigestUpdate(ctx, buffer, bytes)) {
fprintf(stderr, "Unable to update MD5 digest.\n");
exit(1);
}
size -= bytes;
}

Expand All @@ -292,17 +300,23 @@ md5_file(const char *filename, char *buf)
if (bytes < 0)
return NULL;

if (!EVP_DigestFinal(ctx, digest, &md_len)) {
fprintf(stderr, "Unable to finalize MD5 digest.\n");
exit(1);
}

EVP_MD_CTX_free(ctx);

if (!buf)
buf = malloc(MD5_DIGEST_LENGTH * 2 + 1);
buf = malloc(md_len * 2 + 1);
if (!buf)
return NULL;

MD5_Final(digest, &ctx);
for (i = 0; i < MD5_DIGEST_LENGTH; i++) {
for (i = 0; i < md_len; i++) {
buf[2*i] = hex[digest[i] >> 4];
buf[2*i+1] = hex[digest[i] & 0x0f];
}
buf[MD5_DIGEST_LENGTH * 2] = '\0';
buf[md_len * 2] = '\0';

return buf;
}
Expand Down

0 comments on commit 14d90d8

Please sign in to comment.