Skip to content
This repository was archived by the owner on Mar 24, 2025. It is now read-only.

Switching to ScaleFT/sshkeys for reading (encrypted) key data. #8

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 21 additions & 20 deletions server.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package main

import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"regexp"

"github.com/ScaleFT/sshkeys"
)

func server(config Config) {
@@ -49,7 +49,6 @@ func server(config Config) {
}

func readKeyData(config *Config) *[]byte {
// var keyData []byte
var err error
keyData := []byte(os.Getenv(KEY_DATA_ENV_VAR))
if len(keyData) == 0 {
@@ -59,23 +58,25 @@ func readKeyData(config *Config) *[]byte {
log.Fatalf("ERROR reading keyfile %s: %s!\n", config.KeyPath, err)
}
}
pemBlock, _ := pem.Decode(keyData)
if pemBlock != nil {
if x509.IsEncryptedPEMBlock(pemBlock) {
fmt.Println("Decrypting private key with passphrase...")
decoded, err := x509.DecryptPEMBlock(pemBlock, []byte(config.Pwd))
if err == nil {
header := `PRIVATE KEY` // default key type in header
matcher := regexp.MustCompile("-----BEGIN (.*)-----")
if matches := matcher.FindSubmatch(keyData); len(matches) > 1 {
header = string(matches[1])
}
keyData = pem.EncodeToMemory(
&pem.Block{Type: header, Bytes: decoded})
} else {
fmt.Printf("Error decrypting PEM-encoded secret: %s\n", err)
}
}

passphrase := []byte(config.Pwd)
var privateKey interface{}
fmt.Println("Decrypting private key with passphrase...")
privateKey, err = sshkeys.ParseEncryptedRawPrivateKey(keyData, passphrase)
Copy link
Contributor Author

@dhermes dhermes Jan 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that if passphrase is empty, this will still work provided the key isn't actually encrypted (i.e. the name ParseEncryptedRawPrivateKey is a bit misleading, since the Encrypted isn't strictly necessary)

if err != nil {
log.Fatalf("ERROR parsing encrypted key %s!\n", err)
}

fmt.Println("Converting decrypted key to RSA key...")
opts := sshkeys.MarshalOptions{Format: sshkeys.FormatClassicPEM}
var privateKeyAsPem []byte
privateKeyAsPem, err = sshkeys.Marshal(privateKey, &opts)
if err != nil {
log.Fatalf("ERROR converting private key to unencrypted PEM format %s!\n", err)
}

pemBlock, _ := pem.Decode(privateKeyAsPem)
keyData = pem.EncodeToMemory(
&pem.Block{Type: "RSA PRIVATE KEY", Bytes: pemBlock.Bytes})
return &keyData
}