github.com/tommi2day/gomodules@v1.13.2-0.20240423190010-b7d55d252a27/pwlib/encode.go (about)

     1  package pwlib
     2  
     3  import (
     4  	"encoding/base64"
     5  	"os"
     6  
     7  	log "github.com/sirupsen/logrus"
     8  )
     9  
    10  // EncodeFile encodes a file using base64
    11  func EncodeFile(plainFile string, targetFile string) (err error) {
    12  	var plaindata []byte
    13  	log.Debugf("Encrypt %s with B64 to %s", plainFile, targetFile)
    14  	//nolint gosec
    15  	plaindata, err = os.ReadFile(plainFile)
    16  	if err != nil {
    17  		log.Debugf("Cannot read plaintext file %s:%s", plainFile, err)
    18  		return
    19  	}
    20  	b64 := base64.StdEncoding.EncodeToString(plaindata)
    21  	//nolint gosec
    22  	err = os.WriteFile(targetFile, []byte(b64), 0644)
    23  	if err != nil {
    24  		log.Debugf("Cannot write: %s", err.Error())
    25  		return
    26  	}
    27  	return
    28  }
    29  
    30  // DecodeFile decodes a file using base64
    31  func DecodeFile(cryptedfile string) (content []byte, err error) {
    32  	var data []byte
    33  	log.Debugf("decrypt b64 %s", cryptedfile)
    34  	//nolint gosec
    35  	data, err = os.ReadFile(cryptedfile)
    36  	if err != nil {
    37  		log.Debugf("Cannot Read file '%s': %s", cryptedfile, err)
    38  		return
    39  	}
    40  	bindata, err := base64.StdEncoding.DecodeString(string(data))
    41  	if err != nil {
    42  		log.Debugf("decode base64 for %s failed: %s", cryptedfile, err)
    43  		return
    44  	}
    45  	content = bindata
    46  	return
    47  }