package encryption

import (
	"bytes"
	"io/ioutil"

	"github.com/pkg/errors"
)

func (c *AuthorizedFieldClient) DecryptString(blob []byte) (string, error) {
	if blob == nil {
		return "", nil
	}

	plaintext, err := c.decrypt(blob)
	if err != nil {
		return "", errors.Wrap(err, "could not decrypt authorized field")
	}

	return string(plaintext), nil
}

func (c *AuthorizedFieldClient) decrypt(olePayload []byte) ([]byte, error) {
	if olePayload == nil {
		return nil, ErrNilOLEPayload
	}

	decryptedBuf := c.ole.NewDecryptor(bytes.NewReader(olePayload))
	bs, err := ioutil.ReadAll(decryptedBuf)
	if err != nil {
		return nil, err
	}

	return bs, nil
}
