diff options
| author | Shulhan <ms@kilabit.info> | 2023-09-20 21:25:46 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2023-09-20 22:57:39 +0700 |
| commit | 27c988ca384b142f8bb58385a36f1659b18dfd4b (patch) | |
| tree | f7d59e03d05b446dd7ffd3bb47f2cde36ac9081d /awwan.go | |
| parent | 4fc1b3afb4956c412dbe40a9ecfde720b4941031 (diff) | |
| download | awwan-27c988ca384b142f8bb58385a36f1659b18dfd4b.tar.xz | |
all: implement method to decrypt file using private key
The Decrypt method decrypt the file using private key from file
"{{.BaseDir}}/.awwan.key".
The encrypted file must have extension ".vault", otherwise it will return
an error.
The decrypted file output will be written in the same directory without
the ".vault" extension in filePlain.
Diffstat (limited to 'awwan.go')
| -rw-r--r-- | awwan.go | 55 |
1 files changed, 55 insertions, 0 deletions
@@ -14,6 +14,7 @@ import ( "log" "os" "path/filepath" + "strings" "git.sr.ht/~shulhan/awwan/internal" libcrypto "github.com/shuLhan/share/lib/crypto" @@ -42,6 +43,9 @@ const ( defTmpDir = "/tmp" ) +// defEncryptExt default file extension for encrypted file. +const defEncryptExt = `.vault` + // defFilePrivateKey define the default private key file name. const defFilePrivateKey = `.awwan.key` @@ -104,6 +108,57 @@ func New(baseDir string) (aww *Awwan, err error) { return aww, nil } +// Decrypt the file using private key from file "{{.BaseDir}}/.awwan.key". +// The encrypted file must have extension ".vault", otherwise it will return +// an error. +// The decrypted file output will be written in the same directory without +// the ".vault" extension in filePlain. +func (aww *Awwan) Decrypt(fileVault string) (filePlain string, err error) { + var ( + logp = `Decrypt` + ext = filepath.Ext(fileVault) + ) + + if ext != defEncryptExt { + return ``, fmt.Errorf(`%s: invalid extension, expecting %s, got %s`, logp, defEncryptExt, ext) + } + + if aww.privateKey == nil { + err = aww.loadPrivateKey() + if err != nil { + return ``, fmt.Errorf(`%s: %w`, logp, err) + } + } + + var ciphertext []byte + + ciphertext, err = os.ReadFile(fileVault) + if err != nil { + return ``, fmt.Errorf(`%s: %w`, logp, err) + } + + var ( + hash = sha256.New() + label = []byte(`awwan`) + + plaintext []byte + ) + + plaintext, err = rsa.DecryptOAEP(hash, rand.Reader, aww.privateKey, ciphertext, label) + if err != nil { + return ``, fmt.Errorf(`%s: %w`, logp, err) + } + + filePlain = strings.TrimSuffix(fileVault, defEncryptExt) + + err = os.WriteFile(filePlain, plaintext, 0600) + if err != nil { + return ``, fmt.Errorf(`%s: %w`, logp, err) + } + + return filePlain, nil +} + // Encrypt the file using private key from file "{{.BaseDir}}/.awwan.key". // The encrypted file output will be on the same file path with ".vault" // extension. |
