github.com/greenpau/go-authcrunch@v1.1.4/internal/tests/crypto.go (about) 1 // Copyright 2022 Paul Greenberg greenpau@outlook.com 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package tests 16 17 import ( 18 "crypto/rand" 19 "crypto/rsa" 20 "crypto/x509" 21 "encoding/pem" 22 "golang.org/x/crypto/ssh" 23 "testing" 24 ) 25 26 // GetCryptoKeyPair returns private-public key pair. 27 func GetCryptoKeyPair(t *testing.T, keyAlgo, publicKeyType string) (string, string) { 28 switch keyAlgo { 29 case "rsa": 30 default: 31 t.Fatalf("unsupported key algorithm: %s", keyAlgo) 32 } 33 switch publicKeyType { 34 case "openssh", "rsa": 35 default: 36 t.Fatalf("unsupported public key type: %s", publicKeyType) 37 } 38 39 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) 40 if err != nil { 41 t.Fatalf("failed generating private key: %v", err) 42 } 43 if err := privateKey.Validate(); err != nil { 44 t.Fatalf("failed validating private key: %v", err) 45 } 46 privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey) 47 privateKeyPEM := pem.EncodeToMemory( 48 &pem.Block{ 49 Type: "RSA PRIVATE KEY", 50 Bytes: privateKeyBytes, 51 }, 52 ) 53 // t.Logf("private rsa key:\n%s", string(privateKeyPEM)) 54 55 switch publicKeyType { 56 case "openssh": 57 // Create OpenSSH formatted string 58 publicKeyOpenSSH, err := ssh.NewPublicKey(privateKey.Public()) 59 if err != nil { 60 t.Fatalf("failed creating openssh key: %v", err) 61 } 62 authorizedKeyBytes := ssh.MarshalAuthorizedKey(publicKeyOpenSSH) 63 return string(privateKeyPEM), string(authorizedKeyBytes) 64 } 65 66 // Derive Public Key 67 publicKeyBytes, err := x509.MarshalPKIXPublicKey(privateKey.Public()) 68 if err != nil { 69 t.Fatalf("failed creating rsa public key: %v", err) 70 } 71 // Create PEM encoded string 72 publicKeyPEM := pem.EncodeToMemory( 73 &pem.Block{ 74 Type: "RSA PUBLIC KEY", 75 Bytes: publicKeyBytes, 76 }, 77 ) 78 return string(privateKeyPEM), string(publicKeyPEM) 79 }