github.com/zntrio/harp/v2@v2.0.9/pkg/container/identity/key/generator.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package key 19 20 import ( 21 "crypto/ed25519" 22 "crypto/elliptic" 23 "encoding/base64" 24 "fmt" 25 "io" 26 27 "github.com/zntrio/harp/v2/pkg/sdk/security/crypto/deterministicecdsa" 28 29 "golang.org/x/crypto/nacl/box" 30 ) 31 32 func Legacy(random io.Reader) (*JSONWebKey, string, error) { 33 // Generate X25519 keys as identity 34 pub, priv, err := box.GenerateKey(random) 35 if err != nil { 36 return nil, "", fmt.Errorf("unable to generate identity keypair: %w", err) 37 } 38 39 // Wrap as JWK 40 return &JSONWebKey{ 41 Kty: "OKP", 42 Crv: "X25519", 43 X: base64.RawURLEncoding.EncodeToString(pub[:]), 44 D: base64.RawURLEncoding.EncodeToString(priv[:]), 45 }, base64.RawURLEncoding.EncodeToString(pub[:]), err 46 } 47 48 func Ed25519(random io.Reader) (*JSONWebKey, string, error) { 49 // Generate ed25519 keys as identity 50 pub, priv, err := ed25519.GenerateKey(random) 51 if err != nil { 52 return nil, "", fmt.Errorf("unable to generate identity keypair: %w", err) 53 } 54 55 // Wrap as JWK 56 return &JSONWebKey{ 57 Kty: "OKP", 58 Crv: "Ed25519", 59 X: base64.RawURLEncoding.EncodeToString(pub[:]), 60 D: base64.RawURLEncoding.EncodeToString(priv[:]), 61 }, fmt.Sprintf("v1.ipk.%s", base64.RawURLEncoding.EncodeToString(pub[:])), err 62 } 63 64 func P384(random io.Reader) (*JSONWebKey, string, error) { 65 // Generate ecdsa P-384 keys as identity 66 priv, err := deterministicecdsa.GenerateKey(elliptic.P384(), random) 67 if err != nil { 68 return nil, "", fmt.Errorf("unable to generate identity keypair: %w", err) 69 } 70 71 // Marshall as compressed point 72 pub := elliptic.MarshalCompressed(priv.Curve, priv.PublicKey.X, priv.PublicKey.Y) 73 74 // Wrap as JWK 75 return &JSONWebKey{ 76 Kty: "EC", 77 Crv: "P-384", 78 X: base64.RawURLEncoding.EncodeToString(priv.PublicKey.X.Bytes()), 79 Y: base64.RawURLEncoding.EncodeToString(priv.PublicKey.Y.Bytes()), 80 D: base64.RawURLEncoding.EncodeToString(priv.D.Bytes()), 81 }, fmt.Sprintf("v2.ipk.%s", base64.RawURLEncoding.EncodeToString(pub)), err 82 }