使用openssl C API构建ASN1集

时间:2018-12-17 05:37:35

标签: c openssl asn.1

我正在尝试使用openssl C API构建一组序列。正如在各个地方所指出的那样,文档对此非常稀疏,并且似乎不存在代码示例。

我在网络上找到了各种建议,但似乎都无法正常工作。

我已经走了这么远才能创建序列:

#include <openssl/asn1t.h>

countdef struct StringStructure {
    ASN1_INTEGER *count;
    ASN1_INTEGER *asnVersion;
    ASN1_OCTET_STRING *value;
} StringSequence;

DECLARE_ASN1_FUNCTIONS(StringSequence)

ASN1_SEQUENCE(StringSequence) = {
    ASN1_SIMPLE(StringSequence, count, ASN1_INTEGER),
    ASN1_SIMPLE(StringSequence, asnVersion, ASN1_INTEGER),
    ASN1_SIMPLE(StringSequence, value, ASN1_OCTET_STRING),
} ASN1_SEQUENCE_END(StringSequence)

IMPLEMENT_ASN1_FUNCTIONS(StringSequence)

auto aSeq = StringSequence_new();
aSeq->count = ASN1_INTEGER_new();
aSeq->asnVersion = ASN1_INTEGER_new();
aSeq->value = ASN1_OCTET_STRING_new();
if (!ASN1_INTEGER_set(aSeq->count, 10) ||
    !ASN1_INTEGER_set(aSeq->asnVersion, 1) ||
    !ASN1_STRING_set(aSeq->value, "Test", -1)) {
    // -- Error
}

auto anotherSeq = StringSequence_new();
anotherSeq->count = ASN1_INTEGER_new();
anotherSeq->asnVersion = ASN1_INTEGER_new();
anotherSeq->value = ASN1_OCTET_STRING_new();
if (!ASN1_INTEGER_set(anotherSeq->count, 32) ||
    !ASN1_INTEGER_set(anotherSeq->asnVersion, 1) ||
    !ASN1_STRING_set(anotherSeq->value, "Something Else", -1)) {
    // -- Error
}

我应该从那里去那里建立一套?

1 个答案:

答案 0 :(得分:4)

OpenSSL源代码是您最好的文档...

作为您要构建的结构的示例,请查看the PKCS7_SIGNED ASN1 definition in crypto/pkcs7/pk7_asn1.c

ASN1_NDEF_SEQUENCE(PKCS7_SIGNED) = {
        ASN1_SIMPLE(PKCS7_SIGNED, version, ASN1_INTEGER),
        ASN1_SET_OF(PKCS7_SIGNED, md_algs, X509_ALGOR),
        ASN1_SIMPLE(PKCS7_SIGNED, contents, PKCS7),
        ASN1_IMP_SEQUENCE_OF_OPT(PKCS7_SIGNED, cert, X509, 0),
        ASN1_IMP_SET_OF_OPT(PKCS7_SIGNED, crl, X509_CRL, 1),
        ASN1_SET_OF(PKCS7_SIGNED, signer_info, PKCS7_SIGNER_INFO)
} ASN1_NDEF_SEQUENCE_END(PKCS7_SIGNED)

它的第二个成员md_algs是一组X509_ALGOR,其本身就是a sequence defined in crypto/asn1/x_algor.c

ASN1_SEQUENCE(X509_ALGOR) = {
        ASN1_SIMPLE(X509_ALGOR, algorithm, ASN1_OBJECT),
        ASN1_OPT(X509_ALGOR, parameter, ASN1_ANY)
} ASN1_SEQUENCE_END(X509_ALGOR)

因此,字段md_algs是一组序列,就像您要的一样。等效的C结构定义可在include/openssl/pkcs7.h中找到:

typedef struct pkcs7_signed_st {
    ASN1_INTEGER *version;      /* version 1 */
    STACK_OF(X509_ALGOR) *md_algs; /* md used */
    STACK_OF(X509) *cert;       /* [ 0 ] */
    STACK_OF(X509_CRL) *crl;    /* [ 1 ] */
    STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
    struct pkcs7_st *contents;
} PKCS7_SIGNED;

md_algs字段显示,要捕获集合构造,您需要使用the STACK API,该集合用于处理集合。您的情况就是STACK_OF(StringSequence)