return of CERT_FindUserCertByUsage in javascript

112 views Asked by At

I am trying to understand the relationship between C++ dll and JavaScript. There is a js code:

cert = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null);

where cert is defined as

let cert = null;

However in C++, cert is a struct

CERTCertificateStr {
    char *subjectName;
    char *issuerName;
    SECItem derCert;            /* original DER for the cert */
    .... }

I am trying to get the subject name in javascript and I continue the code with

let a = cert.contents.subjectName; 

It is unsuccessful. It logs error as "cannot get content of undefined size"

Anything that i have missed in between C++ and javascript? How can i print the subjectName in javascript?

1

There are 1 answers

1
Noitidart On

I think you are doing jsctypes and you are on the right track. To get the js string though you have to tag on a readString() after casting it to an array with a certain length, its ok to go past the actual length as readString() will read up till the first null char which is \x00. Although if you know the exact length that's always best (you dont have to do the length + 1 for null term) because then you save memory as you dont have to unnecessarily allocate a buffer (array in jsctypes case) more then the length needed.

So try this:

let a = ctypes.cast(cert.contents.subjectName, ctypes.char.array(100).ptr).contents.readString();
console.log('a:', a);

The error cannot get contents of undefined size happens in situations like this:

var a = ctypes.voidptr_t(ctypes.char.array()('rawr'))
console.log('a:', a.contents);

this spits out

Error: cannot get contents of undefined size

So in order to fix that what we do is this:

var b = ctypes.cast(a, ctypes.char.array(5).ptr)
console.log('b:', b.contents);

and this succesfully accesses contents, it gives us (by the way, i used 5 for length which is 4 for the length of rawr + 1 for null terminator but i really didnt have to do that i could have used length of just 4)

CData { length: 5 }

so now we can read the contents as a js string like this:

console.log('b:', b.contents.readString());

and this spits out:

rawr

ALSO, you said the functions returns a struct, does it return a pointer to the struct? Or actually the struct? I would think it returns a pointer to the struct no? so in that case you would do this:

let certPtr = CERT_FindUserCertByUsage(certDB, certName.nickname,certUsageEmailSigner, true, null);

let certStruct = ctypes.StructType('CERTCertificateStr', [
   {'subjectName': ctypes.char.ptr},
   {issuerName: ctypes.char.ptr},
   {derCert: ctypes.voidptr_t}
]);

let cert = ctypes.cast(certPtr, certStruct.ptr).contents;
let a = cert.contents.subjectName.readString();