From ac811b84af2461539d6b04c3d95eed8e5438ec25 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Fri, 22 Sep 2023 02:16:44 +0700 Subject: all: split the decrypt into separate function The decrypt function accept the private key and cipher text to be decrypted. This will allow the function to be used by other methods later, not only by Decrypt method. --- awwan.go | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/awwan.go b/awwan.go index d5242f0..18f6a9e 100644 --- a/awwan.go +++ b/awwan.go @@ -140,10 +140,6 @@ func (aww *Awwan) Decrypt(fileVault string) (filePlain string, err error) { return ``, fmt.Errorf(`%s: invalid extension, expecting %s, got %s`, logp, defEncryptExt, ext) } - if aww.privateKey == nil { - return ``, fmt.Errorf(`%s: missing private key %s`, logp, defFilePrivateKey) - } - var ciphertext []byte ciphertext, err = os.ReadFile(fileVault) @@ -151,14 +147,9 @@ func (aww *Awwan) Decrypt(fileVault string) (filePlain string, err error) { return ``, fmt.Errorf(`%s: %w`, logp, err) } - var ( - hash = sha256.New() - label = []byte(`awwan`) - - plaintext []byte - ) + var plaintext []byte - plaintext, err = libcrypto.DecryptOaep(hash, rand.Reader, aww.privateKey, ciphertext, label) + plaintext, err = decrypt(aww.privateKey, ciphertext) if err != nil { return ``, fmt.Errorf(`%s: %w`, logp, err) } @@ -475,6 +466,24 @@ func (aww *Awwan) loadPrivateKey() (err error) { return nil } +func decrypt(pkey *rsa.PrivateKey, cipher []byte) (plain []byte, err error) { + if pkey == nil { + return nil, fmt.Errorf(`missing private key file %q`, defFilePrivateKey) + } + + var ( + hash = sha256.New() + label = []byte(`awwan`) + ) + + plain, err = libcrypto.DecryptOaep(hash, rand.Reader, pkey, cipher, label) + if err != nil { + return nil, err + } + + return plain, nil +} + // lookupBaseDir find the directory that contains ".ssh" directory from // current working directory until "/", as the base working directory of // awwan. -- cgit v1.3