What are the first 4 and last 2 bytes in DH parameter files? When we generate DH parameters file in PEM format, like this:

-----BEGIN DH PARAMETERS-----
MCYCIQDyl7rfGI2GywHp7JC7juWhv3VL+skipzl/329sQCEBQwIBAg==
-----END DH PARAMETERS-----


or

-----BEGIN DH PARAMETERS-----
MIGHAoGBAdilyft4T5FJO0xga8hzoBcUmAZRTlxE930Dfda4LaC8TFsQkibgUYPJ
AuFWuAnKgjWjLH80Pt1shilYdd8b7vL2TL2/e3BBNr4sr8DJLLa7p04mt0t4CSKO
Cp+/pqanm6Mq9xJ3Wo4SDrx70czGhwi5ZNLwwusez9Djwq8dX8IDAgEC
-----END DH PARAMETERS-----


besides additional header and footer lines, there are 4 bytes at first and 2 bytes at the end of the base64 line, and it depends to the DH parameters. How I can generate them knowing DH parameters?
PEM consists of a header and footer that identify the object that has been encoded. It may sometimes also contain some arguments behind the header line. The actual data is base 64 encoded. You can view the contents by decoding it using a base 64 encoding.

Now the DH parameters are encoded using ASN.1 BER, which is a binary encoding. This encoding is used for most if not all PEM encoded structures. ASN.1 is a data description language. ASN.1 structures can be seen as a tree with constructed nodes (sequences) and primitive nodes (strings, byte arrays, integers and such) all using network ordering. These nodes are generally encoded using tag-length-value (TLV) encoding. As the tag for a SEQUENCE is the value 30 (in hex), the first base 64 letter is almost certainly an M.

The version of base 64 used by PEM pads anything that isn't a multiple of 4 characters (three bytes) to 4 characters using the = character.

So the first characters and the amount of = characters at the end is mainly dependent on the size of the parameters rather than their value.



This is the contents of the ASN.1 tree in the contents of your PEM text:

SEQUENCE(2 elem)
  INTEGER(256 bit) 1097277930034063274792561151504789680016548759529511363308187422232757…
  INTEGER2


and

SEQUENCE(2 elem)
  INTEGER(1025 bit) 331904441233693192104476260016584324479133460055459757886261577377912…
  INTEGER2


generated using the ASN.1 decoder here.