Can $r$ and $s$ from an ECDSA signature be negative numbers? I have an ECDSA implementation in Mathematica over secp256k1 and $r$ and $s$ are always positive numbers. But if you encode them as bytes, the most significant byte can be over 0x80, which would make it a negative number if the big-number is interpreted as being signed.

I'm asking because the bitcoin implementation has these checks which I don't understand:

if (S[0] &amp; 0x80)
    return error("Non-canonical signature: S value negative");
if (R[0] &amp; 0x80)
    return error("Non-canonical signature: R value negative");


The $r$ and $s$ values that I produce seem that they would fail these checks when they are larger than $2^{255}$
You appear to be testing a DER-encoded integer.

DER-encoded integers are defined so that they can encode both positive and negative values (in cryptography, we don't need to encode negative integers all that often; however ASN.1 isn't specific to cryptography).

DER-encoded integers are defined this way:


Positive values are represented by the minimal number of bytes that can represent the integer (in bigendian byte order), with the msbit of the initial byte being clear.


For example, the value 32768 would be represented by the three bytes 0x00 0x80 0x00.  We are not allowed to use the two octets 0x80 0x00, because 0x80 has the msbit set

Negative values are represented by the minimal number of bytes that can represent the integer (in two's complement notation), with the msbit of the initial byte being set.
Zero is represented as a single 0x00 byte


Hence, testing the msbit of the initial byte will correctly tell you whether the represented integer is nonnegative.