如何使用Openssl对特定于上下文的ASN.1进行编码

时间:2013-10-22 20:45:43

标签: c++ encoding openssl pkcs#7

我正在尝试编码pkcs7封装的内容信息:

Sequence:
  OID
  [0] Context-specific
     OCTET STRING

我的第一个问题是对特定于上下文的编码:

[0] Context-specific

所以我尝试使用'Octet String'创建'SET Context-specific',但没有成功:

// Create ASN1_OCTET
ASN1_OCTET_STRING *obj = ASN1_OCTET_STRING_new();
const BYTE* ptr = dataToSign.getData();
ASN1_OCTET_STRING_set(obj, ptr, dataToSign.getSize());

// Create ASN1_TYPE using ASN1_OCTET
ASN1_TYPE   *asn1Type   = ASN1_TYPE_new();
asn1Type->type = V_ASN1_OCTET_STRING;
asn1Type->value.octet_string = obj;

// Using i2d_ASN1_SET_OF_ASN1_TYPE
stack_st_ASN1_TYPE* sk = sk_ASN1_TYPE_new_null();
sk_ASN1_TYPE_push(sk,asn1Type);
int tamanho = i2d_ASN1_SET_OF_ASN1_TYPE(sk,(unsigned char **) NULL, i2d_ASN1_TYPE,V_ASN1_SET, V_ASN1_CONTEXT_SPECIFIC, IS_SET);
unsigned char* data = new BYTE[tamanho];
tamanho = i2d_ASN1_SET_OF_ASN1_TYPE(sk,(unsigned char **) &data, i2d_ASN1_TYPE,V_ASN1_SET, V_ASN1_CONTEXT_SPECIFIC, IS_SET);

我在openssl的网站上找不到文档。 这个地方更好umich - Openssl documentation

我是在正确的轨道上吗?

2 个答案:

答案 0 :(得分:1)

使用i2d_ASN1_bytes功能:

// Initialize ASN1_STRING inplace (no need to free)
ASN1_STRING s = { 0, 0, NULL, 0};
// Initialize with our data
ASN1_STRING_set0(&obj, dataToSign.getData(), dataToSign.getSize());

// Get resulting object length
int data_len = i2d_ASN1_bytes(obj, NULL, 0, V_ASN1_CONTEXT_SPECIFIC)
// Encode object with context tag 0
unsigned char* data = new BYTE[data_len];
unsigned char* p = data;
i2d_ASN1_bytes(obj, &p, 0, V_ASN1_CONTEXT_SPECIFIC);

答案 1 :(得分:0)

  

如何使用Openssl编码ASN.1特定于上下文?

来自asn1.h

#define V_ASN1_UNIVERSAL        0x00
#define V_ASN1_APPLICATION      0x40
#define V_ASN1_CONTEXT_SPECIFIC     0x80
#define V_ASN1_PRIVATE          0xc0
...

#define V_ASN1_BOOLEAN          1   /**/
#define V_ASN1_INTEGER          2
...
#define V_ASN1_UTF8STRING       12
#define V_ASN1_SEQUENCE         16
#define V_ASN1_SET          17
...

因此您需要使用标记V_ASN1_CONTEXT_SPECIFIC

  

我的第一个问题是编码特定于上下文的

来自A Layman's Guide to a Subset of ASN.1, BER, and DER(第12页):

> Example 1: PKCS #7's ContentInfo type has an optional
> content component with an explicit, context-specific tag:
>
> ContentInfo ::= SEQUENCE {
>    contentType ContentType,
>    content
>    [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
> 
> Here the underlying type is ANY DEFINED BY contentType, the
> class is absent (i.e., context-specific), and the tag number
> within the class is 0.

然后,该文档继续讨论ContentInfo,标识符八位字节,基于ANY的{​​{1}}编码等。