ASN1
ASN1编码规则-ing
定义
asn1是一种数据结构的描述方式,是一种抽象语法,适用于通信过程中的数据传输。
类型 | c语言对应 |
---|---|
SEQUENCE | 结构体struct |
SEQUENCE OF | 多个struct类型组成的数组 |
INTEGR | int |
ENUMERATED | 枚举 |
BIT STRING | 比特流 |
OCTET STRING | 字节流 |
SET | 无序结构 |
SET OF | 同SEQUENCE OF定义 |
CHOICE | 联合(union) |
代码
//asn1.h
#ifndef _ASN1_H_
#define _ASN1_H_
#if defined (__cplusplus)
extern "C" {
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
typedef struct test{
ASN1_INTEGER* a;
ASN1_BIT_STRING* b; //比特流
}ASN1_Test;
DECLARE_ASN1_FUNCTIONS(ASN1_Test)
#if defined (__cplusplus)
}
#endif
#endif
//asn1.c
#include "asn1.h"
ASN1_SEQUENCE(ASN1_Test) = {
ASN1_SIMPLE(ASN1_Test, a, ASN1_INTEGER),
ASN1_SIMPLE(ASN1_Test, b, ASN1_BIT_STRING),
} ASN1_SEQUENCE_END(ASN1_Test);
IMPLEMENT_ASN1_FUNCTIONS(ASN1_Test)
//main.c
#include "asn1.h"
int main()
{
ASN1_Test* demo = NULL;
demo = ASN1_Test_new();
unsigned char* buf = NULL; //用数组会失败
if(demo == NULL) {
printf("creat err!\n");
}
ASN1_INTEGER_set(demo->a, 87880);
ASN1_BIT_STRING_set(demo->b, (unsigned char*)"838482842", 10);
int len = i2d_ASN1_Test(demo, &buf);
printf("len = %d\n", len);
printf("****************\n");
for(int i = 0; i < len; ++i)
{
printf("%02x ", buf[i]);
if((i + 1) % 5 == 0){
printf("\n");
}
}
printf("\n");
ASN1_Test_free(demo);
return 0;
}
更多格式
1、
version [0] EXPLICIT INTEGER OPTIONAL,
//对应的描述
ASN1_INTEGER* version;
ASN1_EXP_OPT("略")
2、
version [0] IMPLICIT INTEGER OPTIONAL,
//对应的描述
ASN1_INTEGER* version;
ASN1_IMP_OPT("略")