Search code examples
copensslx509

ASN1_INTEGER to ASN1_STRING


I am using openssl to get data about x509 certificate. Is there a way to convert ASN1_INTEGER to ASN1_STRING, which can than easily be transformed to char array? Is there a way to convert it to any other human readable format?

EDIT: I'm using openssl compiled for iOS, as I am having the iOS project. Here is the code I am using to extract the serial number from the certificate:

ASN1_INTEGER *serial = X509_get_serialNumber(certificateX509);
long value = ASN1_INTEGER_get(serial);
NSLog(@"Serial %ld", value);

certificateX509 is a valid X509 object and I have managed to get some other fields from it (issuer name, expiry date and so on)

EDIT 2:
I finally came to a solution, which may not be the most straightforward one:

 ASN1_INTEGER *serial = X509_get_serialNumber(certificateX509);
 BIGNUM *bnser = ASN1_INTEGER_to_BN(serial, NULL);
 int n = BN_num_bytes(bnser);
 unsigned char outbuf[n];
 int bin = BN_bn2bin(bnser, outbuf);
 char *hexbuf = (char*) outbuf;

hexBuf then contains characters whose value needs to be read as hex integer in order to retrieve logical values. I use NSMutableString to create a human readable string:

NSMutableString *str = [[NSMutableString alloc] init];
for (int i=0; i<n; i++) {
    NSString *temp = [NSString stringWithFormat:@"%.6x", hexbuf[i]];
    [str appendString:[NSString stringWithFormat:@"%@ ", temp]];
}

If there is a simpler way, I would really like to know it.


Solution

  • I finally came to a solution, which may not be the most straightforward one:

     ASN1_INTEGER *serial = X509_get_serialNumber(certificateX509);
     BIGNUM *bnser = ASN1_INTEGER_to_BN(serial, NULL);
     int n = BN_num_bytes(bnser);
     unsigned char outbuf[n];
     int bin = BN_bn2bin(bnser, outbuf);
     char *hexBuf = (char*) outbuf;
    

    hexBuf then contains characters whose value needs to be read as hex integer in order to retrieve logical values. I use NSMutableString to create a human readable string:

     NSMutableString *str = [[NSMutableString alloc] init];
        for (int i=0; i<n; i++) {
        NSString *temp = [NSString stringWithFormat:@"%.6x", hexbuf[i]];
        [str appendString:[NSString stringWithFormat:@"%@ ", temp]];
    }