3. 将公私钥对象转化为字符串

将公私钥对象转化为字符串

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/base64"
    "log"
)

func main() {
    bits := 2048
    privatekey, publickey, err := GenRsaKey(bits)
    if err != nil {
        log.Fatalf("Cannot generate RSA key\n")
    }
    private_key, _ := DumpPrivateKeyBase64(privatekey)
    public_key, _ := DumpPublicKeyBase64(publickey)

}


func DumpPrivateKeyBase64(privatekey *rsa.PrivateKey) (string, error) {
    var keybytes []byte = x509.MarshalPKCS1PrivateKey(privatekey)

    keybase64 := base64.StdEncoding.EncodeToString(keybytes)
    return keybase64, nil
}

func DumpPublicKeyBase64(publickey *rsa.PublicKey) (string, error) {
    keybytes, err := x509.MarshalPKIXPublicKey(publickey)
    if err != nil {
        return "", err
    }

    keybase64 := base64.StdEncoding.EncodeToString(keybytes)
    return keybase64, nil
}


func GenRsaKey(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
    privateKey, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        return nil, nil, err
    }
    publicKey := &privateKey.PublicKey
    return privateKey, publicKey, nil
}

你可能感兴趣的:(3. 将公私钥对象转化为字符串)