1
0
Fork 0
mirror of https://git.sr.ht/~rjarry/aerc synced 2025-02-23 07:53:59 +01:00
aerc/lib/crypto/util/cleartext.go
Koni Marti 108a8ca1d2 cryptoutil: implement cleartext function
Implement a cleartext function in the cryptoutil package to decrypt an
encrypted message to cleartext and construct a valid rfc2822 message.

The headers from the decrypt message body will be merged with the
original headers to create a fully decrypted message.

Implements: https://todo.sr.ht/~rjarry/aerc/238
Signed-off-by: Koni Marti <koni.marti@gmail.com>
Tested-by: Jens Grassel <jens@wegtam.com>
Reviewed-by: Tim Culverhouse <tim@timculverhouse.com>
Acked-by: Robin Jarry <robin@jarry.cc>
2024-08-20 11:54:34 +02:00

69 lines
1.7 KiB
Go

package cryptoutil
import (
"bytes"
"errors"
"io"
"strings"
"git.sr.ht/~rjarry/aerc/app"
"git.sr.ht/~rjarry/aerc/lib/rfc822"
"github.com/emersion/go-message/mail"
)
func Cleartext(r io.Reader, header mail.Header) ([]byte, error) {
msg, err := app.CryptoProvider().Decrypt(
rfc822.NewCRLFReader(r), app.DecryptKeys)
if err != nil {
return nil, errors.New("decrypt error")
}
full, err := createMessage(header, msg.Body)
if err != nil {
return nil, errors.New("failed to create decrypted message")
}
return full, nil
}
func createMessage(header mail.Header, body io.Reader) ([]byte, error) {
e, err := rfc822.ReadMessage(body)
if err != nil {
return nil, err
}
// copy the header values from the "decrypted body". This should set
// the correct content type.
hf := e.Header.Fields()
for hf.Next() {
header.Set(hf.Key(), hf.Value())
}
ctype, params, err := header.ContentType()
if err != nil {
return nil, err
}
// in case there remains a multipart/{encrypted,signed} content type,
// manually correct them to multipart/mixed as a fallback.
ct := strings.ToLower(ctype)
if strings.Contains(ct, "multipart/encrypted") ||
strings.Contains(ct, "multipart/signed") {
delete(params, "protocol")
delete(params, "micalg")
header.SetContentType("multipart/mixed", params)
}
// a SingleInlineWriter is sufficient since the "decrypted body"
// already contains the proper boundaries of the parts; we just want to
// combine it with the headers.
var message bytes.Buffer
w, err := mail.CreateSingleInlineWriter(&message, header)
if err != nil {
return nil, err
}
if _, err := io.Copy(w, e.Body); err != nil {
return nil, err
}
w.Close()
return message.Bytes(), nil
}