gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 := pemBlockForPriv(priv)
  16. pubPem, err := pemBlockForPub(&priv.PublicKey)
  17. if err != nil {
  18. return "", "", err
  19. }
  20. return privPem, pubPem, nil
  21. }
  22. func pemBlockForPriv(priv *rsa.PrivateKey) string {
  23. privBytes := pem.EncodeToMemory(&pem.Block{
  24. Type: "RSA PRIVATE KEY",
  25. Bytes: x509.MarshalPKCS1PrivateKey(priv),
  26. })
  27. return string(privBytes)
  28. }
  29. func pemBlockForPub(pub *rsa.PublicKey) (string, error) {
  30. pubASN1, err := x509.MarshalPKIXPublicKey(pub)
  31. if err != nil {
  32. return "", err
  33. }
  34. pubBytes := pem.EncodeToMemory(&pem.Block{
  35. Type: "PUBLIC KEY",
  36. Bytes: pubASN1,
  37. })
  38. return string(pubBytes), nil
  39. }
  40. // CreatePublicKeyFingerprint creates a fingerprint of the given key.
  41. // The fingerprint is the sha256 sum of the PKIX structure of the key.
  42. func CreatePublicKeyFingerprint(key crypto.PublicKey) ([]byte, error) {
  43. bytes, err := x509.MarshalPKIXPublicKey(key)
  44. if err != nil {
  45. return nil, err
  46. }
  47. checksum := sha256.Sum256(bytes)
  48. return checksum[:], nil
  49. }