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

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