1. 程式人生 > >openssl證書驗證

openssl證書驗證

/* X509證書驗證 */
void x509_verify() {


FILE* fp = fopen("root.der", "rb");
if (fp == NULL) {
printf("fopen error\n");
return;
}


unsigned char root_cert[4096];
uint32_t root_len;
root_len = fread(root_cert,1, 4096, fp);
fclose(fp);


/*DER轉內部x509結構*/
const unsigned char* tmp = (const unsigned char*)root_cert;
X509* root = d2i_X509(NULL, &tmp, root_len);
if (root == NULL) {
printf("d2i_X509 root error \n");
return;
}


fp = fopen("server.der", "rb");
if (fp == NULL) {
printf("fopen error\n");
return;
}


unsigned char user_cert[4096];
uint32_t user_len;
user_len = fread(user_cert,1, 4096, fp);
fclose(fp);


tmp = (unsigned char*) user_cert;
X509* user = d2i_X509(NULL, &tmp, user_len);
if (user == NULL) {
printf("d2i_X509 user error \n");
return;
}


/*將根證書新增到儲存區域*/
X509_STORE* root_store = X509_STORE_new();
X509_STORE_add_cert(root_store, root);


X509_STORE_CTX* ctx = X509_STORE_CTX_new();
STACK_OF(X509)* ca_stack = NULL;
X509_STORE_CTX_init(ctx, root_store, user, ca_stack);


int iv = X509_verify_cert(ctx);
if (iv != 1) {
printf("verify client certificate error: %d  info: %s\n", ctx->error,
X509_verify_cert_error_string(ctx->error));
return;
} else {
printf("verify server certificate ok \n");
return;
}
}