Save and load crypto/rsa PrivateKey to and from the disk

前端 未结 4 1128
萌比男神i
萌比男神i 2021-01-30 10:13

I\'m using crypto/rsa, and trying to find a way to properly save and load a key. Is there a correct way to create a []byte from an rsa.P

4条回答
  •  故里飘歌
    2021-01-30 10:51

    Since the public key part of your question wasn't answered and I just ran into the same problem and solved it, here it is:

    Note the & in front of the Argument to MarshalPKIXPublicKey

    Priv := rsa.GenerateKey(rand.Reader, 4096)
    
    pubASN1, err := x509.MarshalPKIXPublicKey(&Priv.PublicKey)
    if err != nil {
        // do something about it
    }
    
    pubBytes := pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PUBLIC KEY",
        Bytes: pubASN1,
    })
    
    ioutil.WriteFile("key.pub", pubBytes, 0644)
    

    Relevant reads:

    • MarshalPKIXPublicKey(pub interface{}) ([]byte, error) godoc
    • EncodeToMemory(b *Block) []byte godoc
    • Block godoc

    PS: MarshalPKIXPublicKey also accepts ECDSA keys, ajust the pem header appropriately.

提交回复
热议问题