Core components of the web application. https://write.as
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

69 linhas
1.4 KiB

  1. package activitypub
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "fmt"
  8. "log"
  9. )
  10. const keyBitSize = 2048
  11. // GenerateKey creates an RSA keypair.
  12. func GenerateKey() (*rsa.PrivateKey, error) {
  13. priv, err := rsa.GenerateKey(rand.Reader, keyBitSize)
  14. if err != nil {
  15. return nil, err
  16. }
  17. err = priv.Validate()
  18. if err != nil {
  19. return nil, err
  20. }
  21. return priv, nil
  22. }
  23. // EncodeKeysToPEM encodes public and private key to PEM format, returning
  24. // them in that order.
  25. func EncodeKeysToPEM(privKey *rsa.PrivateKey) ([]byte, []byte) {
  26. privDER := x509.MarshalPKCS1PrivateKey(privKey)
  27. // pem.Block
  28. privBlock := pem.Block{
  29. Type: "RSA PRIVATE KEY",
  30. Bytes: privDER,
  31. }
  32. // Private key in PEM format
  33. privPEM := pem.EncodeToMemory(&privBlock)
  34. // Encode public key
  35. pubKey, ok := privKey.Public().(*rsa.PublicKey)
  36. if !ok {
  37. log.Printf("Public key isn't RSA!")
  38. return nil, nil
  39. }
  40. pubDER := x509.MarshalPKCS1PublicKey(pubKey)
  41. pubBlock := pem.Block{
  42. Type: "PUBLIC KEY",
  43. Bytes: pubDER,
  44. }
  45. pubPEM := pem.EncodeToMemory(&pubBlock)
  46. return pubPEM, privPEM
  47. }
  48. // DecodePrivateKey encodes public and private key to PEM format, returning
  49. // them in that order.
  50. func DecodePrivateKey(k []byte) (*rsa.PrivateKey, error) {
  51. block, _ := pem.Decode(k)
  52. if block == nil || block.Type != "RSA PRIVATE KEY" {
  53. return nil, fmt.Errorf("failed to decode PEM block containing private key")
  54. }
  55. return x509.ParsePKCS1PrivateKey(block.Bytes)
  56. }