2021-05-27~5-29

本文深入解析ASN.1编码规则,介绍其在通信中数据传输的应用,并提供C语言中的结构体、枚举、比特流等典型类型的实例。通过ASN1_Test结构体和相关函数的代码演示,帮助读者理解如何在实际项目中使用ASN.1进行数据表示和操作。
摘要由CSDN通过智能技术生成

ASN1编码规则-ing

编码讲解链接

定义

asn1是一种数据结构的描述方式,是一种抽象语法,适用于通信过程中的数据传输。

类型c语言对应
SEQUENCE结构体struct
SEQUENCE OF多个struct类型组成的数组
INTEGRint
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("略")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值