Search code examples
encodinggodigital-signaturebigintegerder

Go, DER and handling big integers


I want to create a Google Go application that will be able to DER encode and decode big integers (namely, ECDSA signature r and s). From what I understand I should use the asn1 package, but what functions should I be calling?

For example, I want to encode

316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d

and

bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc812

to get this:

30450220316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d022100bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc81201

and vice versa. Which function should I call for encoding, and which for decoding and how?


Solution

  • You need to encode an ASN.1 sequence containing both r and s integers as follows:

    ECDSA-Sig-Value ::= SEQUENCE {
      r INTEGER,
      s INTEGER }
    

    Please note that I am not a Go developer but according to the documentation Marshal and Unmarshal functions seems to accept structs in order to encode/decode ASN.1 sequences.

    This code sample seems to work for both encoding and decoding:

    package main
    
    import (
        "fmt"
        "big"
        "asn1"
    )
    
    type ecdsa struct {
        R, S *big.Int
    }
    
    func main() {
        r, _ := new(big.Int).SetString("316eb3cad8b66fcf1494a6e6f9542c3555addbf337f04b62bf4758483fdc881d", 16);
        s, _ := new(big.Int).SetString("bf46d26cef45d998a2cb5d2d0b8342d70973fa7c3c37ae72234696524b2bc812", 16);
        sequence := ecdsa{r, s}
        encoding, _ := asn1.Marshal(sequence)
        fmt.Println(encoding)
        dec := new(ecdsa)
        asn1.Unmarshal(encoding, dec)
        fmt.Println(dec)
    }