keys, oidcIdP

This commit is contained in:
kkb0318
2024-03-26 21:25:25 +09:00
parent e33ea809f0
commit 022c561938
5 changed files with 195 additions and 56 deletions
+34 -54
View File
@@ -1,72 +1,52 @@
package selfhosted
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
jose "github.com/go-jose/go-jose/v4"
"k8s.io/client-go/util/keyutil"
"encoding/pem"
"os"
)
// keyIDFromPublicKey derives a key ID non-reversibly from a public key.
//
// The Key ID is field on a given on JWTs and JWKs that help relying parties
// pick the correct key for verification when the identity party advertises
// multiple keys.
//
// Making the derivation non-reversible makes it impossible for someone to
// accidentally obtain the real key from the key ID and use it for token
// validation.
// This method is copied from
// https://github.com/kubernetes/kubernetes/blob/v1.29.3/pkg/serviceaccount/jwt.go#L99
func keyIDFromPublicKey(publicKey interface{}) (string, error) {
publicKeyDERBytes, err := x509.MarshalPKIXPublicKey(publicKey)
func createKeyPair() error {
// RSAキーペアの生成
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return "", fmt.Errorf("failed to serialize public key to DER format: %v", err)
return err
}
hasher := crypto.SHA256.New()
hasher.Write(publicKeyDERBytes)
publicKeyDERHash := hasher.Sum(nil)
keyID := base64.RawURLEncoding.EncodeToString(publicKeyDERHash)
return keyID, nil
}
type JWK struct {
Keys []jose.JSONWebKey `json:"keys"`
}
func NewJWK(pub []byte) (*JWK, error){
pubKeys, err := keyutil.ParsePublicKeysPEM(pub)
// private keyをPEM形式で保存
privPem := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
privPemFile, err := os.Create("private_key.pem")
if err != nil {
return nil, err
return err
}
pubKey := pubKeys[0]
var alg jose.SignatureAlgorithm
switch pubKey.(type) {
case *rsa.PublicKey:
alg = jose.RS256
default:
return nil, errors.New("public key is not RSA")
defer privPemFile.Close()
if err := pem.Encode(privPemFile, &privPem); err != nil {
return err
}
kid, err := keyIDFromPublicKey(pubKey)
// 公開鍵をPKIX, ASN.1 DER形式に変換
pubASN1, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey)
if err != nil {
return nil, err
return err
}
var keys []jose.JSONWebKey
keys = append(keys, jose.JSONWebKey{
Key: pubKey,
KeyID: kid,
Algorithm: string(alg),
Use: "sig",
})
return &JWK{Keys: keys}, nil
// 公開鍵をPEM形式で保存
pubPem := pem.Block{
Type: "PUBLIC KEY",
Bytes: pubASN1,
}
pubPemFile, err := os.Create("public_key.pem")
if err != nil {
return err
}
defer pubPemFile.Close()
if err := pem.Encode(pubPemFile, &pubPem); err != nil {
return err
}
return nil
}