code.gitea.io/gitea@v1.22.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"
     8  	"crypto/rand"
     9  	"crypto/rsa"
    10  	"crypto/sha256"
    11  	"crypto/x509"
    12  	"encoding/pem"
    13  )
    14  
    15  // GenerateKeyPair generates a public and private keypair
    16  func GenerateKeyPair(bits int) (string, string, error) {
    17  	priv, _ := rsa.GenerateKey(rand.Reader, bits)
    18  	privPem, err := pemBlockForPriv(priv)
    19  	if err != nil {
    20  		return "", "", err
    21  	}
    22  	pubPem, err := pemBlockForPub(&priv.PublicKey)
    23  	if err != nil {
    24  		return "", "", err
    25  	}
    26  	return privPem, pubPem, nil
    27  }
    28  
    29  func pemBlockForPriv(priv *rsa.PrivateKey) (string, error) {
    30  	privBytes := pem.EncodeToMemory(&pem.Block{
    31  		Type:  "RSA PRIVATE KEY",
    32  		Bytes: x509.MarshalPKCS1PrivateKey(priv),
    33  	})
    34  	return string(privBytes), nil
    35  }
    36  
    37  func pemBlockForPub(pub *rsa.PublicKey) (string, error) {
    38  	pubASN1, err := x509.MarshalPKIXPublicKey(pub)
    39  	if err != nil {
    40  		return "", err
    41  	}
    42  	pubBytes := pem.EncodeToMemory(&pem.Block{
    43  		Type:  "PUBLIC KEY",
    44  		Bytes: pubASN1,
    45  	})
    46  	return string(pubBytes), nil
    47  }
    48  
    49  // CreatePublicKeyFingerprint creates a fingerprint of the given key.
    50  // The fingerprint is the sha256 sum of the PKIX structure of the key.
    51  func CreatePublicKeyFingerprint(key crypto.PublicKey) ([]byte, error) {
    52  	bytes, err := x509.MarshalPKIXPublicKey(key)
    53  	if err != nil {
    54  		return nil, err
    55  	}
    56  
    57  	checksum := sha256.Sum256(bytes)
    58  
    59  	return checksum[:], nil
    60  }