How to use encrypted private key with golang ssh

I would appreciate pointers because I can't figure out how to decrypt the encrypted key to use it with golang ssh. I am trying to combine two other sources of code (including this one ), but could not get this to work.

I think I get to DER, but I need to translate this back to PEM in order to use it with crypto / ssh

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,D7C72273BE168626E5B2D1BC72E56326
...
-----END RSA PRIVATE KEY-----

I read:

key, err := ioutil.ReadFile(privateKey)
if err != nil {
    log.Fatalf("Unable to read private key: %v", err)
}

Using an unencrypted key (!) I can:

signer, err := ssh.ParsePrivateKey(key)
if err != nil {
    log.Fatalf("Unable to parse private key: %v", err)
}

config := &ssh.ClientConfig{
    User: username,
    Auth: []ssh.AuthMethod{
        ssh.PublicKeys(signer),
    },
}

And it will work.

I again used code that seems to me to get decrypted PEM as DER:

func decrypt(key []byte, password []byte) []byte {
    block, rest := pem.Decode(key)
    if len(rest) > 0 {
        log.Fatalf("Extra data included in key")
    }
    der, err := x509.DecryptPEMBlock(block, password)
    if err != nil {
        log.Fatalf("Decrypt failed: %v", err)
    }
    return der
}

But how do I get from DER to the subscriber?

Or, what is the best way to solve this?

+6
source share
2 answers

DER RSA, x509.ParsePKCS1PrivateKey ssh.NewSignerFromKey, ssh.Signer

key, err := x509.ParsePKCS1PrivateKey(der)
if err != nil {
    log.Fatal(err)
}
signer := ssh.NewSignerFromKey(key)
+4

, ssh.ParsePrivateKey(key). decrypt, , , , key ssh.ParsePrivateKey(key). pem.EncodeToMemory PEM.

func decrypt(key []byte, password []byte) []byte {
    block, rest := pem.Decode(key)
    if len(rest) > 0 {
        log.Fatalf("Extra data included in key")
    }

    if x509.IsEncryptedPEMBlock(block) {
        der, err := x509.DecryptPEMBlock(block, password)
        if err != nil {
            log.Fatalf("Decrypt failed: %v", err)
        }
        return pem.EncodeToMemory(&pem.Block{Type: block.Type, Bytes: der})
    }
    return key
}
+4

Source: https://habr.com/ru/post/1014789/


All Articles