步骤:
1)初始化环境
a.新建证书存储区X509_STORE_new()
b.新建证书校验上下文X509_STORE_CTX_new()
2)导入根证书
a.读取CA证书,从DER编码格式化为X509结构d2i_X509()
b.将CA证书导入证书存储区X509_STORE_add_cert()
3)导入要校验的证书test
a.读取证书test,从DER编码格式化为X509结构d2i_X509()
b.在证书校验上下文初始化证书test,X509_STORE_CTX_init()
c.校验X509_verify_cert
-
include <stdio.h>
-
#include <string.h>
-
#include <stdlib.h>
-
-
#include <openssl/evp.h>
-
#include <openssl/x509.h>
-
-
#define CERT_PATH "/home/ckelsel/work/rc4/cert"
-
#define ROOT_CERT "ca.cer"
-
#define WIN71H "win71h.cer"
-
#define WIN71Y "win71y.cer"
-
-
-
#define GET_DEFAULT_CA_CERT(str) sprintf(str, "%s/%s", CERT_PATH, ROOT_CERT)
-
#define GET_CUSTOM_CERT(str, path, name) sprintf(str, "%s/%s", path, name)
-
-
#define MAX_LEGTH 4096
-
-
-
int my_load_cert(unsigned char *str, unsigned long *str_len,
-
const char *verify_cert, const unsigned int cert_len)
-
{
-
FILE *fp;
-
fp = fopen(verify_cert, "rb");
-
if ( NULL == fp)
-
{
-
fprintf(stderr, "fopen fail\n");
-
return -1;
-
}
-
-
*str_len = fread(str, 1, cert_len, fp);
-
fclose(fp);
-
return 0;
-
}
-
-
X509 *der_to_x509(const unsigned char *der_str, unsigned int der_str_len)
-
{
-
X509 *x509;
-
x509 = d2i_X509(NULL, &der_str, der_str_len);
-
if ( NULL == x509 )
-
{
-
fprintf(stderr, "d2i_X509 fail\n");
-
-
return NULL;
-
}
-
return x509;
-
}
-
int x509_verify()
-
{
-
int ret;
-
char cert[MAX_LEGTH];
-
-
unsigned char user_der[MAX_LEGTH];
-
unsigned long user_der_len;
-
X509 *user = NULL;
-
-
unsigned char ca_der[MAX_LEGTH];
-
unsigned long ca_der_len;
-
X509 *ca = NULL;
-
-
X509_STORE *ca_store = NULL;
-
X509_STORE_CTX *ctx = NULL;
-
STACK_OF(X509) *ca_stack = NULL;
-
-
/* x509初始化 */
-
ca_store = X509_STORE_new();
-
ctx = X509_STORE_CTX_new();
-
-
/* root ca*/
-
GET_DEFAULT_CA_CERT(cert);
-
/* 从文件中读取 */
-
my_load_cert(ca_der, &ca_der_len, cert, MAX_LEGTH);
-
/* DER编码转X509结构 */
-
ca = der_to_x509(ca_der, ca_der_len);
-
/* 加入证书存储区 */
-
ret = X509_STORE_add_cert(ca_store, ca);
-
if ( ret != 1 )
-
{
-
fprintf(stderr, "X509_STORE_add_cert fail, ret = %d\n", ret);
-
goto EXIT;
-
}
-
-
/* 需要校验的证书 */
-
GET_CUSTOM_CERT(cert, CERT_PATH, WIN71H);
-
my_load_cert(user_der, &user_der_len, cert, MAX_LEGTH);
-
user = der_to_x509(user_der, user_der_len);
-
-
ret = X509_STORE_CTX_init(ctx, ca_store, user, ca_stack);
-
if ( ret != 1 )
-
{
-
fprintf(stderr, "X509_STORE_CTX_init fail, ret = %d\n", ret);
-
goto EXIT;
-
}
-
-
//openssl-1.0.1c/crypto/x509/x509_vfy.h
-
ret = X509_verify_cert(ctx);
-
if ( ret != 1 )
-
{
-
fprintf(stderr, "X509_verify_cert fail, ret = %d, error id = %d, %s\n",
-
ret, ctx->error, X509_verify_cert_error_string(ctx->error));
-
goto EXIT;
-
}
-
EXIT:
-
X509_free(user);
-
X509_free(ca);
-
-
X509_STORE_CTX_cleanup(ctx);
-
X509_STORE_CTX_free(ctx);
-
-
X509_STORE_free(ca_store);
-
-
return ret == 1 ? 0 : -1;
-
}
-
-
int main()
-
{
-
OpenSSL_add_all_algorithms();
-
x509_verify();
-
return 0;
-
}
阅读(6628) | 评论(0) | 转发(0) |