아직미분류2012. 1. 14. 14:24
1. echo -n "string" | md5sum
-n 옵션을 안 적으면 newline character까지 계산되므로 원하지 않는 결과를 얻을 수도 있다.

2. C 프로그램 사용
불확실한 부분이 있는데, MD5_Update에서 length 제한이 없나?
컴파일 옵션: gcc md5.c -std=c99 -lssl -Wall -Wextra -Wconversion
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <openssl/md5.h>

void md5sum(char *str, unsigned char *c);
int md5compare(unsigned char *c, unsigned char *d);
int md5print(unsigned char *c);
int md5sprint(unsigned char *c, char *out);
int md5read(char *str, unsigned char *c);

int main(int argc, char *argv[])
{
	unsigned char orig[MD5_DIGEST_LENGTH];
	if (argc == 2) {
		if (md5read(argv[1], orig) != 0) {
			printf("usage: %s <md5sum string>\n", argv[0]);
			printf("error: wrong md5sum string.\n");
			exit(1);
		}
		// foo(orig);
	} else {
		printf("usage: %s <md5sum string>\n", argv[0]);
		exit(1);
	}
	return 0;
}

void md5sum(char *str, unsigned char *c)
{
	if (!str || !c)
		return;
	MD5_CTX ctx;
	size_t len = strlen(str);
	MD5_Init(&ctx);
	MD5_Update(&ctx, str, len);
	MD5_Final(c, &ctx);
}

int md5compare(unsigned char *c, unsigned char *d)
{
	if (!c || !d)
		return 1;
	for (size_t i = 0; i < MD5_DIGEST_LENGTH; ++i) {
		if (*(c++) != *(d++))
			return 1;
	}
	return 0;
}

// print md5 result to string
int md5print(unsigned char *c)
{
	if (!c)
		return 1;
	for (size_t i = 0; i < MD5_DIGEST_LENGTH; ++i)
		printf("%02x", c[i]);
	putchar('\n');
	return 0;
}

int md5sprint(unsigned char *c, char *out)
{
	if (!c || !out)
		return 1;
	for (size_t i = 0; i < MD5_DIGEST_LENGTH; ++i) {
		sprintf(out, "%02x", c[i]);
		out += 2;
	}
	*out = '\0';
	return 0;
}

// read md5 string and store
int md5read(char *str, unsigned char *c)
{
	if (!str || !c)
		return 1;
	if (strlen(str) != 2 * MD5_DIGEST_LENGTH)
		return 1;
	for (size_t i = 0; i <MD5_DIGEST_LENGTH; ++i) {
		unsigned int tmp;
		sscanf(str, "%02x", &tmp);
		str += 2;
#if 0
		if (tmp > UCHAR_MAX)
			return 1;
#endif
		*(c++) = (unsigned char) tmp;
	}
	return 0;
}
Posted by asdfzxcv