mconnect - KDE Connect protocol implementation in Vala/C
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.

77 lines
1.9 KiB

  1. // Licensed under the Apache License, Version 2.0 (the "License");
  2. // you may not use this file except in compliance with the License.
  3. // You may obtain a copy of the License at
  4. //
  5. // http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Unless required by applicable law or agreed to in writing, software
  8. // distributed under the License is distributed on an "AS IS" BASIS,
  9. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. // See the License for the specific language governing permissions and
  11. // limitations under the License.
  12. package protocol
  13. import (
  14. "crypto/ecdsa"
  15. "crypto/elliptic"
  16. "crypto/rand"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "crypto/x509/pkix"
  20. "math/big"
  21. "time"
  22. )
  23. type DeviceCertificate struct {
  24. key *ecdsa.PrivateKey
  25. cert []byte
  26. }
  27. func (d *DeviceCertificate) TLSCertificate() *tls.Certificate {
  28. return &tls.Certificate{
  29. PrivateKey: d.key,
  30. Certificate: [][]byte{d.cert},
  31. }
  32. }
  33. // GenerateDeviceCertificate returns a device certificate
  34. func GenerateDeviceCertificate(entity string) (*DeviceCertificate, error) {
  35. limit := big.Int{}
  36. limit.Lsh(big.NewInt(1), 128)
  37. serial, err := rand.Int(rand.Reader, &limit)
  38. if err != nil {
  39. return nil, err
  40. }
  41. priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  42. if err != nil {
  43. return nil, err
  44. }
  45. startTime := time.Now()
  46. // 10 years from now
  47. expireTime := startTime.AddDate(10, 0, 0)
  48. template := x509.Certificate{
  49. SerialNumber: serial,
  50. Subject: pkix.Name{
  51. CommonName: entity,
  52. Organization: []string{"mconnect"},
  53. OrganizationalUnit: []string{"mconnect"},
  54. },
  55. NotBefore: startTime,
  56. NotAfter: expireTime,
  57. BasicConstraintsValid: true,
  58. }
  59. selfSign := template
  60. cert, err := x509.CreateCertificate(rand.Reader, &template, &selfSign,
  61. &priv.PublicKey, priv)
  62. if err != nil {
  63. return nil, err
  64. }
  65. devcert := &DeviceCertificate{
  66. key: priv,
  67. cert: cert,
  68. }
  69. return devcert, nil
  70. }