You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

keypair.go 1.4KB

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