curve25519.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package all
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "fmt"
  6. "golang.org/x/crypto/curve25519"
  7. )
  8. func Curve25519Genkey(StdEncoding bool, input_base64 string) {
  9. var output string
  10. var err error
  11. var privateKey, publicKey []byte
  12. var encoding *base64.Encoding
  13. if *input_stdEncoding || StdEncoding {
  14. encoding = base64.StdEncoding
  15. } else {
  16. encoding = base64.RawURLEncoding
  17. }
  18. if len(input_base64) > 0 {
  19. privateKey, err = encoding.DecodeString(input_base64)
  20. if err != nil {
  21. output = err.Error()
  22. goto out
  23. }
  24. if len(privateKey) != curve25519.ScalarSize {
  25. output = "Invalid length of private key."
  26. goto out
  27. }
  28. }
  29. if privateKey == nil {
  30. privateKey = make([]byte, curve25519.ScalarSize)
  31. if _, err = rand.Read(privateKey); err != nil {
  32. output = err.Error()
  33. goto out
  34. }
  35. }
  36. // Modify random bytes using algorithm described at:
  37. // https://cr.yp.to/ecdh.html.
  38. privateKey[0] &= 248
  39. privateKey[31] &= 127 | 64
  40. if publicKey, err = curve25519.X25519(privateKey, curve25519.Basepoint); err != nil {
  41. output = err.Error()
  42. goto out
  43. }
  44. output = fmt.Sprintf("Private key: %v\nPublic key: %v",
  45. encoding.EncodeToString(privateKey),
  46. encoding.EncodeToString(publicKey))
  47. out:
  48. fmt.Println(output)
  49. }