简体   繁体   中英

How to parse public key with N= and E= in golang?

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM