code.gitea.io/gitea@v1.19.3/modules/util/keypair.go (about)

     1  // Copyright 2021 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package util
     5  
     6  import (
     7  	"crypto/rand"
     8  	"crypto/rsa"
     9  	"crypto/x509"
    10  	"encoding/pem"
    11  )
    12  
    13  // GenerateKeyPair generates a public and private keypair
    14  func GenerateKeyPair(bits int) (string, string, error) {
    15  	priv, _ := rsa.GenerateKey(rand.Reader, bits)
    16  	privPem, err := pemBlockForPriv(priv)
    17  	if err != nil {
    18  		return "", "", err
    19  	}
    20  	pubPem, err := pemBlockForPub(&priv.PublicKey)
    21  	if err != nil {
    22  		return "", "", err
    23  	}
    24  	return privPem, pubPem, nil
    25  }
    26  
    27  func pemBlockForPriv(priv *rsa.PrivateKey) (string, error) {
    28  	privBytes := pem.EncodeToMemory(&pem.Block{
    29  		Type:  "RSA PRIVATE KEY",
    30  		Bytes: x509.MarshalPKCS1PrivateKey(priv),
    31  	})
    32  	return string(privBytes), nil
    33  }
    34  
    35  func pemBlockForPub(pub *rsa.PublicKey) (string, error) {
    36  	pubASN1, err := x509.MarshalPKIXPublicKey(pub)
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  	pubBytes := pem.EncodeToMemory(&pem.Block{
    41  		Type:  "PUBLIC KEY",
    42  		Bytes: pubASN1,
    43  	})
    44  	return string(pubBytes), nil
    45  }