generate.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package signature
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "fmt"
  8. "os"
  9. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  10. )
  11. func GenerateKeyPair(keyPairName string) error {
  12. // generate a key pair
  13. keyPair, err := rsa.GenerateKey(rand.Reader, 4096)
  14. if err != nil {
  15. log.Error("Failed to generate key pair: %v", err)
  16. return err
  17. }
  18. // marshal the keys to PEM format
  19. privateKey := x509.MarshalPKCS1PrivateKey(keyPair)
  20. publicKey := x509.MarshalPKCS1PublicKey(&keyPair.PublicKey)
  21. privateKeyPem := pem.EncodeToMemory(&pem.Block{
  22. Type: "RSA PRIVATE KEY",
  23. Bytes: privateKey,
  24. })
  25. publicKeyPem := pem.EncodeToMemory(&pem.Block{
  26. Type: "RSA PUBLIC KEY",
  27. Bytes: publicKey,
  28. })
  29. // write the keys to files
  30. privateKeyPath := fmt.Sprintf("%s.private.pem", keyPairName)
  31. publicKeyPath := fmt.Sprintf("%s.public.pem", keyPairName)
  32. if err := os.WriteFile(privateKeyPath, privateKeyPem, 0644); err != nil {
  33. log.Error("Failed to write private key: %v", err)
  34. return err
  35. }
  36. if err := os.WriteFile(publicKeyPath, publicKeyPem, 0644); err != nil {
  37. log.Error("Failed to write public key: %v", err)
  38. return err
  39. }
  40. log.Info("Key pair generated successfully")
  41. log.Info("Private key: %s", privateKeyPath)
  42. log.Info("Public key: %s", publicKeyPath)
  43. return nil
  44. }