jwk.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  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. https://www.apache.org/licenses/LICENSE-2.0
  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. */
  13. // Package template provides utilities for working with JWK keys and PEM encoding.
  14. package template
  15. import (
  16. "crypto/x509"
  17. "github.com/lestrrat-go/jwx/v2/jwk"
  18. )
  19. func jwkPublicKeyPem(jwkjson string) (string, error) {
  20. k, err := jwk.ParseKey([]byte(jwkjson))
  21. if err != nil {
  22. return "", err
  23. }
  24. var rawkey any
  25. err = k.Raw(&rawkey)
  26. if err != nil {
  27. return "", err
  28. }
  29. mpk, err := x509.MarshalPKIXPublicKey(rawkey)
  30. if err != nil {
  31. return "", err
  32. }
  33. return pemEncode(mpk, "PUBLIC KEY")
  34. }
  35. func jwkPrivateKeyPem(jwkjson string) (string, error) {
  36. k, err := jwk.ParseKey([]byte(jwkjson))
  37. if err != nil {
  38. return "", err
  39. }
  40. var mpk []byte
  41. var pk any
  42. err = k.Raw(&pk)
  43. if err != nil {
  44. return "", err
  45. }
  46. mpk, err = x509.MarshalPKCS8PrivateKey(pk)
  47. if err != nil {
  48. return "", err
  49. }
  50. return pemEncode(mpk, "PRIVATE KEY")
  51. }