Development

[OpenSSL] Hash Value ํ•จ์ˆ˜

JayKim๐Ÿ™‚ 2022. 12. 9. 11:18

์•„๋ž˜๋Š” ํ•ด์‰ฌ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๋Š” ์†Œ์Šค์ด๋‹ค

pAlg ์— ์‚ฌ์šฉ๋˜๋Š” ๊ฐ’์€ md5, sha1, sha224, sha256, sm3 ๋“ฑ ๋ฌธ์ž์—ด ์ด๋‹ค.
pSrc ๊ฐ€ ์ž…๋ ฅ ๊ฐ’
pHash ๊ฐ€ ๊ฒฐ๊ณผ ํ•ด์‰ฌ ๊ฐ’

BIN ๊ตฌ์กฐ์ฒด

typedef struct _BIN {
	int				nLen;
	unsigned char	*pVal;
} BIN;
int JS_PKI_genHash(const char * pAlg, const BIN * pSrc, BIN * pHash)
{
	int				nRet = 0;
	EVP_MD_CTX		*pCTX = NULL;
	const EVP_MD	*pMD = NULL;
	unsigned char	*pDigest = NULL;
	int				nDigestLen = 0;

	pMD = EVP_get_digestbyname(pAlg);
	if (pMD == NULL)
	{
		fprintf(stderr, "invalid digest algorithm(%s)\n", pAlg);
		return -1;
	}

	pCTX = EVP_MD_CTX_create();
	if (pCTX == NULL)
	{
		fprintf(stderr, "fail to create ctx\n");
		return -2;
	}

	nRet = EVP_DigestInit(pCTX, pMD);
	if (nRet != 1)
	{
		fprintf(stderr, "digest init fail(%d)\n", nRet);
		nRet = -3;
		goto end;
	}

	nRet = EVP_DigestUpdate(pCTX, pSrc->pVal, pSrc->nLen);
	if (nRet != 1)
	{
		fprintf(stderr, "digest update fail(%d)\n", nRet);
		nRet = -4;
		goto end;
	}

	pDigest = (unsigned char *)JS_calloc(1, EVP_MD_size(pMD));
	if (pDigest == NULL)
	{
		fprintf(stderr, "out of memeory for digest\n");
		nRet = -5;
		goto end;
	}

	nRet = EVP_DigestFinal(pCTX, pDigest, (unsigned int *)&nDigestLen);
	if (nRet != 1)
	{
		fprintf(stderr, "digest final fail(%d)\n", nRet);
		nRet = -6;
		goto end;
	}

	if (nDigestLen > 0)
	{
		JS_BIN_set(pHash, pDigest, nDigestLen);
		nRet = 0;
	}

end :
	if (pCTX)
	{
		EVP_MD_CTX_destroy(pCTX);
	}

	if (pDigest) JS_free(pDigest);

	return nRet;
}

์•„๋ž˜๋Š” BerEditor ์—์„œ ํ•ด์‰ฌ ์œ„ ํ•จ์ˆ˜๋ฅผ ๋Œ๋ฆฐ ํ™”๋ฉด์ด๋‹ค

๋ฐ˜์‘ํ˜•