@@ -10,7 +10,6 @@ import (
1010 "encoding/pem"
1111 "fmt"
1212 "math/big"
13- "os"
1413
1514 "golang.org/x/crypto/argon2"
1615 "golang.org/x/crypto/hkdf"
@@ -83,53 +82,50 @@ func bytesToKeys(private []byte, passphrase string, publics [][]byte) (crypto.Pr
8382 return prv , pubs , nil
8483}
8584
86- // GenerateKeyFile generates a new ed25519 ssh key pair.
85+ // GenerateKeyFile generates a new ed25519 ssh key pair. The first return value is the private key in PEM format,
86+ // the second return value is the public key in ssh authorized_key format.
8787// If deterministic is true, the key will be generated based on the passphrase itself,
8888// so the same passphrase will always generate the same key, this is useful if you don't want to backup the key,
8989// but it's less secure, you must use a strong passphrase.
90- func GenerateKeyFile (deterministic bool , privateKeyPath , comment , passphrase string ) error {
90+ func GenerateKeyFile (deterministic bool , comment , passphrase string ) ([] byte , [] byte , error ) {
9191 var prvKeyPem * pem.Block
9292
9393 seed := rand .Reader
9494
9595 if passphrase != "" && deterministic {
9696 salt := sha256 .Sum256 ([]byte (passphrase ))
97- derivedKey := argon2 .IDKey ([]byte (passphrase ), salt [:], 128 , 64 * 1024 , 4 , 32 )
97+ derivedKey := argon2 .IDKey ([]byte (passphrase ), salt [:], 1 , 64 * 1024 , 4 , 32 )
9898 seed = hkdf .New (sha256 .New , derivedKey , nil , nil )
9999 }
100100
101101 publicKey , privateKey , err := ed25519 .GenerateKey (seed )
102102 if err != nil {
103- return err
103+ return nil , nil , err
104104 }
105105
106106 sshPubKey , err := ssh .NewPublicKey (publicKey )
107107 if err != nil {
108- return err
108+ return nil , nil , err
109109 }
110110
111111 pubKeyString := fmt .Sprintf ("%s %s %s\n " ,
112112 sshPubKey .Type (),
113113 base64 .StdEncoding .EncodeToString (sshPubKey .Marshal ()),
114114 comment ,
115115 )
116- err = os .WriteFile (privateKeyPath + PUB_KEY_EXT , []byte (pubKeyString ), 0o644 )
117- if err != nil {
118- return err
119- }
120116
121117 if passphrase != "" {
122118 prvKeyPem , err = ssh .MarshalPrivateKeyWithPassphrase (privateKey , comment , []byte (passphrase ))
123119 } else {
124120 prvKeyPem , err = ssh .MarshalPrivateKey (privateKey , comment )
125121 }
126122 if err != nil {
127- return err
123+ return nil , nil , err
128124 }
129125
130126 prvKeyBytes := pem .EncodeToMemory (prvKeyPem )
131127
132- return os . WriteFile ( privateKeyPath , prvKeyBytes , 0o600 )
128+ return prvKeyBytes , [] byte ( pubKeyString ), nil
133129}
134130
135131func bigIntToBytes (a * big.Int , padding int ) []byte {
0 commit comments