Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenSSL ASN.1 programming tutorial

Tags:

c

openssl

asn.1

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

like image 628
Rython Avatar asked Jun 20 '12 11:06

Rython


People also ask

What is ASN in OpenSSL?

OpenSSL::ASN1. Abstract Syntax Notation One (or ASN. 1) is a notation syntax to describe data structures and is defined in ITU-T X. 680.

What is ASN file format?

ASN. 1, or Abstract Syntax Notation One, is an International Standards Organization (ISO) data representation format used to achieve interoperability between platforms. NCBI uses ASN. 1 for the storage and retrieval of data such as nucleotide and protein sequences, structures, genomes, PubMed records, and more.

What ASN 1?

​ASN. 1 is a formal notation used for describing data transmitted by telecommunications protocols, regardless of language implementation and physical representation of these data, whatever the application, whether complex or very simple.


2 Answers

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.

like image 115
Alexander Dzyoba Avatar answered Oct 11 '22 15:10

Alexander Dzyoba


#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.

like image 42
Chao Zhao Avatar answered Oct 11 '22 15:10

Chao Zhao