Skip to content

Instantly share code, notes, and snippets.

@arrieta
Last active January 28, 2021 03:06
Show Gist options
  • Save arrieta/13870cf587dbf3fc1cadcf3736131d00 to your computer and use it in GitHub Desktop.
Save arrieta/13870cf587dbf3fc1cadcf3736131d00 to your computer and use it in GitHub Desktop.
AWS Lambda Generate Key Pair (Go)
// 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