2 // ========================LICENSE_START=================================
5 // Copyright (C) 2022: Nordix Foundation
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
11 // http://www.apache.org/licenses/LICENSE-2.0
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 // ========================LICENSE_END===================================
30 "golang.org/x/crypto/ssh"
36 Keys []Key `json:"keys"`
39 Kid string `json:"kid,omitempty"`
40 Kty string `json:"kty"`
41 Use string `json:"use"`
44 X5c []string `json:"x5c"`
45 X5t string `json:"x5t"`
48 func getKeyFromPrivate(key []byte) *rsa.PublicKey {
49 parsed, err := ssh.ParseRawPrivateKey(key)
54 // Convert back to an *rsa.PrivateKey
55 privateKey := parsed.(*rsa.PrivateKey)
57 publicKey := &privateKey.PublicKey
61 func getKeyFromPublic(key []byte) *rsa.PublicKey {
62 pubPem, _ := pem.Decode(key)
64 parsed, err := x509.ParsePKIXPublicKey(pubPem.Bytes)
66 fmt.Println("Unable to parse RSA public key", err)
69 // Convert back to an *rsa.PublicKey
70 publicKey := parsed.(*rsa.PublicKey)
75 func getCert(cert []byte) *x509.Certificate {
76 certPem, _ := pem.Decode(cert)
78 panic("Failed to parse pem file")
82 certificate, err := x509.ParseCertificate(certPem.Bytes)
84 fmt.Println("Unable to parse Certificate", err)
90 func getPublicKeyFromCert(cert_bytes []byte) *rsa.PublicKey {
91 block, _ := pem.Decode([]byte(cert_bytes))
92 var cert *x509.Certificate
93 cert, _ = x509.ParseCertificate(block.Bytes)
94 rsaPublicKey := cert.PublicKey.(*rsa.PublicKey)
99 func CreateJWKS(certFile string) string {
100 var publicKey *rsa.PublicKey
102 cert, err := ioutil.ReadFile(certFile)
106 publicKey = getPublicKeyFromCert(cert)
108 certificate := getCert(cert)
109 // generate fingerprint with sha1
110 // you can also use md5, sha256, etc.
111 fingerprint := sha1.Sum(certificate.Raw)
118 N: base64.RawStdEncoding.EncodeToString(publicKey.N.Bytes()),
119 E: base64.RawStdEncoding.EncodeToString(big.NewInt(int64(publicKey.E)).Bytes()),
120 X5c: []string{base64.RawStdEncoding.EncodeToString(certificate.Raw)},
121 X5t: base64.RawStdEncoding.EncodeToString(fingerprint[:]),
123 jwksKeys := []Key{jwksKey}
124 jwks := Jwks{jwksKeys}
126 jwksJson, err := json.Marshal(jwks)
131 return string(jwksJson)