Why the signature is always 65 (1+32+32) bytes long? A signature created by the Bitcoin-Qt client can always be decoded (base64) to a 65-byte array. This array seems (according to https://github.com/bitcoin/bitcoin/blob/master/src/key.cpp#L217) to contain a header byte, a 32-byte R part, and a 32-byte S part.

I've extracted some (R,S) pairs from some ECDSA Signatures encoded in the DER format. I found that R and S are not necessarily of 32 bytes in size. They sometimes can be 33 bytes long. Could anyone tell me why the signature created by the Qt client is always 65 bytes, or whether it is OK to always convert both R and S into a 32-byte array? Thanks.
There are two different encodings used.

Everything in the Bitcoin protocol, including transaction signatures and alert signatures, uses DER encoding. This results in 71 bytes signatures (on average), as there are several header bytes, and the R and S valued are variable length.

For message signatures, a custom encoding is used which is more compact (and more recent) and supports public key recovery (given a message and a signature, find which public key would have created it). The code you're referring to in the question is for creating such signatures.

A correct DER-encoded signature has the following form:


0x30: a header byte indicating a compound structure.
A 1-byte length descriptor for all what follows.
0x02: a header byte indicating an integer.
A 1-byte length descriptor for the R value
The R coordinate, as a big-endian integer.
0x02: a header byte indicating an integer.
A 1-byte length descriptor for the S value.
The S coordinate, as a big-endian integer.


Where initial 0x00 bytes for R and S are not allowed, except when their first byte would otherwise be above 0x7F (in which case a single 0x00 in front is required). Also note that inside transaction signatures, an extra hashtype byte follows the actual signature data.