3

I have a mbedtls-generated RSA public key, created on an embedded device that I need to parse in Golang. My key is not in pem format, only contains the modulus and exponent and looks like this:

N = 9C99AB1DC1462220A628D19BB6C6627FDCCC208FD9F93722F44515F5086F3312D3EFE256A11789F1F7F9A114B879A2DE0005FAE99A68321DD821CE589D1F6E0D
E = 010001

I am sure I could I could parse this myself, but since you should just about never implement your own crypto methods and Golang has a very complete suite of functionality, what can I do to create an rsa.PublicKey from this?

I could generate a PEM key but this seems like a big waste

Thank you

Ali Afshar
  • 40,967
  • 12
  • 95
  • 109

1 Answers1

7

There is nothing wrong with parsing your own input, I wouldn't call this "reimplementing crypto primitives".

To get the public key, simply parse the modulus into a big integer:

bigN.SetString("9C99AB1DC1462220A628D...", 16)

Then create your own rsa.PublicKey.

Full example in the playground:

N := "9C99AB1DC1462220A628D19BB6C6627FDCCC208FD9F93722F44515F5086F3312D3EFE256A11789F1F7F9A114B879A2DE0005FAE99A68321DD821CE589D1F6E0D"
E := 010001
bigN := new(big.Int)
_, ok := bigN.SetString(N, 16)
if !ok {
    panic("failed to parse")
}
pub := rsa.PublicKey{
    N: bigN,
    E: E,
}
fmt.Println(pub)
Marc
  • 19,394
  • 6
  • 47
  • 51