简体   繁体   中英

determien leading zeros in serialnumber

Hi I currently got the problem that I want to create a representation of serial numbers from X509-certificates that match exactly the hex representation in a .crt file. In order to get a feeling of this I created a number of certificates and translated the BigInteger representation to hex like this:

public static String toHex (String number) {
    BigInteger toHex = new BigInteger(number, 10);
    String hex = toHex.toString(16);
    if (hex.trim().length()%2 == 1) {
        hex = "0" + hex;
    }
    hex = hex.replaceAll("(?<=..)(..)", " $1");
    return hex;
}

my problem now is that this does not work at all. I found at least one serial number representation where this code fails:

BigInteger: 186553134784695772803573402931138131429
Hex from .crt: 00 8c 58 d3 ac 72 fc 2f 17 70 cd 17 a5 07 d3 f5 e5

there are 2 leading zeros and I cannot figure out why and in which cases these leading zeros are added. Is anyone able to help me?

Ps: I do not want to remove the leading zeros I really want to add them.

The .crt file is encoded using DER encoding. For an INTEGER the two's complement form, most significant digit first, with the minimum number of octets must be used. Since the value you have picked is positive but starts with 0x8c..., a zero octet must be prefixed to keep the most significant bit from making it a negative number.

I don't think you need help writing the code to test the first digit (after making it an even number of digits) to determine that a "00" must be prefixed.

Producing exactly the same number of octets as in the .crt file only makes sense when you need to compare the octets from that file. It would, however, be more reliable to decode the .crt using some DER decoder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM