1

I am generating a key pair in Koltin and saving them into two files, when trying to read these files in any other language than go, it causes and error "Invalid key format".

Here the go Code which generates the keys, encodes them and saves them into pem files. The privatekey should be PKCS8 encoded and the publickey X509 encoded.

func ExportPublicKeyAsPemStr(pubkey *rsa.PublicKey) string {
    pubkeyPem := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY",Bytes: x509.MarshalPKCS1PublicKey(pubkey)}))
    err := createFile("C:/tmp/publickey.pub", pubkeyPem)
    if err != nil {
        panic(err)
    }
    return pubkeyPem
}
func ExportPrivateKeyAsPemStr(privatekey *rsa.PrivateKey) string {
    privatekeyBytes, err := x509.MarshalPKCS8PrivateKey(privatekey)
    if err != nil {
        panic(err)
    }
    privatekeyPem := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY",Bytes: privatekeyBytes}))
    err = createFile("C:/tmp/privatekey.key", privatekeyPem)
    if err != nil {
        panic(err)
    }
    return privatekeyPem
}
func ExportMsgAsPemStr(msg []byte) string {
    msgPem := string(pem.EncodeToMemory(&pem.Block{Type: "MESSAGE",Bytes: msg}))
    err := createFile("C:/tmp/message.pem", msgPem)
    if err != nil {
        panic(err)
    }
    return msgPem
}
func main() {
    bits := 2048
    flag.Parse()
    //args := flag.Args()
    //m:=args[0]
    bobPrivateKey, _ := rsa.GenerateKey(rand.Reader,bits)

    bobPublicKey := &bobPrivateKey.PublicKey
    fmt.Printf("%s\n",  ExportPrivateKeyAsPemStr(bobPrivateKey))
    fmt.Printf("%s\n", ExportPublicKeyAsPemStr(bobPublicKey))
    message := []byte("This is a message with confidential text")
    label := []byte("")
    hash := sha256.New()
    ciphertext, _ := rsa.EncryptOAEP(hash, rand.Reader, bobPublicKey, message,label)
    fmt.Printf("%s\n",ExportMsgAsPemStr(ciphertext))
    plainText, _:= rsa.DecryptOAEP(hash, rand.Reader, bobPrivateKey, ciphertext, label)
    fmt.Printf("RSA decrypted to [%s]", plainText)
}

func createFile(name string, data string) error {
    f, err := os.Create(name)
    if err != nil {
        return err
    }
    defer f.Close()
    _, err = f.WriteString(data)
    if err != nil {
        return err
    }
    return nil
}

Here some sample content of the two pem files: Privatekey:

-----BEGIN RSA PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDB6TI3vNW8+aDx
yzkI5AFIge6O8qPN2DSS7btnwx3AkMWmLg2PY6y5ocs0riZpSKV7fFCJ9+JVhC2r
cSmV6EGaq4r6mHrcX26m/5YMNk+93k1E30Q3JlFyoSkTB2zzt8qKP0rvvimMcI56
uyRiI0LuGdlUqQZ4c0yhyimyHms4vdc6IY3PBFF7V+AKpWkyTmWlUffx987rRp9l
jefz27dsqqv31JvJhBVtQVTAjMSB/vuV0cw6VIBrTBWK5i/zj6NqKp18MEJrugpj
BPqMErKx0Q3oMQ4iIhW1/+kuyyIYoSInTAERqX03nEp+0XETjsZUK6xUxDOtaeFQ
qMhN9F6lAgMBAAECggEAeSFeIFlSv0DE3CZR047yikO4LQ2/a3fSp7Hf7pqA/Giz
PvLnv5nJLRC3qonbLsuVrATlHrp9ZWQzTzRagO1cBe2A3Lfhj8YBjkp8hdZri7TR
WeOKblT+bffke6GY2soFuMR+4DJPLA6nwl0jBjb2uVvmWi9X/mgwB6UM1NqRqhg9
rT0Ct0vd5tBtMsEdl5pY7MRaEIfkM4pOC9ZOqv1791EXnO4io5qQgwOYhSJdOb/4
xavs3gUs+qbJr2dF67vk9RimCNetBdWe917As8QC42JZJcjLupeFwnqRgYGk7ByX
/gkP+rv3XOFr16UZe3RmDBPfxNdQIQYM2LmlUG5XRQKBgQDObRXQCO/YOZSqfgJZ
bHo82qY8dv1jR89+SS6JowVbMODaEZnrfCjfediOuiw1siw6bHKoOwXpVZnPoYUa
drvdM7S86d/54mBNMU9XqecWsybmlIovnlcob0+zUMUKoaW0jf+xgu8zkwYrtNKW
rmaSYylyKDjrSL4Zo6HufDUe+wKBgQDweq/U+9XL6ev0ejTww88w5SbD5d7rqGCQ
aSdH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PUBLIC KEY-----

Now if I for example enter them into this website or this one(Algorithm RS256) I get an InvalidKeyException...

Could someone tell what I am doing wrong?

  • 3
    Your private key seems to be a Pkcs8-key, but it has the wrong start- and end-line which should be `-----BEGIN PRIVATE KEY-----` and `-----END PRIVATE KEY-----`. Your public key seems to be a public Pkcs1-key, but not an X.509-key. I suspect that the `MarshalPKIXPublicKey`-method must be used to generate an X.509-key whose start- and end-line is `-----BEGIN PUBLIC KEY-----` and `-----END PUBLIC KEY-----`. For an overview of the different formats see [here](https://stackoverflow.com/a/49878687/9014097) and [here](https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem). – Topaco Oct 16 '19 at 09:08
  • The PEM header and footer are indeed correct the way you do it. Also what you suspected proved to be right. Thx a lot – mait.taim Oct 16 '19 at 10:02

0 Answers0