openssl证书验证

来源:互联网 发布:ubuntu嵌入式工控机 编辑:程序博客网 时间:2024/06/05 05:44

私钥和证书有不同的存储格式,在使用之前需要进行转换

.crt 证书文件 ,可以是DER(二进制)编码的,也可以是PEM( ASCII (Base64) )编码的 ,在类unix系统中比较常见。使用vi打开文件如果内容出现如下样式,则表明是PEM的。

-----BEGIN CERTIFICATE-----
MIIF0TCCA7mgAwIBAgIJA
.....
LMH9av0=
-----END CERTIFICATE-----

.cer 也是证书  常见于Windows系统  编码类型同样可以是DER或者PEM的

.csr 证书签名请求   一般是生成请求以后发送给CA,然后CA会给你签名并发回证书

使用如下命令可以将PEM格式的文件转为DER格式:

openssl x509 -inform PEM -in private_key.pem -outform DER

证书验证代码:

/* 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;
}
}

0 0