git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/zign/init.go (about)

     1  package zign
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  
     7  	"git.sr.ht/~pingoo/stdx/crypto"
     8  )
     9  
    10  const SaltSize = crypto.KeySize256
    11  
    12  func Init(password []byte) (encryptedAndEncodedPrivateKey string, encodedPublicKey string, err error) {
    13  	publicKey, privateKey, err := crypto.GenerateEd25519KeyPair()
    14  	if err != nil {
    15  		err = fmt.Errorf("zign.Init: generating ed25519 keypair: %w", err)
    16  		return
    17  	}
    18  	defer crypto.Zeroize(privateKey)
    19  
    20  	salt, err := crypto.RandBytes(SaltSize)
    21  	if err != nil {
    22  		err = fmt.Errorf("zign.Init: generating random salt: %w", err)
    23  		return
    24  	}
    25  	encryptionKey, err := crypto.DeriveKeyFromPassword(password, salt, crypto.DefaultDeriveKeyFromPasswordParams)
    26  	if err != nil {
    27  		err = fmt.Errorf("zign.Init: deriving encryption key from password: %w", err)
    28  		return
    29  	}
    30  
    31  	encryptedPrivateKey, err := crypto.Encrypt(encryptionKey, privateKey.Bytes(), salt)
    32  	if err != nil {
    33  		err = fmt.Errorf("zign.Init: encrypting private key: %w", err)
    34  		return
    35  	}
    36  
    37  	encryptedPrivateKeyAndSalt := append(encryptedPrivateKey, salt...)
    38  
    39  	encryptedAndEncodedPrivateKey = base64.StdEncoding.EncodeToString(encryptedPrivateKeyAndSalt)
    40  	encodedPublicKey = base64.StdEncoding.EncodeToString(publicKey.Bytes())
    41  
    42  	return
    43  }