14#include <QJsonDocument>
16#include <QRegularExpression>
24#include <rnp/rnp_err.h>
30auto rnpError(
const QString &what, rnp_result_t result) -> QString {
31 return QStringLiteral(
"%1: %2").arg(
32 what, QString::fromUtf8(rnp_result_to_string(result)));
35auto rnpError(
const char *what, rnp_result_t result) -> QString {
36 return rnpError(QString::fromUtf8(what), result);
39void setError(QString *error,
const QString &message) {
40 if (error !=
nullptr) {
46 void operator()(rnp_input_st *input)
const { rnp_input_destroy(input); }
49 void operator()(rnp_output_st *output)
const { rnp_output_destroy(output); }
52 void operator()(rnp_key_handle_st *key)
const { rnp_key_handle_destroy(key); }
54using Input = std::unique_ptr<rnp_input_st, InputDeleter>;
55using Output = std::unique_ptr<rnp_output_st, OutputDeleter>;
56using Key = std::unique_ptr<rnp_key_handle_st, KeyDeleter>;
59auto memoryInput(
const QByteArray &data, QString *error,
const char *what)
61 rnp_input_t input =
nullptr;
62 const rnp_result_t result = rnp_input_from_memory(
63 &input,
reinterpret_cast<const uint8_t *
>(data.constData()),
64 static_cast<size_t>(data.size()),
false);
65 if (result != RNP_SUCCESS) {
66 setError(error, rnpError(what, result));
74auto memoryOutput(QString *error,
const char *what, qint64 maxBytes = 0)
76 rnp_output_t output =
nullptr;
77 const rnp_result_t result =
78 rnp_output_to_memory(&output,
static_cast<size_t>(maxBytes));
79 if (result != RNP_SUCCESS) {
80 setError(error, rnpError(what, result));
83 return Output(output);
87auto outputBytes(rnp_output_t output) -> std::optional<QByteArray> {
88 uint8_t *buf =
nullptr;
90 if (rnp_output_memory_get_buf(output, &buf, &len,
false) != RNP_SUCCESS) {
93 return QByteArray(
reinterpret_cast<const char *
>(buf),
94 static_cast<qsizetype
>(len));
98auto isValidKey(rnp_key_handle_t key) ->
bool {
100 return rnp_key_is_valid(key, &valid) == RNP_SUCCESS && valid;
103auto allowsEncryption(rnp_key_handle_t key) ->
bool {
104 bool allowed =
false;
105 return rnp_key_allows_usage(key,
"encrypt", &allowed) == RNP_SUCCESS &&
115auto canEncryptTo(rnp_key_handle_t key) ->
bool {
116 if (!isValidKey(key)) {
119 if (allowsEncryption(key)) {
123 rnp_key_get_subkey_count(key, &subkeys);
124 for (
size_t i = 0; i < subkeys; ++i) {
125 rnp_key_handle_t handle =
nullptr;
126 if (rnp_key_get_subkey_at(key, i, &handle) != RNP_SUCCESS ||
130 const Key subkey(handle);
131 if (isValidKey(handle) && allowsEncryption(handle)) {
144auto secretIsHere(rnp_key_handle_t key) ->
bool {
146 if (rnp_key_have_secret(key, &secret) != RNP_SUCCESS || !secret) {
149 char *type =
nullptr;
150 if (rnp_key_get_protection_type(key, &type) != RNP_SUCCESS ||
154 const QString protection = QString::fromLatin1(type);
155 rnp_buffer_destroy(type);
156 return protection != QLatin1String(
"GPG-None") &&
157 protection != QLatin1String(
"GPG-Smartcard") &&
158 protection != QLatin1String(
"Unknown");
161auto isProtected(rnp_key_handle_t key) ->
bool {
163 return rnp_key_is_protected(key, &locked) == RNP_SUCCESS && locked;
172template <
typename Visit>
173auto forEachSecretPart(rnp_key_handle_t key, Visit visit) ->
int {
175 if (secretIsHere(key)) {
182 rnp_key_get_subkey_count(key, &subkeys);
183 for (
size_t i = 0; i < subkeys; ++i) {
184 rnp_key_handle_t handle =
nullptr;
185 if (rnp_key_get_subkey_at(key, i, &handle) != RNP_SUCCESS ||
189 const Key subkey(handle);
190 if (secretIsHere(handle)) {
192 if (!visit(handle)) {
205auto signingKeyOf(rnp_key_handle_t key) -> Key {
206 if (!isValidKey(key)) {
209 rnp_key_handle_t handle =
nullptr;
210 if (rnp_key_get_default_key(key,
"sign", 0, &handle) != RNP_SUCCESS ||
215 if (!isValidKey(handle) || !secretIsHere(handle)) {
222enum class Usage { Encrypt, Sign };
224auto usableFor(rnp_key_handle_t primary, Usage usage) ->
bool {
225 return usage == Usage::Encrypt ? canEncryptTo(primary)
226 : signingKeyOf(primary) != nullptr;
230auto primaryFingerprint(rnp_key_handle_t key) -> QString {
231 bool primary =
false;
232 rnp_key_is_primary(key, &primary);
234 if ((primary ? rnp_key_get_fprint(key, &fpr)
235 : rnp_key_get_primary_fprint(key, &fpr)) != RNP_SUCCESS) {
238 QString result = QString::fromLatin1(fpr);
239 rnp_buffer_destroy(fpr);
249auto liveUserIds(rnp_key_handle_t key) -> QStringList {
252 rnp_key_get_uid_count(key, &uids);
253 for (
size_t i = 0; i < uids; ++i) {
254 rnp_uid_handle_t handle =
nullptr;
255 if (rnp_key_get_uid_handle_at(key, i, &handle) != RNP_SUCCESS ||
262 const bool known = rnp_uid_is_valid(handle, &valid) == RNP_SUCCESS &&
263 rnp_uid_is_revoked(handle, &revoked) == RNP_SUCCESS;
264 rnp_uid_handle_destroy(handle);
266 if (!known || !valid || revoked ||
267 rnp_key_get_uid_at(key, i, &uid) != RNP_SUCCESS) {
270 live << QString::fromUtf8(uid);
271 rnp_buffer_destroy(uid);
277template <
typename Hit>
278auto anyUserIdMatches(rnp_key_handle_t key, Hit hit) ->
bool {
279 const QStringList uids = liveUserIds(key);
280 return std::any_of(uids.cbegin(), uids.cend(), hit);
284auto mailboxOf(
const QString &uid) -> QString {
285 const qsizetype open = uid.lastIndexOf(QLatin1Char(
'<'));
286 const qsizetype close = uid.lastIndexOf(QLatin1Char(
'>'));
287 return open >= 0 && close > open ? uid.mid(open + 1, close - open - 1)
296template <
typename Match>
297auto matchingPrimaries(rnp_ffi_t ffi, Usage usage, Match match) -> QStringList {
298 QStringList primaries;
299 rnp_identifier_iterator_t it =
nullptr;
300 if (rnp_identifier_iterator_create(ffi, &it,
"fingerprint") != RNP_SUCCESS) {
303 const char *fpr =
nullptr;
304 while (rnp_identifier_iterator_next(it, &fpr) == RNP_SUCCESS &&
306 rnp_key_handle_t handle =
nullptr;
307 if (rnp_locate_key(ffi,
"fingerprint", fpr, &handle) != RNP_SUCCESS ||
311 const Key key(handle);
312 if (!match(handle)) {
315 const QString primary = primaryFingerprint(handle);
316 rnp_key_handle_t primaryHandle =
nullptr;
317 if (primary.isEmpty() || primaries.contains(primary) ||
318 rnp_locate_key(ffi,
"fingerprint", primary.toLatin1().constData(),
319 &primaryHandle) != RNP_SUCCESS ||
320 primaryHandle ==
nullptr) {
323 const Key primaryKey(primaryHandle);
324 if (usableFor(primaryHandle, usage)) {
325 primaries << primary;
328 rnp_identifier_iterator_destroy(it);
344auto locateExactKey(rnp_ffi_t ffi,
const char *type,
const QString &lookup,
345 const QString &recipient, QString *why, Usage usage)
347 rnp_key_handle_t handle =
nullptr;
348 rnp_locate_key(ffi, type, lookup.toUpper().toLatin1().constData(), &handle);
349 if (handle ==
nullptr) {
351 (usage == Usage::Encrypt ? QStringLiteral(
"No public key for %1")
352 : QStringLiteral(
"No secret key for %1"))
359 const QString primary = primaryFingerprint(handle);
360 rnp_key_handle_t primaryHandle =
nullptr;
361 rnp_locate_key(ffi,
"fingerprint", primary.toLatin1().constData(),
363 const Key primaryKey(primaryHandle);
364 if (primaryHandle ==
nullptr || !usableFor(primaryHandle, usage)) {
366 (usage == Usage::Encrypt
367 ? QStringLiteral(
"The key %1 cannot be encrypted to: it "
368 "is expired or revoked, or has no valid "
370 : QStringLiteral(
"The key %1 cannot sign: it is expired "
371 "or revoked, has no valid signing key, "
372 "or its secret key is not here"))
391auto primariesNamedBy(rnp_ffi_t ffi,
const QString &
id,
const QString &keyId,
392 bool isHexId, Usage usage) -> QStringList {
393 if (isHexId && keyId.size() == 8) {
395 const QString shortId = keyId.toUpper();
396 return matchingPrimaries(ffi, usage, [&shortId](rnp_key_handle_t key) {
397 char *keyId =
nullptr;
398 if (rnp_key_get_keyid(key, &keyId) != RNP_SUCCESS) {
401 const bool hit = QString::fromLatin1(keyId).endsWith(shortId);
402 rnp_buffer_destroy(keyId);
406 static const QRegularExpression address(
407 QStringLiteral(R
"(^(?:<[^\s<>@]+@[^\s<>@]+>|[^\s<>@]+@[^\s<>@]+)$)"));
408 if (address.match(
id).hasMatch()) {
414 QString mailbox = id;
415 mailbox.remove(QLatin1Char(
'<')).remove(QLatin1Char(
'>'));
416 return matchingPrimaries(ffi, usage, [&mailbox](rnp_key_handle_t key) {
417 return anyUserIdMatches(key, [&mailbox](
const QString &uid) {
418 return mailboxOf(uid).compare(mailbox, Qt::CaseInsensitive) == 0;
426 QStringList primaries =
427 matchingPrimaries(ffi, usage, [&
id](rnp_key_handle_t key) {
428 return anyUserIdMatches(
429 key, [&
id](
const QString &uid) {
return uid == id; });
431 if (primaries.isEmpty()) {
432 primaries = matchingPrimaries(ffi, usage, [&
id](rnp_key_handle_t key) {
433 return anyUserIdMatches(key, [&
id](
const QString &uid) {
434 return uid.contains(
id, Qt::CaseInsensitive);
448auto locateKey(rnp_ffi_t ffi,
const QString &recipient, QString *why,
449 Usage usage = Usage::Encrypt) -> Key {
450 const QString
id = recipient.trimmed();
452 setError(why, QStringLiteral(
"Empty recipient"));
459 static const QRegularExpression blanks(QStringLiteral(
"\\s+"));
460 static const QRegularExpression hex(QStringLiteral(
"^[0-9A-Fa-f]+$"));
461 const auto withoutPrefix = [](
const QString &text) {
462 return text.startsWith(QLatin1String(
"0x"), Qt::CaseInsensitive) &&
463 hex.match(text.mid(2)).hasMatch()
467 QString fingerprint = id;
468 fingerprint.remove(blanks);
469 fingerprint = withoutPrefix(fingerprint);
470 const QString keyId = withoutPrefix(
id);
471 if (keyId.compare(QLatin1String(
"0x"), Qt::CaseInsensitive) == 0) {
472 setError(why, QStringLiteral(
"Empty recipient"));
475 const bool isHexId = hex.match(keyId).hasMatch();
476 const char *type =
nullptr;
479 if (hex.match(fingerprint).hasMatch() &&
480 (fingerprint.size() == 40 || fingerprint.size() == 64)) {
481 type =
"fingerprint";
482 lookup = std::move(fingerprint);
483 }
else if (isHexId && keyId.size() == 16) {
487 if (type !=
nullptr) {
488 return locateExactKey(ffi, type, lookup, recipient, why, usage);
491 const QStringList primaries =
492 primariesNamedBy(ffi,
id, keyId, isHexId, usage);
493 if (primaries.size() > 1) {
495 QStringLiteral(
"%1 matches more than one key").arg(recipient));
498 if (primaries.isEmpty()) {
499 setError(why, (usage == Usage::Encrypt
500 ? QStringLiteral(
"No usable public key for %1")
501 : QStringLiteral(
"No usable secret key for %1"))
505 rnp_key_handle_t key =
nullptr;
506 rnp_locate_key(ffi,
"fingerprint", primaries.first().toLatin1().constData(),
512auto passwordCallback(rnp_ffi_t ,
void *appCtx, rnp_key_handle_t key,
515 size_t bufLen) ->
bool {
516 const auto *provider =
518 if (provider ==
nullptr || !*provider || bufLen == 0) {
522 char *rawId =
nullptr;
523 if (rnp_key_get_keyid(key, &rawId) == RNP_SUCCESS) {
524 keyId = QString::fromLatin1(rawId);
525 rnp_buffer_destroy(rawId);
527 QByteArray passphrase = (*provider)(keyId).toUtf8();
528 if (passphrase.isEmpty() ||
529 static_cast<size_t>(passphrase.size()) >= bufLen) {
530 passphrase.fill(
'\0');
533 std::memcpy(buf, passphrase.constData(),
534 static_cast<size_t>(passphrase.size()));
535 buf[passphrase.size()] =
'\0';
536 passphrase.fill(
'\0');
543 rnp_ffi_t ffi =
nullptr;
544 if (rnp_ffi_create(&ffi,
"GPG",
"GPG") == RNP_SUCCESS) {
551 if (
m_ffi !=
nullptr) {
552 rnp_ffi_destroy(
m_ffi);
565 std::min<qint64>(bytes, std::numeric_limits<quint32>::max());
575 if (
m_ffi ==
nullptr) {
576 setError(error, QStringLiteral(
"RNP is not available"));
579 Input input = memoryInput(keyData, error,
"Cannot read the key data");
583 char *json =
nullptr;
584 const rnp_result_t result = rnp_import_keys(
585 m_ffi, input.get(), RNP_LOAD_SAVE_PUBLIC_KEYS | RNP_LOAD_SAVE_SECRET_KEYS,
587 if (result != RNP_SUCCESS) {
588 setError(error, rnpError(
"Cannot import the keys", result));
591 QJsonParseError parseError{};
592 const QJsonDocument doc = QJsonDocument::fromJson(json, &parseError);
593 rnp_buffer_destroy(json);
594 const QJsonValue keysValue = doc.object().value(QStringLiteral(
"keys"));
595 if (parseError.error != QJsonParseError::NoError || !keysValue.isArray()) {
597 setError(error, QStringLiteral(
"Cannot read RNP's import report: %1")
598 .arg(parseError.error != QJsonParseError::NoError
599 ? parseError.errorString()
600 : QStringLiteral(
"no key list")));
603 QStringList primaries;
604 const QJsonArray keys = keysValue.toArray();
605 for (
const auto &entry : keys) {
607 entry.toObject().value(QStringLiteral(
"fingerprint")).toString();
608 rnp_key_handle_t key =
nullptr;
609 if (rnp_locate_key(
m_ffi,
"fingerprint", fpr.toLatin1().constData(),
610 &key) != RNP_SUCCESS ||
614 bool primary =
false;
615 rnp_key_is_primary(key, &primary);
616 rnp_key_handle_destroy(key);
617 if (primary && !primaries.contains(fpr)) {
625 const QStringList &recipients, QString *error)
627 if (
m_ffi ==
nullptr) {
628 setError(error, QStringLiteral(
"RNP is not available"));
631 if (recipients.isEmpty()) {
632 setError(error, QStringLiteral(
"No recipients"));
635 Input input = memoryInput(plaintext, error,
"Cannot read the entry");
636 Output output = memoryOutput(error,
"Cannot encrypt");
637 if (!input || !output) {
640 rnp_op_encrypt_t op =
nullptr;
641 rnp_result_t result =
642 rnp_op_encrypt_create(&op,
m_ffi, input.get(), output.get());
643 if (result != RNP_SUCCESS) {
644 setError(error, rnpError(
"Cannot encrypt", result));
647 const std::unique_ptr<rnp_op_encrypt_st, rnp_result_t (*)(rnp_op_encrypt_t)>
648 guard(op, rnp_op_encrypt_destroy);
649 for (
const QString &recipient : recipients) {
651 const Key key = locateKey(
m_ffi, recipient, &why);
653 setError(error, why);
656 result = rnp_op_encrypt_add_recipient(op, key.get());
657 if (result != RNP_SUCCESS) {
659 rnpError(QStringLiteral(
"Cannot encrypt to %1").arg(recipient),
664 rnp_op_encrypt_set_armor(op,
false);
665 result = rnp_op_encrypt_execute(op);
666 if (result != RNP_SUCCESS) {
667 setError(error, rnpError(
"Cannot encrypt", result));
670 std::optional<QByteArray> cipher = outputBytes(output.get());
672 setError(error, QStringLiteral(
"Cannot encrypt: no output from RNP"));
683 if (
m_ffi ==
nullptr) {
684 setError(error, QStringLiteral(
"RNP is not available"));
687 Input input = memoryInput(ciphertext, error,
"Cannot read the entry");
688 Output output = memoryOutput(error,
"Cannot decrypt",
m_maxPlaintext);
689 if (!input || !output) {
695 rnp_op_verify_t op =
nullptr;
696 rnp_result_t result =
697 rnp_op_verify_create(&op,
m_ffi, input.get(), output.get());
698 if (result != RNP_SUCCESS) {
699 setError(error, rnpError(
"Cannot decrypt", result));
702 const std::unique_ptr<rnp_op_verify_st, rnp_result_t (*)(rnp_op_verify_t)>
703 guard(op, rnp_op_verify_destroy);
706 rnp_op_verify_set_flags(op, RNP_VERIFY_IGNORE_SIGS_ON_DECRYPT);
707 result = rnp_op_verify_execute(op);
708 if (result != RNP_SUCCESS) {
709 setError(error, rnpError(
"Cannot decrypt", result));
712 char *mode =
nullptr;
713 bool protectedOk =
false;
714 if (rnp_op_verify_get_protection_info(op, &mode,
nullptr, &protectedOk) !=
718 QStringLiteral(
"Refusing a message without integrity "
720 .arg(QString::fromLatin1(mode !=
nullptr ? mode :
"unknown")));
721 rnp_buffer_destroy(mode);
724 rnp_buffer_destroy(mode);
725 std::optional<QByteArray> plain = outputBytes(output.get());
727 setError(error, QStringLiteral(
"Cannot decrypt: no output from RNP"));
739auto fingerprintOf(rnp_key_handle_t key) -> QString {
741 if (rnp_key_get_fprint(key, &fpr) != RNP_SUCCESS) {
744 QString result = QString::fromLatin1(fpr);
745 rnp_buffer_destroy(fpr);
749auto isRevoked(rnp_key_handle_t key) ->
bool {
750 bool revoked =
false;
751 return rnp_key_is_revoked(key, &revoked) == RNP_SUCCESS && revoked;
760auto firstSecretOfUnknownProtection(rnp_ffi_t ffi) -> std::optional<QString> {
762 rnp_identifier_iterator_t it =
nullptr;
763 if (rnp_identifier_iterator_create(ffi, &it,
"fingerprint") != RNP_SUCCESS) {
767 const char *fpr =
nullptr;
768 while (found.isEmpty() && !failed) {
769 if (rnp_identifier_iterator_next(it, &fpr) != RNP_SUCCESS) {
773 if (fpr ==
nullptr) {
776 rnp_key_handle_t handle =
nullptr;
777 if (rnp_locate_key(ffi,
"fingerprint", fpr, &handle) != RNP_SUCCESS ||
782 const Key key(handle);
784 if (rnp_key_have_secret(handle, &secret) != RNP_SUCCESS) {
791 char *type =
nullptr;
792 if (rnp_key_get_protection_type(handle, &type) != RNP_SUCCESS ||
797 if (QString::fromLatin1(type) == QLatin1String(
"Unknown")) {
798 found = QString::fromLatin1(fpr);
800 rnp_buffer_destroy(type);
802 rnp_identifier_iterator_destroy(it);
810auto primaryOf(rnp_ffi_t ffi, rnp_key_handle_t key) -> Key {
811 const QString primary = primaryFingerprint(key);
812 rnp_key_handle_t handle =
nullptr;
813 if (primary.isEmpty() ||
814 rnp_locate_key(ffi,
"fingerprint", primary.toLatin1().constData(),
815 &handle) != RNP_SUCCESS) {
830 char *keyId =
nullptr;
831 if (rnp_key_get_keyid(handle, &keyId) == RNP_SUCCESS) {
832 info.
keyId = QString::fromLatin1(keyId);
833 rnp_buffer_destroy(keyId);
835 info.
userIds = liveUserIds(handle);
836 uint32_t created = 0;
837 if (rnp_key_get_creation(handle, &created) == RNP_SUCCESS) {
838 info.
created = QDateTime::fromSecsSinceEpoch(created, QTimeZone::UTC);
840 uint32_t lifetime = 0;
841 if (rnp_key_get_expiration(handle, &lifetime) == RNP_SUCCESS &&
845 info.
revoked = isRevoked(handle);
846 bool expired =
false;
847 info.
expired = rnp_key_is_expired(handle, &expired) == RNP_SUCCESS && expired;
849 info.
hasSecret = forEachSecretPart(handle, [&info](rnp_key_handle_t part) {
855 info.
canSign = signingKeyOf(handle) !=
nullptr;
863 if (
m_ffi ==
nullptr) {
866 rnp_identifier_iterator_t it =
nullptr;
867 if (rnp_identifier_iterator_create(
m_ffi, &it,
"fingerprint") !=
871 const char *fpr =
nullptr;
872 while (rnp_identifier_iterator_next(it, &fpr) == RNP_SUCCESS &&
874 rnp_key_handle_t handle =
nullptr;
875 if (rnp_locate_key(
m_ffi,
"fingerprint", fpr, &handle) != RNP_SUCCESS ||
879 const Key key(handle);
880 bool primary =
false;
881 if (rnp_key_is_primary(handle, &primary) != RNP_SUCCESS || !primary) {
884 const KeyInfo info = keyInfoOf(handle);
889 rnp_identifier_iterator_destroy(it);
894 QString *error) -> QByteArray {
895 if (
m_ffi ==
nullptr) {
896 setError(error, QStringLiteral(
"RNP is not available"));
902 const Key named = locateKey(
m_ffi, signer, &why, Usage::Sign);
904 setError(error, why);
907 const Key primary = primaryOf(
m_ffi, named.get());
908 const Key signing = primary ? signingKeyOf(primary.get()) :
nullptr;
910 setError(error, QStringLiteral(
"The key %1 cannot sign").arg(signer));
913 Input input = memoryInput(data, error,
"Cannot read the data to sign");
914 Output output = memoryOutput(error,
"Cannot sign");
915 if (!input || !output) {
918 rnp_op_sign_t op =
nullptr;
919 rnp_result_t result =
920 rnp_op_sign_detached_create(&op,
m_ffi, input.get(), output.get());
921 if (result != RNP_SUCCESS) {
922 setError(error, rnpError(
"Cannot sign", result));
925 const std::unique_ptr<rnp_op_sign_st, rnp_result_t (*)(rnp_op_sign_t)> guard(
926 op, rnp_op_sign_destroy);
927 rnp_op_sign_set_armor(op,
false);
928 result = rnp_op_sign_add_signature(op, signing.get(),
nullptr);
929 if (result == RNP_SUCCESS) {
931 result = rnp_op_sign_execute(op);
933 if (result != RNP_SUCCESS) {
934 setError(error, rnpError(
"Cannot sign", result));
937 std::optional<QByteArray> signature = outputBytes(output.get());
938 if (!signature || signature->isEmpty()) {
939 setError(error, QStringLiteral(
"Cannot sign: no output from RNP"));
946 QString *error) -> QStringList {
947 if (
m_ffi ==
nullptr) {
948 setError(error, QStringLiteral(
"RNP is not available"));
951 Input input = memoryInput(data, error,
"Cannot read the signed data");
952 Input sigInput = memoryInput(signature, error,
"Cannot read the signature");
953 if (!input || !sigInput) {
956 rnp_op_verify_t op =
nullptr;
957 rnp_result_t result =
958 rnp_op_verify_detached_create(&op,
m_ffi, input.get(), sigInput.get());
959 if (result != RNP_SUCCESS) {
960 setError(error, rnpError(
"Cannot verify", result));
963 const std::unique_ptr<rnp_op_verify_st, rnp_result_t (*)(rnp_op_verify_t)>
964 guard(op, rnp_op_verify_destroy);
966 result = rnp_op_verify_execute(op);
968 rnp_op_verify_get_signature_count(op, &count);
969 for (
size_t i = 0; i < count; ++i) {
970 rnp_op_verify_signature_t sig =
nullptr;
971 if (rnp_op_verify_get_signature_at(op, i, &sig) != RNP_SUCCESS ||
972 rnp_op_verify_signature_get_status(sig) != RNP_SUCCESS) {
975 rnp_key_handle_t handle =
nullptr;
976 if (rnp_op_verify_signature_get_key(sig, &handle) != RNP_SUCCESS ||
980 const Key key(handle);
981 const Key primary = primaryOf(
m_ffi, handle);
986 if (isRevoked(handle) || !primary || isRevoked(primary.get())) {
987 setError(error, QStringLiteral(
"The signature is by a revoked key (%1)")
988 .arg(primaryFingerprint(handle)));
991 return {fingerprintOf(handle), fingerprintOf(primary.get())};
993 setError(error, result != RNP_SUCCESS ? rnpError(
"No valid signature", result)
994 : QStringLiteral(
"No valid signature"));
999 const QString &passphrase, QString *error) ->
bool {
1000 if (
m_ffi ==
nullptr) {
1001 setError(error, QStringLiteral(
"RNP is not available"));
1004 if (passphrase.isEmpty()) {
1005 setError(error, QStringLiteral(
"An empty passphrase protects nothing"));
1008 rnp_key_handle_t handle =
nullptr;
1009 rnp_locate_key(
m_ffi,
"fingerprint",
1010 fingerprint.toUpper().toLatin1().constData(), &handle);
1011 const Key key(handle);
1016 int unprotected = 0;
1020 : forEachSecretPart(handle, [&unprotected](rnp_key_handle_t part) {
1021 unprotected += isProtected(part) ? 0 : 1;
1025 setError(error, QStringLiteral(
"No secret key for %1").arg(fingerprint));
1028 if (unprotected == 0) {
1030 QStringLiteral(
"The secret key %1 is protected already; its "
1031 "passphrase is not changed here")
1035 QByteArray secret = passphrase.toUtf8();
1037 forEachSecretPart(handle, [&](rnp_key_handle_t part) {
1038 if (isProtected(part)) {
1042 const rnp_result_t result =
1043 rnp_key_protect(part, secret.constData(),
nullptr,
nullptr,
nullptr, 0);
1044 if (result != RNP_SUCCESS) {
1047 rnpError(QStringLiteral(
"Cannot protect %1").arg(fingerprintOf(part)),
1059 if (!key.secretProtected) {
1060 setError(error, QStringLiteral(
"The secret key %1 is not protected "
1062 .arg(key.fingerprint));
1069 const std::optional<QString> unknown = firstSecretOfUnknownProtection(
m_ffi);
1071 setError(error, QStringLiteral(
"Cannot tell how every secret key is "
1072 "protected; nothing is written"));
1075 if (!unknown->isEmpty()) {
1076 setError(error, QStringLiteral(
"The secret key %1 has a protection RNP "
1085 QString *error)
const ->
bool {
1086 if (
m_ffi ==
nullptr) {
1087 setError(error, QStringLiteral(
"RNP is not available"));
1094 QStringLiteral(
"%1 is a link, not a keyring folder").arg(dir));
1107 std::optional<QByteArray> ring = QByteArray();
1109 Output output = memoryOutput(error,
"Cannot save the keyring");
1113 const rnp_result_t result =
1114 rnp_save_keys(
m_ffi,
"GPG", output.get(),
1115 RNP_LOAD_SAVE_PUBLIC_KEYS | RNP_LOAD_SAVE_SECRET_KEYS);
1116 if (result != RNP_SUCCESS) {
1117 setError(error, rnpError(
"Cannot save the keyring", result));
1120 ring = outputBytes(output.get());
1122 setError(error, QStringLiteral(
"Cannot save the keyring: no output"));
1128 setError(error, QStringLiteral(
"The keyring is larger than %1 bytes")
1134 if (!QDir().mkpath(dir) ||
1135 !QFile::setPermissions(dir, QFile::ReadOwner | QFile::WriteOwner |
1137 setError(error, QStringLiteral(
"Cannot create %1").arg(dir));
1144 QDir(dir).filePath(QStringLiteral(
"keyring.gpg")), *ring,
true,
1146 setError(error, QStringLiteral(
"Cannot write the keyring: %1").arg(why));
1153 if (
m_ffi ==
nullptr) {
1154 setError(error, QStringLiteral(
"RNP is not available"));
1160 QStringLiteral(
"%1 is a link, not a keyring folder").arg(dir));
1163 const QString path = QDir(dir).filePath(QStringLiteral(
"keyring.gpg"));
1164 const QFileInfo info(path);
1165 if (!info.exists() && !info.isSymLink()) {
1168 const std::optional<QByteArray> bytes =
1171 setError(error, QStringLiteral(
"Cannot read %1 as a keyring (a regular "
1172 "file of at most %2 bytes)")
1177 if (bytes->isEmpty()) {
1180 Input input = memoryInput(*bytes, error,
"Cannot read the keyring");
1184 const rnp_result_t result =
1185 rnp_load_keys(
m_ffi,
"GPG", input.get(),
1186 RNP_LOAD_SAVE_PUBLIC_KEYS | RNP_LOAD_SAVE_SECRET_KEYS);
1187 if (result != RNP_SUCCESS) {
1189 rnpError(QStringLiteral(
"Cannot load %1").arg(path), result));
static constexpr qint64 kMaxKeyringBytes
Most bytes of a keyring file: saveKeyring() writes no larger one, loadKeyring() reads no larger one.
auto sign(const QByteArray &data, const QString &signer, QString *error=nullptr) -> QByteArray
Makes a detached signature over data, as gpg –detach-sign –local-user signer does (for ....
void setPassphraseProvider(PassphraseProvider provider)
Sets how secret-key passphrases are obtained.
std::function< QString(const QString &keyId)> PassphraseProvider
Asks for the passphrase of a secret key.
RnpCrypto()
Creates an empty keyring.
auto importKeys(const QByteArray &keyData, QString *error=nullptr) -> QStringList
Imports public and secret keys from armored or binary key data.
qint64 m_maxPlaintext
Largest plaintext decrypt() returns, in bytes.
auto verify(const QByteArray &data, const QByteArray &signature, QString *error=nullptr) -> QStringList
Checks a detached signature over data, as QtPass reads gpg's VALIDSIG.
void setMaxPlaintextBytes(qint64 bytes)
Sets the most bytes of plaintext decrypt() may produce.
~RnpCrypto()
Frees the keyring and everything RNP holds for it.
rnp_ffi_st * m_ffi
RNP's handle holding this object's keyring; null when RNP could not be initialised,...
auto protectKey(const QString &fingerprint, const QString &passphrase, QString *error=nullptr) -> bool
Protects the secret parts of a key with passphrase.
auto decrypt(const QByteArray &ciphertext, QString *error=nullptr, bool *ok=nullptr) -> QByteArray
Decrypts an OpenPGP message with any secret key in the keyring.
auto listKeys(bool secretOnly=false) const -> QList< KeyInfo >
The primary keys in the keyring.
auto isValid() const -> bool
Whether the RNP context could be created at all.
auto loadKeyring(const QString &dir, QString *error=nullptr) -> bool
Adds the keyring in dir (as saveKeyring() wrote it) to this one. Secret keys stay protected until an ...
auto encrypt(const QByteArray &plaintext, const QStringList &recipients, QString *error=nullptr) -> QByteArray
Encrypts plaintext to every recipient, as one message.
PassphraseProvider m_passphrase
Asked for the passphrase of a locked secret key during decryption; set with setPassphraseProvider(),...
auto saveKeyring(const QString &dir, bool allowUnprotected=false, QString *error=nullptr) const -> bool
Writes the keyring to dir: keyring.gpg, public and secret keys in one file (OpenPGP keys,...
auto everySecretIsProtected(QString *error) const -> bool
Whether saveKeyring() may write the secret keys without the user's consent: each is protected by a pa...
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
static auto readRegularFile(const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
Read path whole, as the regular file it is (openRegularFile()), when it holds at most maxBytes.
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
RnpCrypto, in-process OpenPGP encryption and decryption through the RNP library.
One primary key in the keyring, as the Users dialog lists keys.
QStringList userIds
Its user IDs that are still its own (valid, not revoked), in the keyring's order.
QDateTime expires
When it expires; invalid when it does not.
bool canSign
Whether it can sign now, with a secret key that is here.
bool canEncrypt
Whether a message can be encrypted to it now.
bool secretProtected
Whether every secret part of it that is here is protected by a passphrase; true when none is here.
bool expired
Whether it has expired.
QString fingerprint
The primary key's fingerprint, upper-case hex.
QString keyId
The primary key's 16-hex-digit key ID.
QDateTime created
When it was created.
bool hasSecret
Whether a secret part of it (primary or subkey) is here to use: a GnuPG stub (a key left at home,...
bool revoked
Whether it has been revoked.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...