Last active
January 28, 2021 03:06
-
-
Save arrieta/13870cf587dbf3fc1cadcf3736131d00 to your computer and use it in GitHub Desktop.
AWS Lambda Generate Key Pair (Go)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sample code used to generate a cryptographic key pair via an AWS Lambda function. | |
// (C) 2019 Nabla Zero Labs | |
// MIT License | |
package main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/pem" | |
"golang.org/x/crypto/ssh" | |
"github.com/aws/aws-lambda-go/lambda" | |
) | |
type KeyPairRequest struct { | |
User string `json:"user"` | |
} | |
type KeyPairResponse struct { | |
User string `json:"user"` | |
KeyLength int `json:"key_length"` | |
PrivateKey string `json:"private_key"` | |
PublicKey string `json:"public_key"` | |
} | |
func main() { | |
lambda.Start(HandleKeyPairRequest) | |
} | |
func HandleKeyPairRequest(request KeyPairRequest) (KeyPairResponse, error) { | |
keyLength := 2048 | |
privateKey, err := rsa.GenerateKey(rand.Reader, keyLength) | |
if err != nil { | |
return KeyPairResponse{}, err | |
} | |
err = privateKey.Validate() | |
if err != nil { | |
return KeyPairResponse{}, err | |
} | |
publicKeyRSA, err := ssh.NewPublicKey(&privateKey.PublicKey) | |
if err != nil { | |
return KeyPairResponse{}, err | |
} | |
publicKey := ssh.MarshalAuthorizedKey(publicKeyRSA) | |
privateBlock := pem.Block{ | |
Type: "RSA PRIVATE KEY", | |
Headers: nil, | |
Bytes: x509.MarshalPKCS1PrivateKey(privateKey)} | |
privatePEM := pem.EncodeToMemory(&privateBlock) | |
return KeyPairResponse{ | |
User: request.User, | |
KeyLength: keyLength, | |
PrivateKey: string(privatePEM), | |
PublicKey: string(publicKey)}, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment