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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package activitypub
  5. import (
  6. "crypto/rand"
  7. "crypto/rsa"
  8. "crypto/x509"
  9. "encoding/pem"
  10. )
  11. const rsaBits = 2048
  12. // GenerateKeyPair generates a public and private keypair for signing actions by users for activitypub purposes
  13. func GenerateKeyPair() (string, string, error) {
  14. priv, _ := rsa.GenerateKey(rand.Reader, rsaBits)
  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. }