Search code examples
copensslpkiasn.1serial-number

char * to ASN1_INTEGER


For PKI certificate generation , and for setting up serial number , I used RAND_bytes to get 20 bytes of random serial number, now I wanted this char * to be set to serial number of certificate , which seems to be of type ASN1_INTEGER *

Tried ASN1_TYPE_set_octetstring(ASN1_TYPE *, unsigned char *, len) but since it takes ASN1_TYPE * and not ASN1_INTEGER* it gave a crash

How do I convert between unsigned char * to ASN1_INTEGER ?

Thanks,


Solution

  • I'm fairly sure this is what you're looking for, but I could be wrong. If you want to have a 20-byte ASN1_INTEGER one way to do that is sending it through the BIGNUM library first:

    unsigned char data[20] = {0};
    RAND_bytes(data, sizeof(data));
    data[0] &= 0x7F;
    
    // build big number from our bytes
    BIGNUM* bn = BN_new();
    BN_bin2bn(data, sizeof(data), bn);
    
    // build the ASN1_INTEGER from our BIGNUM
    ASN1_INTEGER* asnInt = ASN1_INTEGER_new();
    BN_to_ASN1_INTEGER(bn, asnInt);
    
    // TODO: use your ASN1_INTEGER
    
    // cleanup
    ASN1_INTEGER_free(asnInt);
    BN_free(bn);