-->

OpenSSL ASN.1 programming tutorial

2019-06-17 02:25发布

问题:

I'm looking for any C/C++ tutorial, sample code or documentation about using OpenSSL library for ASN.1 DER encoding.

回答1:

Well, as you can see on openssl website there is no official documentation for ASN.1 functions.

But you can always download openssl sources. After unpack you can see in doc/crypto directory documentation for ASN.1.

# ~/tmp/openssl-1.0.1c/doc/crypto> ls -1 | grep -i asn
ASN1_generate_nconf.pod
ASN1_OBJECT_new.pod
ASN1_STRING_length.pod
ASN1_STRING_new.pod
ASN1_STRING_print_ex.pod
d2i_ASN1_OBJECT.pod

This files is plain old documentation that, i believe, can be converted to HTML/PDF. It contains what you want.



回答2:

#include <openssl/asn1.h>
#include <cstdio>
#include <cstring>

void xprint(void *data, int len) {
  unsigned char *ptr = reinterpret_cast<unsigned char*>(data);
  for (int i = 0; i < len; i++) {
    printf("%x ", *ptr);
    ptr += 1;
  }
  printf("\n");
}

void str_test() {
  ASN1_STRING asn1str;
  const char *s = "stackoverflow save the world!aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
  ASN1_STRING_set(&asn1str, s, strlen(s) + 1);
  const char *value = reinterpret_cast<char*>(ASN1_STRING_data(&asn1str));
  printf("The value is %s, strlen: %zu\n", value, strlen(value));
  unsigned char *ptr = new unsigned char[1024];
  int ret = M_i2d_ASN1_OCTET_STRING(&asn1str, &ptr);
  // int ret = i2d_ASN1_bytes(&asn1str, &ptr, V_ASN1_OCTET_STRING, V_ASN1_UNIVERSAL);
  printf("return: %d\n", ret);
  xprint(ptr - ret, ret);
}

int main(int argc, char** argv) {
  str_test();
  return 0;
}

Hope this will save you some time and struggling.

http://www.umich.edu/~x509/ssleay/asn1_convert.html This link is really helpful.



标签: c openssl asn.1