eintopf.info@v0.13.16/service/auth/key.go (about) 1 // Copyright (C) 2022 The Eintopf authors 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <https://www.gnu.org/licenses/>. 15 16 package auth 17 18 import ( 19 "crypto/rand" 20 "crypto/rsa" 21 "crypto/x509" 22 "encoding/pem" 23 "fmt" 24 25 "github.com/golang-jwt/jwt/v4" 26 ) 27 28 // ParseAuthKeys parses a PEM encoded private and public rsa key pair. 29 func ParseAuthKeys(privateKey, publicKey []byte) (*rsa.PrivateKey, *rsa.PublicKey, error) { 30 priv, err := jwt.ParseRSAPrivateKeyFromPEM(privateKey) 31 if err != nil { 32 return nil, nil, fmt.Errorf("failed to parse private key: %s", err) 33 } 34 35 pub, err := jwt.ParseRSAPublicKeyFromPEM(publicKey) 36 if err != nil { 37 return nil, nil, fmt.Errorf("failed to parse public key: %s", err) 38 } 39 40 return priv, pub, nil 41 } 42 43 // CreateAuthKeys creates a PEM encoded private and public rsa key pair. 44 func CreateAuthKeys() ([]byte, []byte, error) { 45 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) 46 if err != nil { 47 return nil, nil, err 48 } 49 privateKeyBytes, err := x509.MarshalPKCS8PrivateKey(privateKey) 50 if err != nil { 51 return nil, nil, err 52 } 53 privateKeyBlock := pem.EncodeToMemory( 54 &pem.Block{ 55 Type: "PRIVATE KEY", 56 Bytes: privateKeyBytes, 57 }, 58 ) 59 60 publicKeyBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey) 61 if err != nil { 62 return nil, nil, err 63 } 64 publicKeyBlock := pem.EncodeToMemory( 65 &pem.Block{ 66 Type: "PUBLIC KEY", 67 Bytes: publicKeyBytes, 68 }, 69 ) 70 return privateKeyBlock, publicKeyBlock, nil 71 }