Openssl証明書の有効性の検証

2383 ワード

久しぶりにブログを書いて、直接コードをつけました.
#include 
#include 
#include 
#include 
#include 
int LoadCert(unsigned char * szFilePath, unsigned char *pbCert, int size)
{
	int len = 0;
	if(szFilePath == NULL || pbCert == NULL || size < 128)
	{
		return -1;
	}
	FILE *fp = fopen(szFilePath, "rb");
	if ( NULL == fp)
	{
		return -2;
	}

	len = fread(pbCert, 1, size, fp);
	fclose(fp);
	return len;
}

int VerifyCert(unsigned char *pbCaCert, int nCaLen, unsigned char *pbCert, int nCertLen, unsigned char *pbCN, int size)
{
	int rv = -1;
	if(pbCaCert == NULL || nCaLen < 128 || pbCert == NULL || nCertLen < 128)
	{
		return rv;
	}

	X509 *ca = NULL;
	X509 *cert = NULL;

	X509_STORE *caStore = NULL;
	X509_STORE_CTX *ctx = NULL;
	X509_NAME *subject = NULL;
	
	OpenSSL_add_all_algorithms();

	caStore = X509_STORE_new();
	ctx = X509_STORE_CTX_new();

	ca = d2i_X509(NULL, ( const unsigned char **)&pbCaCert, nCaLen);
	if(ca == NULL)
	{
		return -2;
	}

	rv = X509_STORE_add_cert(caStore, ca);
	if ( rv != 1 )
	{
		rv = -3;
		goto EXIT_VERIFY;
	}

	cert = d2i_X509(NULL, ( const unsigned char **)&pbCert, nCertLen);
	if(cert == NULL)
	{
		rv = -4;
		goto EXIT_VERIFY;
	}

	rv = X509_STORE_CTX_init(ctx, caStore, cert, NULL);
	if ( rv != 1 )
	{
		rv = -5;
		goto EXIT_VERIFY;
	}

	rv = X509_verify_cert(ctx);
	if ( rv != 1 )
	{
		fprintf(stderr, "X509_verify_cert fail, rv = %d, error id = %d, %s
", rv, ctx->error, X509_verify_cert_error_string(ctx->error)); rv = (rv == 0 ? 1 : rv); goto EXIT_VERIFY; } subject = X509_get_subject_name(cert); if(subject) { X509_NAME_get_text_by_NID(subject, NID_commonName, pbCN, size); } rv = (rv == 1 ? 0 : rv); EXIT_VERIFY: if(cert) X509_free(cert); if(ca) X509_free(ca); if(caStore) X509_STORE_free(caStore); if(ctx) { X509_STORE_CTX_cleanup(ctx); X509_STORE_CTX_free(ctx); } return rv; } int main(void) { int rv = 0; int i = 0; int caLen = 0; int certLen =0; unsigned char cn[255] = {0}; unsigned char cert[4096] = {0}; unsigned char ca[4096] = {0}; caLen = LoadCert("ca.cer", ca, 4096); certLen = LoadCert("Jinhill.cer", cert, 4096); rv = VerifyCert(ca, caLen, cert, certLen, cn, 255); printf("rv=%d, cn=%s
", rv, cn); return 0; }