#89 Decrypt and verify with OpenPGP.js and GnuPG

This commit is contained in:
the-djmaze 2022-02-11 11:01:07 +01:00
parent 85f9209176
commit e0e490c64f
8 changed files with 354 additions and 315 deletions

View file

@ -21,7 +21,7 @@ export function ParseMime(text)
}
get bodyRaw() {
return text.slice(this.body_start, this.body_end);
return text.slice(this.bodyStart, this.bodyEnd);
}
get body() {
@ -99,9 +99,10 @@ export function ParseMime(text)
part.headers = headers;
// get body
part.body_start = start_pos + head.length;
part.body_end = start_pos + mimePart.length;
part.bodyStart = start_pos + head.length;
part.bodyEnd = start_pos + mimePart.length;
// get child parts
let boundary = headers['content-type'].params.boundary;
if (boundary) {
part.boundary = boundary;
@ -109,16 +110,16 @@ export function ParseMime(text)
let regex = new RegExp('(?:^|\r?\n)--' + boundary + '(?:--)?(?:\r?\n|$)', 'g'),
body = mimePart.slice(head.length),
bodies = body.split(regex),
pos = part.body_start;
pos = part.bodyStart;
[...body.matchAll(regex)].forEach(([boundary], index) => {
if (!index) {
part.body_text = bodies[0];
// Mostly something like: "This is a multi-part message in MIME format."
part.bodyText = bodies[0];
}
pos += bodies[index].length;
pos += boundary.length;
part.parts.push(ParsePart(bodies[1+index], pos, ((id ? id + '.' : '') + (1+index))));
if ('--' == boundary.trim().slice(-2)) {
// end
// Not the end?
if ('--' != boundary.trim().slice(-2)) {
pos += bodies[index].length + boundary.length;
part.parts.push(ParsePart(bodies[1+index], pos, ((id ? id + '.' : '') + (1+index))));
}
});
}

76
dev/Mime/Utils.js Normal file
View file

@ -0,0 +1,76 @@
import { ParseMime } from 'Mime/Parser';
import { AttachmentModel } from 'Model/Attachment';
import { FileInfo } from 'Common/File';
import { BEGIN_PGP_MESSAGE } from 'Stores/User/Pgp';
/**
* @param string data
* @param MessageModel message
*/
export function MimeToMessage(data, message)
{
let signed;
const struct = ParseMime(data);
if (struct.headers) {
let html = struct.getByContentType('text/html');
html = html ? html.body : '';
struct.forEach(part => {
let cd = part.header('content-disposition'),
cid = part.header('content-id'),
type = part.header('content-type');
if (cid || cd) {
// if (cd && 'attachment' === cd.value) {
let attachment = new AttachmentModel;
attachment.mimeType = type.value;
attachment.fileName = type.name || (cd && cd.params.filename) || '';
attachment.fileNameExt = attachment.fileName.replace(/^.+(\.[a-z]+)$/, '$1');
attachment.fileType = FileInfo.getType('', type.value);
attachment.url = part.dataUrl;
attachment.friendlySize = FileInfo.friendlySize(part.body.length);
/*
attachment.isThumbnail = false;
attachment.contentLocation = '';
attachment.download = '';
attachment.folder = '';
attachment.uid = '';
attachment.mimeIndex = part.id;
attachment.framed = false;
*/
attachment.cid = cid ? cid.value : '';
if (cid && html) {
let cid = 'cid:' + attachment.contentId(),
found = html.includes(cid);
attachment.isInline(found);
attachment.isLinked(found);
found && (html = html
.replace('src="' + cid + '"', 'src="' + attachment.url + '"')
.replace("src='" + cid + "'", "src='" + attachment.url + "'")
);
} else {
message.attachments.push(attachment);
}
} else if ('multipart/signed' === type.value && 'application/pgp-signature' === type.params.protocol) {
signed = {
MicAlg: type.micalg,
BodyPart: part.parts[0],
SigPart: part.parts[1]
};
}
});
const text = struct.getByContentType('text/plain');
message.plain(text ? text.body : '');
message.html(html);
} else {
message.plain(data);
}
if (!signed && message.plain().includes(BEGIN_PGP_MESSAGE)) {
signed = true;
}
message.pgpSigned(signed);
// TODO: Verify instantly?
}

View file

@ -459,8 +459,7 @@ export class MessageModel extends AbstractModel {
body.classList.toggle('plain', 1);
body.innerHTML = plainToHtml(
this.plain()
.replace(/-----BEGIN PGP SIGNATURE-----[\s\S]*/, '')
.replace(/-----BEGIN PGP SIGNED MESSAGE-----(\r?\n[a-z][^\r\n]+)+/i, '')
.replace(/-----BEGIN PGP (SIGNED MESSAGE-----(\r?\n[a-z][^\r\n]+)+|SIGNATURE-----[\s\S]*)/, '')
.trim()
)
.replace(url, '$1<a href="$2" target="_blank">$2</a>')

View file

@ -197,10 +197,15 @@ export const GnuPGUserStore = new class {
async verify(message) {
let data = message.pgpSigned(); // { BodyPartId: "1", SigPartId: "2", MicAlg: "pgp-sha256" }
if (data) {
data = { ...data }; // clone
// const sender = message.from[0].email;
// let mode = await this.hasPublicKeyForEmails([sender]);
data.Folder = message.folder;
data.Uid = message.uid;
if (data.BodyPart) {
data.BodyPart = data.BodyPart.raw;
data.SigPart = data.SigPart.body;
}
let response = await Remote.post('MessagePgpVerify', null, data);
if (response && response.Result) {
return {

View file

@ -214,9 +214,14 @@ export const OpenPGPUserStore = new class {
data.Folder = message.folder;
data.Uid = message.uid;
data.GnuPG = 0;
let response = data.SigPartId
? await Remote.post('MessagePgpVerify', null, data)
: { Result: { text: message.plain(), signature: null } };
let response;
if (data.SigPartId) {
response = await Remote.post('MessagePgpVerify', null, data);
} else if (data.BodyPart) {
response = { Result: { text: data.BodyPart.raw, signature: data.SigPart.body } };
} else {
response = { Result: { text: message.plain(), signature: null } };
}
if (response) {
const signature = response.Result.signature
? await openpgp.readSignature({ armoredSignature: response.Result.signature })

View file

@ -10,223 +10,228 @@ import { staticLink } from 'Common/Links';
import { GnuPGUserStore } from 'Stores/User/GnuPG';
import { OpenPGPUserStore } from 'Stores/User/OpenPGP';
export const PgpUserStore = new class {
constructor() {
// https://mailvelope.github.io/mailvelope/Keyring.html
this.mailvelopeKeyring = null;
}
export const
BEGIN_PGP_MESSAGE = '-----BEGIN PGP MESSAGE-----',
// BEGIN_PGP_SIGNATURE = '-----BEGIN PGP SIGNATURE-----',
// BEGIN_PGP_SIGNED = '-----BEGIN PGP SIGNED MESSAGE-----',
init() {
if (SettingsCapa(Capa.OpenPGP) && window.crypto && crypto.getRandomValues) {
const script = createElement('script', {src:staticLink('js/min/openpgp.min.js')});
script.onload = () => this.loadKeyrings();
script.onerror = () => {
this.loadKeyrings();
console.error(script.src);
};
doc.head.append(script);
} else {
this.loadKeyrings();
PgpUserStore = new class {
constructor() {
// https://mailvelope.github.io/mailvelope/Keyring.html
this.mailvelopeKeyring = null;
}
}
loadKeyrings(identifier) {
identifier = identifier || SettingsGet('Email');
if (window.mailvelope) {
const fn = keyring => {
this.mailvelopeKeyring = keyring;
console.log('mailvelope ready');
init() {
if (SettingsCapa(Capa.OpenPGP) && window.crypto && crypto.getRandomValues) {
const script = createElement('script', {src:staticLink('js/min/openpgp.min.js')});
script.onload = () => this.loadKeyrings();
script.onerror = () => {
this.loadKeyrings();
console.error(script.src);
};
mailvelope.getKeyring().then(fn, err => {
if (identifier) {
// attempt to create a new keyring for this app/user
mailvelope.createKeyring(identifier).then(fn, err => console.error(err));
} else {
console.error(err);
}
});
addEventListener('mailvelope-disconnect', event => {
alert('Mailvelope is updated to version ' + event.detail.version + '. Reload page');
}, false);
} else {
addEventListener('mailvelope', () => this.loadKeyrings(identifier));
}
if (OpenPGPUserStore.isSupported()) {
OpenPGPUserStore.loadKeyrings();
}
if (SettingsCapa(Capa.GnuPG)) {
GnuPGUserStore.loadKeyrings();
}
}
/**
* @returns {boolean}
*/
isSupported() {
return !!(OpenPGPUserStore.isSupported() || GnuPGUserStore.isSupported() || window.mailvelope);
}
/**
* @returns {boolean}
*/
isEncrypted(text) {
return 0 === text.trim().indexOf('-----BEGIN PGP MESSAGE-----');
}
async mailvelopeHasPublicKeyForEmails(recipients) {
const
keyring = this.mailvelopeKeyring,
mailvelope = keyring && await keyring.validKeyForAddress(recipients)
/*.then(LookupResult => Object.entries(LookupResult))*/,
entries = mailvelope && Object.entries(mailvelope);
return entries && entries.filter(value => value[1]).length === recipients.length;
}
/**
* Checks if verifying/encrypting a message is possible with given email addresses.
* Returns the first library that can.
*/
async hasPublicKeyForEmails(recipients) {
const count = recipients.length;
if (count) {
if (GnuPGUserStore.hasPublicKeyForEmails(recipients)) {
return 'gnupg';
}
if (OpenPGPUserStore.hasPublicKeyForEmails(recipients)) {
return 'openpgp';
doc.head.append(script);
} else {
this.loadKeyrings();
}
}
return false;
}
async getMailvelopePrivateKeyFor(email/*, sign*/) {
let keyring = this.mailvelopeKeyring;
if (keyring && await keyring.hasPrivateKey({email:email})) {
return ['mailvelope', email];
}
return false;
}
/**
* Checks if signing a message is possible with given email address.
* Returns the first library that can.
*/
async getKeyForSigning(email) {
let key = OpenPGPUserStore.getPrivateKeyFor(email, 1);
if (key) {
return ['openpgp', key];
}
key = GnuPGUserStore.getPrivateKeyFor(email, 1);
if (key) {
return ['gnupg', key];
}
// return await this.getMailvelopePrivateKeyFor(email, 1);
}
async decrypt(message) {
const sender = message.from[0].email,
armoredText = message.plain();
if (!this.isEncrypted(armoredText)) {
return;
}
// Try OpenPGP.js
let result = await OpenPGPUserStore.decrypt(armoredText, sender);
if (result) {
return result;
}
// Try Mailvelope (does not support inline images)
try {
let key = await this.getMailvelopePrivateKeyFor(message.to[0].email);
if (key) {
/**
* https://mailvelope.github.io/mailvelope/Mailvelope.html#createEncryptedFormContainer
* Creates an iframe to display an encrypted form
*/
// mailvelope.createEncryptedFormContainer('#mailvelope-form');
/**
* https://mailvelope.github.io/mailvelope/Mailvelope.html#createDisplayContainer
* Creates an iframe to display the decrypted content of the encrypted mail.
*/
const body = message.body;
body.textContent = '';
result = await mailvelope.createDisplayContainer(
'#'+body.id,
armoredText,
this.mailvelopeKeyring,
{
senderAddress: sender
}
);
if (result) {
if (result.error && result.error.message) {
if ('PWD_DIALOG_CANCEL' !== result.error.code) {
alert(result.error.code + ': ' + result.error.message);
}
loadKeyrings(identifier) {
identifier = identifier || SettingsGet('Email');
if (window.mailvelope) {
const fn = keyring => {
this.mailvelopeKeyring = keyring;
console.log('mailvelope ready');
};
mailvelope.getKeyring().then(fn, err => {
if (identifier) {
// attempt to create a new keyring for this app/user
mailvelope.createKeyring(identifier).then(fn, err => console.error(err));
} else {
body.classList.add('mailvelope');
return;
console.error(err);
}
});
addEventListener('mailvelope-disconnect', event => {
alert('Mailvelope is updated to version ' + event.detail.version + '. Reload page');
}, false);
} else {
addEventListener('mailvelope', () => this.loadKeyrings(identifier));
}
if (OpenPGPUserStore.isSupported()) {
OpenPGPUserStore.loadKeyrings();
}
if (SettingsCapa(Capa.GnuPG)) {
GnuPGUserStore.loadKeyrings();
}
}
/**
* @returns {boolean}
*/
isSupported() {
return !!(OpenPGPUserStore.isSupported() || GnuPGUserStore.isSupported() || window.mailvelope);
}
/**
* @returns {boolean}
*/
isEncrypted(text) {
return 0 === text.trim().indexOf(BEGIN_PGP_MESSAGE);
}
async mailvelopeHasPublicKeyForEmails(recipients) {
const
keyring = this.mailvelopeKeyring,
mailvelope = keyring && await keyring.validKeyForAddress(recipients)
/*.then(LookupResult => Object.entries(LookupResult))*/,
entries = mailvelope && Object.entries(mailvelope);
return entries && entries.filter(value => value[1]).length === recipients.length;
}
/**
* Checks if verifying/encrypting a message is possible with given email addresses.
* Returns the first library that can.
*/
async hasPublicKeyForEmails(recipients) {
const count = recipients.length;
if (count) {
if (GnuPGUserStore.hasPublicKeyForEmails(recipients)) {
return 'gnupg';
}
if (OpenPGPUserStore.hasPublicKeyForEmails(recipients)) {
return 'openpgp';
}
}
} catch (err) {
console.error(err);
return false;
}
// Now try GnuPG
return GnuPGUserStore.decrypt(message);
}
async getMailvelopePrivateKeyFor(email/*, sign*/) {
let keyring = this.mailvelopeKeyring;
if (keyring && await keyring.hasPrivateKey({email:email})) {
return ['mailvelope', email];
}
return false;
}
async verify(message) {
const signed = message.pgpSigned();
if (signed) {
/**
* Checks if signing a message is possible with given email address.
* Returns the first library that can.
*/
async getKeyForSigning(email) {
let key = OpenPGPUserStore.getPrivateKeyFor(email, 1);
if (key) {
return ['openpgp', key];
}
key = GnuPGUserStore.getPrivateKeyFor(email, 1);
if (key) {
return ['gnupg', key];
}
// return await this.getMailvelopePrivateKeyFor(email, 1);
}
async decrypt(message) {
const sender = message.from[0].email,
gnupg = GnuPGUserStore.hasPublicKeyForEmails([sender]),
openpgp = OpenPGPUserStore.hasPublicKeyForEmails([sender]);
// Detached signature use GnuPG first, else we must download whole message
if (gnupg && signed.SigPartId) {
return GnuPGUserStore.verify(message);
armoredText = message.plain();
if (!this.isEncrypted(armoredText)) {
return;
}
if (openpgp) {
return OpenPGPUserStore.verify(message);
// Try OpenPGP.js
let result = await OpenPGPUserStore.decrypt(armoredText, sender);
if (result) {
return result;
}
if (gnupg) {
return GnuPGUserStore.verify(message);
// Try Mailvelope (does not support inline images)
try {
let key = await this.getMailvelopePrivateKeyFor(message.to[0].email);
if (key) {
/**
* https://mailvelope.github.io/mailvelope/Mailvelope.html#createEncryptedFormContainer
* Creates an iframe to display an encrypted form
*/
// mailvelope.createEncryptedFormContainer('#mailvelope-form');
/**
* https://mailvelope.github.io/mailvelope/Mailvelope.html#createDisplayContainer
* Creates an iframe to display the decrypted content of the encrypted mail.
*/
const body = message.body;
body.textContent = '';
result = await mailvelope.createDisplayContainer(
'#'+body.id,
armoredText,
this.mailvelopeKeyring,
{
senderAddress: sender
}
);
if (result) {
if (result.error && result.error.message) {
if ('PWD_DIALOG_CANCEL' !== result.error.code) {
alert(result.error.code + ': ' + result.error.message);
}
} else {
body.classList.add('mailvelope');
return;
}
}
}
} catch (err) {
console.error(err);
}
// Mailvelope can't
// https://github.com/mailvelope/mailvelope/issues/434
// Now try GnuPG
return GnuPGUserStore.decrypt(message);
}
}
/**
* Returns headers that should be added to an outgoing email.
* So far this is only the autocrypt header.
*/
/*
this.mailvelopeKeyring.additionalHeadersForOutgoingEmail(headers)
this.mailvelopeKeyring.addSyncHandler(syncHandlerObj)
this.mailvelopeKeyring.createKeyBackupContainer(selector, options)
this.mailvelopeKeyring.createKeyGenContainer(selector, {
// userIds: [],
keySize: 4096
})
async verify(message) {
const signed = message.pgpSigned();
if (signed) {
const sender = message.from[0].email,
gnupg = GnuPGUserStore.hasPublicKeyForEmails([sender]),
openpgp = OpenPGPUserStore.hasPublicKeyForEmails([sender]);
// Detached signature use GnuPG first, else we must download whole message
if (gnupg && signed.SigPartId) {
return GnuPGUserStore.verify(message);
}
if (openpgp) {
return OpenPGPUserStore.verify(message);
}
if (gnupg) {
return GnuPGUserStore.verify(message);
}
// Mailvelope can't
// https://github.com/mailvelope/mailvelope/issues/434
}
}
this.mailvelopeKeyring.exportOwnPublicKey(emailAddr).then(<AsciiArmored, Error>)
this.mailvelopeKeyring.importPublicKey(armored)
/**
* Returns headers that should be added to an outgoing email.
* So far this is only the autocrypt header.
*/
/*
this.mailvelopeKeyring.additionalHeadersForOutgoingEmail(headers)
this.mailvelopeKeyring.addSyncHandler(syncHandlerObj)
this.mailvelopeKeyring.createKeyBackupContainer(selector, options)
this.mailvelopeKeyring.createKeyGenContainer(selector, {
// userIds: [],
keySize: 4096
})
// https://mailvelope.github.io/mailvelope/global.html#SyncHandlerObject
this.mailvelopeKeyring.addSyncHandler({
uploadSync
downloadSync
backup
restore
});
*/
this.mailvelopeKeyring.exportOwnPublicKey(emailAddr).then(<AsciiArmored, Error>)
this.mailvelopeKeyring.importPublicKey(armored)
};
// https://mailvelope.github.io/mailvelope/global.html#SyncHandlerObject
this.mailvelopeKeyring.addSyncHandler({
uploadSync
downloadSync
backup
restore
});
*/
};

View file

@ -33,7 +33,6 @@ import { SMAudio } from 'Common/Audio';
import { i18n } from 'Common/Translator';
import { attachmentDownload } from 'Common/Links';
import { FileInfo } from 'Common/File';
import { MessageFlagsCache } from 'Common/Cache';
@ -53,73 +52,12 @@ import { AbstractViewRight } from 'Knoin/AbstractViews';
import { PgpUserStore } from 'Stores/User/Pgp';
import { ParseMime } from 'Mime/Parser';
import { AttachmentModel } from 'Model/Attachment';
import { MimeToMessage } from 'Mime/Utils';
const
oMessageScrollerDom = () => elementById('messageItem') || {},
currentMessage = () => MessageUserStore.message(),
mimeToMessage = (data, message) => {
const headers = data.split(/\r?\n\r?\n/)[0];
if (/Content-Type:/i.test(headers)) {
const struct = ParseMime(data),
text = struct.getByContentType('text/plain');
let html = struct.getByContentType('text/html');
html = html ? html.body : '';
// TODO: Check multipart/signed application/pgp-signature application/pgp-keys
struct.forEach(part => {
let cd = part.header('content-disposition'),
cid = part.header('content-id'),
type = part.header('content-type');
if (cid || cd) {
// if (cd && 'attachment' === cd.value) {
let attachment = new AttachmentModel;
attachment.mimeType = type.value;
attachment.fileName = type.name || (cd && cd.params.filename) || '';
attachment.fileNameExt = attachment.fileName.replace(/^.+(\.[a-z]+)$/, '$1');
attachment.fileType = FileInfo.getType('', type.value);
attachment.url = part.dataUrl;
attachment.friendlySize = FileInfo.friendlySize(part.body.length);
/*
attachment.isThumbnail = false;
attachment.contentLocation = '';
attachment.download = '';
attachment.folder = '';
attachment.uid = '';
attachment.mimeIndex = part.id;
attachment.framed = false;
*/
attachment.cid = cid ? cid.value : '';
if (cid && html) {
let cid = 'cid:' + attachment.contentId(),
found = html.includes(cid);
attachment.isInline(found);
attachment.isLinked(found);
found && (html = html
.replace('src="' + cid + '"', 'src="' + attachment.url + '"')
.replace("src='" + cid + "'", "src='" + attachment.url + "'")
);
} else {
message.attachments.push(attachment);
}
}
});
message.plain(text ? text.body : '');
if (html) {
message.html(html.replace(/<\/?script[\s\S]*?>/gi, ''));
message.viewHtml();
} else {
message.viewPlain();
}
return;
}
message.plain(data);
message.viewPlain();
};
currentMessage = () => MessageUserStore.message();
export class MailMessageView extends AbstractViewRight {
constructor() {
@ -647,7 +585,8 @@ export class MailMessageView extends AbstractViewRight {
const oMessage = currentMessage();
PgpUserStore.decrypt(oMessage).then(result => {
if (result && result.data) {
mimeToMessage(result.data, oMessage);
MimeToMessage(result.data, oMessage);
oMessage.html() ? oMessage.viewHtml() : oMessage.viewPlain();
if (result.signatures && result.signatures.length) {
oMessage.pgpSigned(true);
oMessage.pgpVerified({

View file

@ -660,48 +660,57 @@ trait Messages
{
$sFolderName = $this->GetActionParam('Folder', '');
$iUid = (int) $this->GetActionParam('Uid', 0);
$sBodyPartId = $this->GetActionParam('BodyPartId', '');
$sSigPartId = $this->GetActionParam('SigPartId', '');
// $sMicAlg = $this->GetActionParam('MicAlg', '');
$oAccount = $this->initMailClientConnection();
$oImapClient = $this->MailClient()->ImapClient();
$oImapClient->FolderExamine($sFolderName);
$aParts = [
FetchType::BODY_PEEK.'['.$sBodyPartId.']',
// An empty section specification refers to the entire message, including the header.
// But Dovecot does not return it with BODY.PEEK[1], so we also use BODY.PEEK[1.MIME].
FetchType::BODY_PEEK.'['.$sBodyPartId.'.MIME]'
];
if ($sSigPartId) {
$aParts[] = FetchType::BODY_PEEK.'['.$sSigPartId.']';
}
$oFetchResponse = $oImapClient->Fetch($aParts, $iUid, true)[0];
$sBodyMime = $oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sBodyPartId.'.MIME]');
if ($sSigPartId) {
$sBodyPart = $this->GetActionParam('BodyPart', '');
$sSigPart = $this->GetActionParam('SigPart', '');
if ($sBodyPart) {
$result = [
'text' => \preg_replace('/\\R/s', "\r\n",
$sBodyMime . $oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sBodyPartId.']')
),
'signature' => preg_replace('/[^\x00-\x7F]/', '',
$oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sSigPartId.']')
)
'text' => \preg_replace('/\\R/s', "\r\n", $sBodyPart),
'signature' => $this->GetActionParam('SigPart', '')
];
} else {
// clearsigned text
$result = [
'text' => $oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sBodyPartId.']'),
'signature' => ''
$sBodyPartId = $this->GetActionParam('BodyPartId', '');
$sSigPartId = $this->GetActionParam('SigPartId', '');
// $sMicAlg = $this->GetActionParam('MicAlg', '');
$oAccount = $this->initMailClientConnection();
$oImapClient = $this->MailClient()->ImapClient();
$oImapClient->FolderExamine($sFolderName);
$aParts = [
FetchType::BODY_PEEK.'['.$sBodyPartId.']',
// An empty section specification refers to the entire message, including the header.
// But Dovecot does not return it with BODY.PEEK[1], so we also use BODY.PEEK[1.MIME].
FetchType::BODY_PEEK.'['.$sBodyPartId.'.MIME]'
];
$decode = (new \MailSo\Mime\HeaderCollection($sBodyMime))->ValueByName(\MailSo\Mime\Enumerations\Header::CONTENT_TRANSFER_ENCODING);
if ('base64' === $decode) {
$result['text'] = \base64_decode($result['text']);
} else if ('quoted-printable' === $decode) {
$result['text'] = \quoted_printable_decode($result['text']);
if ($sSigPartId) {
$aParts[] = FetchType::BODY_PEEK.'['.$sSigPartId.']';
}
$oFetchResponse = $oImapClient->Fetch($aParts, $iUid, true)[0];
$sBodyMime = $oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sBodyPartId.'.MIME]');
if ($sSigPartId) {
$result = [
'text' => \preg_replace('/\\R/s', "\r\n",
$sBodyMime . $oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sBodyPartId.']')
),
'signature' => preg_replace('/[^\x00-\x7F]/', '',
$oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sSigPartId.']')
)
];
} else {
// clearsigned text
$result = [
'text' => $oFetchResponse->GetFetchValue(FetchType::BODY.'['.$sBodyPartId.']'),
'signature' => ''
];
$decode = (new \MailSo\Mime\HeaderCollection($sBodyMime))->ValueByName(\MailSo\Mime\Enumerations\Header::CONTENT_TRANSFER_ENCODING);
if ('base64' === $decode) {
$result['text'] = \base64_decode($result['text']);
} else if ('quoted-printable' === $decode) {
$result['text'] = \quoted_printable_decode($result['text']);
}
}
}