certificate_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package otlptracehttp_test
  15. import (
  16. "bytes"
  17. "crypto/ecdsa"
  18. "crypto/elliptic"
  19. "crypto/rand"
  20. "crypto/x509"
  21. "crypto/x509/pkix"
  22. "encoding/pem"
  23. "math/big"
  24. "net"
  25. "time"
  26. )
  27. type pemCertificate struct {
  28. Certificate []byte
  29. PrivateKey []byte
  30. }
  31. // Based on https://golang.org/src/crypto/tls/generate_cert.go,
  32. // simplified and weakened.
  33. func generateWeakCertificate() (*pemCertificate, error) {
  34. priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  35. if err != nil {
  36. return nil, err
  37. }
  38. keyUsage := x509.KeyUsageDigitalSignature
  39. notBefore := time.Now()
  40. notAfter := notBefore.Add(time.Hour)
  41. serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
  42. serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
  43. if err != nil {
  44. return nil, err
  45. }
  46. template := x509.Certificate{
  47. SerialNumber: serialNumber,
  48. Subject: pkix.Name{
  49. Organization: []string{"otel-go"},
  50. },
  51. NotBefore: notBefore,
  52. NotAfter: notAfter,
  53. KeyUsage: keyUsage,
  54. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  55. BasicConstraintsValid: true,
  56. DNSNames: []string{"localhost"},
  57. IPAddresses: []net.IP{net.IPv6loopback, net.IPv4(127, 0, 0, 1)},
  58. }
  59. derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
  60. if err != nil {
  61. return nil, err
  62. }
  63. certificateBuffer := new(bytes.Buffer)
  64. if err := pem.Encode(certificateBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
  65. return nil, err
  66. }
  67. privDERBytes, err := x509.MarshalPKCS8PrivateKey(priv)
  68. if err != nil {
  69. return nil, err
  70. }
  71. privBuffer := new(bytes.Buffer)
  72. if err := pem.Encode(privBuffer, &pem.Block{Type: "PRIVATE KEY", Bytes: privDERBytes}); err != nil {
  73. return nil, err
  74. }
  75. return &pemCertificate{
  76. Certificate: certificateBuffer.Bytes(),
  77. PrivateKey: privBuffer.Bytes(),
  78. }, nil
  79. }