ditch CachedPublicKeyRing, and some cleanup

This commit is contained in:
Vincent Breitmoser 2018-06-26 11:43:23 +02:00
parent 31830a8c86
commit 1635c261b8
24 changed files with 119 additions and 308 deletions

View file

@ -19,7 +19,6 @@ package org.sufficientlysecure.keychain.operations;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import android.content.Context;
import android.support.annotation.NonNull;
@ -39,10 +38,9 @@ import org.sufficientlysecure.keychain.pgp.PgpCertifyOperation.PgpCertifyResult;
import org.sufficientlysecure.keychain.pgp.Progressable;
import org.sufficientlysecure.keychain.pgp.UncachedKeyRing;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyMetadataDao;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.provider.KeyWritableRepository;
import org.sufficientlysecure.keychain.provider.KeyMetadataDao;
import org.sufficientlysecure.keychain.service.CertifyActionsParcel;
import org.sufficientlysecure.keychain.service.CertifyActionsParcel.CertifyAction;
import org.sufficientlysecure.keychain.service.ContactSyncAdapterService;

View file

@ -18,16 +18,29 @@
package org.sufficientlysecure.keychain.operations;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.annotation.NonNull;
import com.textuality.keybase.lib.KeybaseQuery;
import com.textuality.keybase.lib.Proof;
import com.textuality.keybase.lib.prover.Prover;
import org.json.JSONObject;
import de.measite.minidns.Client;
import de.measite.minidns.DNSMessage;
import de.measite.minidns.Question;
import de.measite.minidns.Record;
import de.measite.minidns.record.Data;
import de.measite.minidns.record.TXT;
import org.bouncycastle.openpgp.PGPUtil;
import org.json.JSONObject;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.network.OkHttpKeybaseClient;
import org.sufficientlysecure.keychain.network.orbot.OrbotHelper;
import org.sufficientlysecure.keychain.operations.results.DecryptVerifyResult;
import org.sufficientlysecure.keychain.operations.results.KeybaseVerificationResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult;
@ -35,28 +48,12 @@ import org.sufficientlysecure.keychain.operations.results.OperationResult.LogTyp
import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyInputParcel;
import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyOperation;
import org.sufficientlysecure.keychain.pgp.Progressable;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyWritableRepository;
import org.sufficientlysecure.keychain.service.KeybaseVerificationParcel;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
import org.sufficientlysecure.keychain.network.OkHttpKeybaseClient;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.util.Preferences;
import org.sufficientlysecure.keychain.network.orbot.OrbotHelper;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import de.measite.minidns.Client;
import de.measite.minidns.DNSMessage;
import de.measite.minidns.Question;
import de.measite.minidns.Record;
import de.measite.minidns.record.Data;
import de.measite.minidns.record.TXT;
public class KeybaseVerificationOperation extends BaseOperation<KeybaseVerificationParcel> {
@ -162,7 +159,7 @@ public class KeybaseVerificationOperation extends BaseOperation<KeybaseVerificat
}
long verifyingKeyId = decryptVerifyResult.getSignatureResult().getKeyId();
byte[] verifyingFingerprint = mKeyRepository.getCachedPublicKeyRing(verifyingKeyId).getFingerprint();
byte[] verifyingFingerprint = mKeyRepository.getFingerprintByKeyId(verifyingKeyId);
if (!requiredFingerprint.equals(KeyFormattingUtils.convertFingerprintToHex(verifyingFingerprint))) {
log.add(LogType.MSG_KEYBASE_ERROR_FINGERPRINT_MISMATCH, 1);
return new KeybaseVerificationResult(OperationResult.RESULT_ERROR, log);

View file

@ -61,15 +61,11 @@ public abstract class CanonicalizedKeyRing extends KeyRing {
return getRing().getPublicKey().getFingerprint();
}
public byte[] getRawPrimaryUserId() throws PgpKeyNotFoundException {
public byte[] getRawPrimaryUserId() {
return getPublicKey().getRawPrimaryUserId();
}
public String getPrimaryUserId() throws PgpKeyNotFoundException {
return getPublicKey().getPrimaryUserId();
}
public String getPrimaryUserIdWithFallback() throws PgpKeyNotFoundException {
public String getPrimaryUserIdWithFallback() {
return getPublicKey().getPrimaryUserIdWithFallback();
}
@ -107,10 +103,6 @@ public abstract class CanonicalizedKeyRing extends KeyRing {
return creationDate.after(now) || (expirationDate != null && expirationDate.before(now));
}
public boolean canCertify() throws PgpKeyNotFoundException {
return getRing().getPublicKey().isEncryptionKey();
}
public Set<Long> getEncryptIds() {
HashSet<Long> result = new HashSet<>();
for (CanonicalizedPublicKey key : publicKeyIterator()) {
@ -130,15 +122,6 @@ public abstract class CanonicalizedKeyRing extends KeyRing {
throw new PgpKeyNotFoundException("No valid encryption key found!");
}
public boolean hasEncrypt() throws PgpKeyNotFoundException {
try {
getEncryptId();
return true;
} catch (PgpKeyNotFoundException e) {
return false;
}
}
public long getSigningId() throws PgpKeyNotFoundException {
for(CanonicalizedPublicKey key : publicKeyIterator()) {
if (key.canSign() && key.isValid()) {

View file

@ -100,7 +100,7 @@ public class CanonicalizedPublicKeyRing extends CanonicalizedKeyRing {
* - the user id that matches the userIdToKeep parameter, or the primary user id if none matches
* each with their most recent binding certificates
*/
public CanonicalizedPublicKeyRing minimize(@Nullable String userIdToKeep) throws IOException, PgpKeyNotFoundException {
public CanonicalizedPublicKeyRing minimize(@Nullable String userIdToKeep) throws IOException {
CanonicalizedPublicKey masterKey = getPublicKey();
PGPPublicKey masterPubKey = masterKey.getPublicKey();
boolean userIdStrippedOk = false;

View file

@ -326,7 +326,7 @@ public class CanonicalizedSecretKey extends CanonicalizedPublicKey {
spGen.setSignatureCreationTime(false, creationTimestamp);
signatureGenerator.setHashedSubpackets(spGen.generate());
return signatureGenerator;
} catch (PgpKeyNotFoundException | PGPException e) {
} catch (PGPException e) {
// TODO: simply throw PGPException!
throw new PgpGeneralException("Error initializing signature!", e);
}

View file

@ -17,17 +17,12 @@
package org.sufficientlysecure.keychain.pgp;
import android.text.TextUtils;
import org.openintents.openpgp.util.OpenPgpUtils;
import org.openintents.openpgp.util.OpenPgpUtils.UserId;
import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing.VerificationStatus;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* An abstract KeyRing.
* <p/>
@ -37,28 +32,17 @@ import java.util.regex.Pattern;
* here.
*
* @see CanonicalizedKeyRing
* @see org.sufficientlysecure.keychain.provider.CachedPublicKeyRing
*/
public abstract class KeyRing {
abstract public long getMasterKeyId() throws PgpKeyNotFoundException;
abstract public String getPrimaryUserId() throws PgpKeyNotFoundException;
abstract public String getPrimaryUserIdWithFallback() throws PgpKeyNotFoundException;
public UserId getSplitPrimaryUserIdWithFallback() throws PgpKeyNotFoundException {
return splitUserId(getPrimaryUserIdWithFallback());
}
abstract public boolean isRevoked() throws PgpKeyNotFoundException;
abstract public boolean canCertify() throws PgpKeyNotFoundException;
abstract public long getEncryptId() throws PgpKeyNotFoundException;
abstract public boolean hasEncrypt() throws PgpKeyNotFoundException;
abstract public VerificationStatus getVerified() throws PgpKeyNotFoundException;
/**

View file

@ -119,11 +119,7 @@ public class OpenPgpSignatureResultBuilder {
// from RING
setKeyId(signingRing.getMasterKeyId());
try {
setPrimaryUserId(signingRing.getPrimaryUserIdWithFallback());
} catch (PgpKeyNotFoundException e) {
Timber.d("No primary user id in keyring with master key id " + signingRing.getMasterKeyId());
}
setPrimaryUserId(signingRing.getPrimaryUserIdWithFallback());
setSignatureKeyCertified(signingRing.getVerified() == VerificationStatus.VERIFIED_SECRET);
List<String> allUserIds = signingRing.getUnorderedUserIds();

View file

@ -8,6 +8,8 @@ import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.db.SupportSQLiteQuery;
import android.database.Cursor;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
class AbstractDao {
private final KeychainDatabase db;
@ -41,6 +43,14 @@ class AbstractDao {
return result;
}
<T> T mapSingleRowOrThrow(SupportSQLiteQuery query, Mapper<T> mapper) throws NotFoundException {
T result = mapSingleRow(query, mapper);
if (result == null) {
throw new NotFoundException();
}
return result;
}
<T> T mapSingleRow(SupportSQLiteQuery query, Mapper<T> mapper) {
try (Cursor cursor = getReadableDb().query(query)) {
if (cursor.moveToNext()) {

View file

@ -1,105 +0,0 @@
/*
* Copyright (C) 2017 Schürmann & Breitmoser GbR
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.provider;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing.VerificationStatus;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType;
import org.sufficientlysecure.keychain.pgp.KeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
/** This implementation of KeyRing provides a cached view of PublicKeyRing
* objects based on database queries exclusively.
*
* This class should be used where only few points of data but no actual
* cryptographic operations are required about a PublicKeyRing which is already
* in the database. This happens commonly in UI code, where parsing of a PGP
* key for examination would be a very expensive operation.
*
* Each getter method is implemented using a more or less expensive database
* query, while object construction is (almost) free. A common pattern is
* mProviderHelper.getCachedKeyRing(uri).getterMethod()
*
* TODO Ensure that the values returned here always match the ones returned by
* the parsed KeyRing!
*
*/
public class CachedPublicKeyRing extends KeyRing {
private UnifiedKeyInfo unifiedKeyInfo;
public CachedPublicKeyRing(UnifiedKeyInfo unifiedKeyInfo) {
this.unifiedKeyInfo = unifiedKeyInfo;
}
@Override
public long getMasterKeyId() {
return unifiedKeyInfo.master_key_id();
}
public byte[] getFingerprint() {
return unifiedKeyInfo.fingerprint();
}
public long getCreationTime() {
return unifiedKeyInfo.creation();
}
@Override
public String getPrimaryUserId() {
return unifiedKeyInfo.user_id();
}
public String getPrimaryUserIdWithFallback() {
return getPrimaryUserId();
}
@Override
public boolean isRevoked() {
return unifiedKeyInfo.is_revoked();
}
@Override
public boolean canCertify() {
return unifiedKeyInfo.can_certify();
}
@Override
public long getEncryptId() {
return unifiedKeyInfo.has_encrypt_key_int();
}
@Override
public boolean hasEncrypt() {
return unifiedKeyInfo.has_encrypt_key();
}
public long getAuthenticationId() {
return unifiedKeyInfo.has_auth_key_int();
}
@Override
public VerificationStatus getVerified() {
return unifiedKeyInfo.verified();
}
public boolean hasAnySecret() {
return unifiedKeyInfo.has_any_secret();
}
}

View file

@ -20,7 +20,6 @@ package org.sufficientlysecure.keychain.provider;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentResolver;
@ -102,15 +101,6 @@ public class KeyRepository extends AbstractDao {
mLog = new OperationLog();
}
// replace with getUnifiedKeyInfo
public CachedPublicKeyRing getCachedPublicKeyRing(long masterKeyId) throws NotFoundException {
UnifiedKeyInfo unifiedKeyInfo = getUnifiedKeyInfo(masterKeyId);
if (unifiedKeyInfo == null) {
throw new NotFoundException();
}
return new CachedPublicKeyRing(unifiedKeyInfo);
}
public CanonicalizedPublicKeyRing getCanonicalizedPublicKeyRing(long masterKeyId) throws NotFoundException {
UnifiedKeyInfo unifiedKeyInfo = getUnifiedKeyInfo(masterKeyId);
if (unifiedKeyInfo == null) {
@ -146,22 +136,12 @@ public class KeyRepository extends AbstractDao {
public Long getMasterKeyIdBySubkeyId(long subKeyId) {
SqlDelightQuery query = SubKey.FACTORY.selectMasterKeyIdBySubkey(subKeyId);
try (Cursor cursor = getReadableDb().query(query)) {
if (cursor.moveToFirst()) {
return SubKey.FACTORY.selectMasterKeyIdBySubkeyMapper().map(cursor);
}
return null;
}
return mapSingleRow(query, SubKey.FACTORY.selectMasterKeyIdBySubkeyMapper()::map);
}
public UnifiedKeyInfo getUnifiedKeyInfo(long masterKeyId) {
SqlDelightQuery query = SubKey.FACTORY.selectUnifiedKeyInfoByMasterKeyId(masterKeyId);
try (Cursor cursor = getReadableDb().query(query)) {
if (cursor.moveToNext()) {
return SubKey.UNIFIED_KEY_INFO_MAPPER.map(cursor);
}
return null;
}
return mapSingleRow(query, SubKey.UNIFIED_KEY_INFO_MAPPER::map);
}
public List<UnifiedKeyInfo> getUnifiedKeyInfo(long... masterKeyIds) {
@ -190,13 +170,9 @@ public class KeyRepository extends AbstractDao {
}
public List<String> getConfirmedUserIds(long masterKeyId) {
ArrayList<String> userIds = new ArrayList<>();
SqlDelightQuery query = UserPacket.FACTORY.selectUserIdsByMasterKeyIdAndVerification(
Certification.FACTORY, masterKeyId, VerificationStatus.VERIFIED_SECRET);
for (UserId userId : mapAllRows(query, UserPacket.USER_ID_MAPPER::map)) {
userIds.add(userId.user_id());
}
return userIds;
return mapAllRows(query, (cursor) -> UserPacket.USER_ID_MAPPER.map(cursor).user_id());
}
public List<SubKey> getSubKeysByMasterKeyId(long masterKeyId) {
@ -206,12 +182,12 @@ public class KeyRepository extends AbstractDao {
public SecretKeyType getSecretKeyType(long keyId) throws NotFoundException {
SqlDelightQuery query = SubKey.FACTORY.selectSecretKeyType(keyId);
try (Cursor cursor = getReadableDb().query(query)) {
if (cursor.moveToFirst()) {
return SubKey.SKT_MAPPER.map(cursor);
}
throw new NotFoundException();
}
return mapSingleRowOrThrow(query, SubKey.SKT_MAPPER::map);
}
public byte[] getFingerprintByKeyId(long keyId) throws NotFoundException {
SqlDelightQuery query = SubKey.FACTORY.selectFingerprintByKeyId(keyId);
return mapSingleRowOrThrow(query, SubKey.FACTORY.selectFingerprintByKeyIdMapper()::map);
}
private byte[] getKeyRingAsArmoredData(byte[] data) throws IOException {
@ -267,20 +243,12 @@ public class KeyRepository extends AbstractDao {
public long getSecretSignId(long masterKeyId) throws NotFoundException {
SqlDelightQuery query = SubKey.FACTORY.selectEffectiveSignKeyIdByMasterKeyId(masterKeyId);
Long signKeyId = mapSingleRow(query, SubKey.FACTORY.selectEffectiveSignKeyIdByMasterKeyIdMapper()::map);
if (signKeyId == null) {
throw new NotFoundException();
}
return signKeyId;
return mapSingleRowOrThrow(query, SubKey.FACTORY.selectEffectiveSignKeyIdByMasterKeyIdMapper()::map);
}
public Long getSecretAuthenticationId(long masterKeyId) throws NotFoundException {
public long getSecretAuthenticationId(long masterKeyId) throws NotFoundException {
SqlDelightQuery query = SubKey.FACTORY.selectEffectiveAuthKeyIdByMasterKeyId(masterKeyId);
Long authKeyId = mapSingleRow(query, SubKey.FACTORY.selectEffectiveAuthKeyIdByMasterKeyIdMapper()::map);
if (authKeyId == null) {
throw new NotFoundException();
}
return authKeyId;
return mapSingleRowOrThrow(query, SubKey.FACTORY.selectEffectiveAuthKeyIdByMasterKeyIdMapper()::map);
}
public static class NotFoundException extends Exception {

View file

@ -52,6 +52,7 @@ import org.openintents.openpgp.OpenPgpSignatureResult;
import org.openintents.openpgp.OpenPgpSignatureResult.AutocryptPeerResult;
import org.openintents.openpgp.util.OpenPgpApi;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.operations.BackupOperation;
import org.sufficientlysecure.keychain.operations.results.DecryptVerifyResult;
import org.sufficientlysecure.keychain.operations.results.ExportResult;
@ -68,7 +69,6 @@ import org.sufficientlysecure.keychain.pgp.Progressable;
import org.sufficientlysecure.keychain.pgp.SecurityProblem;
import org.sufficientlysecure.keychain.provider.ApiAppDao;
import org.sufficientlysecure.keychain.provider.AutocryptPeerDao;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.provider.KeychainExternalContract.AutocryptStatus;
@ -742,17 +742,16 @@ public class OpenPgpService extends Service {
result.putExtra(OpenPgpApi.RESULT_SIGN_KEY_ID, signKeyId);
if (signKeyId != Constants.key.none) {
try {
CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(signKeyId);
String userId = cachedPublicKeyRing.getPrimaryUserId();
long creationTime = cachedPublicKeyRing.getCreationTime() * 1000;
result.putExtra(OpenPgpApi.RESULT_PRIMARY_USER_ID, userId);
result.putExtra(OpenPgpApi.RESULT_KEY_CREATION_TIME, creationTime);
} catch (NotFoundException e) {
Timber.e(e, "Error loading key info");
return createErrorResultIntent(OpenPgpError.GENERIC_ERROR, e.getMessage());
UnifiedKeyInfo unifiedKeyInfo = mKeyRepository.getUnifiedKeyInfo(signKeyId);
if (unifiedKeyInfo == null) {
Timber.e("Error loading key info");
return createErrorResultIntent(OpenPgpError.GENERIC_ERROR, "Signing key not found!");
}
String userId = unifiedKeyInfo.user_id();
long creationTime = unifiedKeyInfo.creation() * 1000;
result.putExtra(OpenPgpApi.RESULT_PRIMARY_USER_ID, userId);
result.putExtra(OpenPgpApi.RESULT_KEY_CREATION_TIME, creationTime);
}
return result;

View file

@ -40,13 +40,13 @@ import org.openintents.ssh.authentication.response.PublicKeyResponse;
import org.openintents.ssh.authentication.response.SigningResponse;
import org.openintents.ssh.authentication.response.SshPublicKeyResponse;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogEntryParcel;
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKey;
import org.sufficientlysecure.keychain.pgp.SshPublicKey;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import org.sufficientlysecure.keychain.provider.ApiAppDao;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
@ -368,18 +368,19 @@ public class SshAuthenticationService extends Service {
private CanonicalizedPublicKey getPublicKey(long masterKeyId) throws NotFoundException {
KeyRepository keyRepository = KeyRepository.create(getApplicationContext());
long authSubKeyId = keyRepository.getCachedPublicKeyRing(masterKeyId)
.getAuthenticationId();
return keyRepository.getCanonicalizedPublicKeyRing(masterKeyId)
.getPublicKey(authSubKeyId);
UnifiedKeyInfo unifiedKeyInfo = keyRepository.getUnifiedKeyInfo(masterKeyId);
if (unifiedKeyInfo == null) {
throw new NotFoundException();
}
return keyRepository.getCanonicalizedPublicKeyRing(masterKeyId).getPublicKey(unifiedKeyInfo.has_auth_key_int());
}
private String getDescription(long masterKeyId) throws NotFoundException {
CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId);
UnifiedKeyInfo unifiedKeyInfo = mKeyRepository.getUnifiedKeyInfo(masterKeyId);
String description = "";
long authSubKeyId = mKeyRepository.getSecretAuthenticationId(masterKeyId);
description += cachedPublicKeyRing.getPrimaryUserId();
description += unifiedKeyInfo.user_id();
description += " (" + Long.toHexString(authSubKeyId) + ")";
return description;

View file

@ -152,8 +152,8 @@ public class RequestKeyPermissionActivity extends FragmentActivity {
}
@Override
public void displayKeyInfo(UserId userId) {
keyUserIdView.setText(userId.name);
public void displayKeyInfo(String userIdName) {
keyUserIdView.setText(userIdName);
}
@Override

View file

@ -25,12 +25,11 @@ import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import org.openintents.openpgp.util.OpenPgpUtils.UserId;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import org.sufficientlysecure.keychain.provider.ApiAppDao;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.remote.ApiPermissionHelper;
@ -94,18 +93,16 @@ class RequestKeyPermissionPresenter {
}
private void setRequestedMasterKeyId(long[] subKeyIds) throws PgpKeyNotFoundException {
CachedPublicKeyRing secretKeyRingOrPublicFallback = findSecretKeyRingOrPublicFallback(subKeyIds);
UnifiedKeyInfo secretKeyRingOrPublicFallback = findSecretKeyRingOrPublicFallback(subKeyIds);
if (secretKeyRingOrPublicFallback == null) {
throw new PgpKeyNotFoundException("No key found among requested!");
}
this.masterKeyId = secretKeyRingOrPublicFallback.getMasterKeyId();
masterKeyId = secretKeyRingOrPublicFallback.master_key_id();
view.displayKeyInfo(secretKeyRingOrPublicFallback.name());
UserId userId = secretKeyRingOrPublicFallback.getSplitPrimaryUserIdWithFallback();
view.displayKeyInfo(userId);
if (secretKeyRingOrPublicFallback.hasAnySecret()) {
if (secretKeyRingOrPublicFallback.has_any_secret()) {
view.switchToLayoutRequestKeyChoice();
} else {
view.switchToLayoutNoSecret();
@ -113,22 +110,22 @@ class RequestKeyPermissionPresenter {
}
@Nullable
private CachedPublicKeyRing findSecretKeyRingOrPublicFallback(long[] subKeyIds) {
CachedPublicKeyRing publicFallbackRing = null;
private UnifiedKeyInfo findSecretKeyRingOrPublicFallback(long[] subKeyIds) {
UnifiedKeyInfo publicFallbackRing = null;
for (long candidateSubKeyId : subKeyIds) {
try {
Long masterKeyId = keyRepository.getMasterKeyIdBySubkeyId(candidateSubKeyId);
if (masterKeyId == null) {
continue;
}
CachedPublicKeyRing cachedPublicKeyRing = keyRepository.getCachedPublicKeyRing(masterKeyId);
UnifiedKeyInfo unifiedKeyInfo = keyRepository.getUnifiedKeyInfo(masterKeyId);
SecretKeyType secretKeyType = keyRepository.getSecretKeyType(candidateSubKeyId);
if (secretKeyType.isUsable()) {
return cachedPublicKeyRing;
return unifiedKeyInfo;
}
if (publicFallbackRing == null) {
publicFallbackRing = cachedPublicKeyRing;
publicFallbackRing = unifiedKeyInfo;
}
} catch (NotFoundException e) {
// no matter
@ -180,7 +177,7 @@ class RequestKeyPermissionPresenter {
void setTitleText(String text);
void setTitleClientIcon(Drawable drawable);
void displayKeyInfo(UserId userId);
void displayKeyInfo(String userIdName);
void finish();
void finishAsCancelled();

View file

@ -34,11 +34,10 @@ import android.widget.ImageView;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.operations.results.CertifyResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.service.CertifyActionsParcel;
import org.sufficientlysecure.keychain.service.CertifyActionsParcel.CertifyAction;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
@ -47,7 +46,6 @@ import org.sufficientlysecure.keychain.ui.util.FormattingUtils;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.widget.CertifyKeySpinner;
import org.sufficientlysecure.keychain.util.Preferences;
import timber.log.Timber;
public class CertifyKeyFragment
@ -68,15 +66,10 @@ public class CertifyKeyFragment
long certifyKeyId = getActivity().getIntent()
.getLongExtra(CertifyKeyActivity.EXTRA_CERTIFY_KEY_ID, Constants.key.none);
if (certifyKeyId != Constants.key.none) {
try {
CachedPublicKeyRing key = (KeyRepository
.create(getContext()))
.getCachedPublicKeyRing(certifyKeyId);
if (key.canCertify()) {
mCertifyKeySpinner.setPreSelectedKeyId(certifyKeyId);
}
} catch (NotFoundException e) {
Timber.e(e, "certify certify check failed");
KeyRepository keyRepository = KeyRepository.create(getContext());
UnifiedKeyInfo unifiedKeyInfo = keyRepository.getUnifiedKeyInfo(certifyKeyId);
if (unifiedKeyInfo != null && unifiedKeyInfo.can_certify()) {
mCertifyKeySpinner.setPreSelectedKeyId(certifyKeyId);
}
}
}

View file

@ -48,7 +48,6 @@ import org.sufficientlysecure.keychain.operations.results.EditKeyResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult;
import org.sufficientlysecure.keychain.operations.results.UploadResult;
import org.sufficientlysecure.keychain.pgp.KeyRing;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.service.ChangeUnlockParcel;
@ -414,8 +413,8 @@ public class CreateKeyFinalFragment extends Fragment {
SaveKeyringParcel.Builder builder;
try {
CachedPublicKeyRing key = keyRepository.getCachedPublicKeyRing(saveKeyResult.mMasterKeyId);
builder = SaveKeyringParcel.buildChangeKeyringParcel(saveKeyResult.mMasterKeyId, key.getFingerprint());
byte[] fingerprint = keyRepository.getFingerprintByKeyId(saveKeyResult.mMasterKeyId);
builder = SaveKeyringParcel.buildChangeKeyringParcel(saveKeyResult.mMasterKeyId, fingerprint);
} catch (NotFoundException e) {
Timber.e("Key that should be moved to Security Token not found in database!");
return;

View file

@ -31,8 +31,8 @@ import android.widget.ViewAnimator;
import com.tokenautocomplete.TokenCompleteTextView.TokenListener;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.ui.adapter.KeyAdapter.KeyItem;
@ -136,16 +136,12 @@ public class EncryptModeAsymmetricFragment extends EncryptModeFragment {
*/
private void preselectKeys(Long signatureKeyId, long[] encryptionKeyIds) {
if (signatureKeyId != null) {
try {
CachedPublicKeyRing keyring = mKeyRepository.getCachedPublicKeyRing(signatureKeyId);
if (keyring.hasAnySecret()) {
mSignKeySpinner.setPreSelectedKeyId(signatureKeyId);
}
} catch (NotFoundException e) {
Timber.e(e, "key not found for signing!");
Notify.create(getActivity(), getString(R.string.error_preselect_sign_key,
KeyFormattingUtils.beautifyKeyId(signatureKeyId)),
Style.ERROR).show();
UnifiedKeyInfo unifiedKeyInfo = mKeyRepository.getUnifiedKeyInfo(signatureKeyId);
if (unifiedKeyInfo == null) {
String beautifyKeyId = KeyFormattingUtils.beautifyKeyId(signatureKeyId);
Notify.create(getActivity(), getString(R.string.error_preselect_sign_key, beautifyKeyId), Style.ERROR).show();
} else if (unifiedKeyInfo.has_any_secret()) {
mSignKeySpinner.setPreSelectedKeyId(signatureKeyId);
}
}

View file

@ -52,13 +52,13 @@ import android.widget.ViewAnimator;
import org.openintents.openpgp.util.OpenPgpUtils;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey.SecretKeyType;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing;
import org.sufficientlysecure.keychain.pgp.KeyRing;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.KeyRepository.NotFoundException;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
@ -285,11 +285,14 @@ public class PassphraseDialogActivity extends FragmentActivity {
KeyRepository keyRepository = KeyRepository.create(getContext());
Long masterKeyId = keyRepository.getMasterKeyIdBySubkeyId(subKeyId);
CachedPublicKeyRing cachedPublicKeyRing = keyRepository.getCachedPublicKeyRing(masterKeyId);
UnifiedKeyInfo unifiedKeyInfo = keyRepository.getUnifiedKeyInfo(masterKeyId);
if (unifiedKeyInfo == null) {
throw new NotFoundException();
}
// yes the inner try/catch block is necessary, otherwise the final variable
// above can't be statically verified to have been set in all cases because
// the catch clause doesn't return.
String mainUserId = cachedPublicKeyRing.getPrimaryUserIdWithFallback();
String mainUserId = unifiedKeyInfo.user_id();
OpenPgpUtils.UserId mainUserIdSplit = KeyRing.splitUserId(mainUserId);
if (mainUserIdSplit.name != null) {
userId = mainUserIdSplit.name;
@ -314,14 +317,10 @@ public class PassphraseDialogActivity extends FragmentActivity {
throw new AssertionError("Unhandled SecretKeyType (should not happen)");
}
}
} catch (KeyRepository.NotFoundException e) {
} catch (NotFoundException e) {
alert.setTitle(R.string.title_key_not_found);
alert.setMessage(getString(R.string.key_not_found, mRequiredInput.getSubKeyId()));
alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
alert.setPositiveButton(android.R.string.ok, (dialog, which) -> dismiss());
alert.setCancelable(false);
return alert.create();
}
@ -595,13 +594,9 @@ public class PassphraseDialogActivity extends FragmentActivity {
} else {
Timber.d("Caching entered passphrase");
try {
PassphraseCacheService.addCachedPassphrase(getActivity(),
unlockedKey.getRing().getMasterKeyId(), unlockedKey.getKeyId(), passphrase,
unlockedKey.getRing().getPrimaryUserIdWithFallback(), timeToLiveSeconds);
} catch (PgpKeyNotFoundException e) {
Timber.e(e, "adding of a passphrase failed");
}
PassphraseCacheService.addCachedPassphrase(getActivity(),
unlockedKey.getRing().getMasterKeyId(), unlockedKey.getKeyId(), passphrase,
unlockedKey.getRing().getPrimaryUserIdWithFallback(), timeToLiveSeconds);
}
finishCaching(passphrase, unlockedKey.getKeyId());

View file

@ -58,7 +58,6 @@ import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKey;
import org.sufficientlysecure.keychain.pgp.SshPublicKey;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.provider.TemporaryFileProvider;
import org.sufficientlysecure.keychain.ui.ViewKeyAdvActivity.ViewKeyAdvViewModel;
@ -140,14 +139,13 @@ public class ViewKeyAdvShareFragment extends Fragment {
}
private String getShareKeyContent(boolean asSshKey)
throws PgpKeyNotFoundException, KeyRepository.NotFoundException, IOException, PgpGeneralException,
NoSuchAlgorithmException {
throws KeyRepository.NotFoundException, IOException, PgpGeneralException, NoSuchAlgorithmException {
KeyRepository keyRepository = KeyRepository.create(requireContext());
String content;
if (asSshKey) {
long authSubKeyId = keyRepository.getCachedPublicKeyRing(unifiedKeyInfo.master_key_id()).getAuthenticationId();
long authSubKeyId = unifiedKeyInfo.has_auth_key_int();
CanonicalizedPublicKey publicKey = keyRepository.getCanonicalizedPublicKeyRing(unifiedKeyInfo.master_key_id())
.getPublicKey(authSubKeyId);
SshPublicKey sshPublicKey = new SshPublicKey(publicKey);
@ -224,7 +222,7 @@ public class ViewKeyAdvShareFragment extends Fragment {
} catch (PgpGeneralException | IOException | NoSuchAlgorithmException e) {
Timber.e(e, "error processing key!");
Notify.create(activity, R.string.error_key_processing, Notify.Style.ERROR).show();
} catch (PgpKeyNotFoundException | KeyRepository.NotFoundException e) {
} catch (KeyRepository.NotFoundException e) {
Timber.e(e, "key not found!");
Notify.create(activity, R.string.error_key_not_found, Notify.Style.ERROR).show();
}

View file

@ -44,8 +44,6 @@ import org.sufficientlysecure.keychain.operations.ImportOperation;
import org.sufficientlysecure.keychain.operations.results.ImportKeyResult;
import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing;
import org.sufficientlysecure.keychain.pgp.CanonicalizedKeyRing.VerificationStatus;
import org.sufficientlysecure.keychain.pgp.KeyRing;
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
import org.sufficientlysecure.keychain.provider.KeyRepository;
import org.sufficientlysecure.keychain.service.ImportKeyringParcel;
import org.sufficientlysecure.keychain.ui.base.CryptoOperationHelper;
@ -88,16 +86,15 @@ public class ImportKeysAdapter extends RecyclerView.Adapter<ImportKeysAdapter.Vi
KeyState keyState = new KeyState();
long keyId = KeyFormattingUtils.convertKeyIdHexToKeyId(entry.getKeyIdHex());
try {
KeyRing keyRing;
VerificationStatus verified;
if (entry.isSecretKey()) {
keyRing = mKeyRepository.getCanonicalizedSecretKeyRing(keyId);
verified = mKeyRepository.getCanonicalizedSecretKeyRing(keyId).getVerified();
} else {
keyRing = mKeyRepository.getCachedPublicKeyRing(keyId);
verified = mKeyRepository.getUnifiedKeyInfo(keyId).verified();
}
keyState.mAlreadyPresent = true;
VerificationStatus verified = keyRing.getVerified();
keyState.mVerified = verified != null && verified != VerificationStatus.UNVERIFIED;
} catch (KeyRepository.NotFoundException | PgpKeyNotFoundException ignored) {
} catch (KeyRepository.NotFoundException ignored) {
}
mKeyStates[i] = keyState;

View file

@ -382,7 +382,7 @@ public class LinkedIdViewFragment extends CryptoOperationFragment implements OnB
byte[] fingerprint;
try {
fingerprint = KeyRepository.create(activity).getCachedPublicKeyRing(masterKeyId).getFingerprint();
fingerprint = KeyRepository.create(activity).getFingerprintByKeyId(masterKeyId);
} catch (NotFoundException e) {
throw new IllegalStateException("Key to verify linked id for must exist in db!");
}

View file

@ -78,6 +78,11 @@ SELECT has_secret
FROM keys
WHERE key_id = ?;
selectFingerprintByKeyId:
SELECT fingerprint
FROM keys
WHERE key_id = ?;
selectEffectiveSignKeyIdByMasterKeyId:
SELECT key_id
FROM keys

View file

@ -34,6 +34,7 @@ import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowLog;
import org.sufficientlysecure.keychain.KeychainTestRunner;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.operations.results.PgpEditKeyResult;
import org.sufficientlysecure.keychain.operations.results.PromoteKeyResult;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey;
@ -42,7 +43,6 @@ import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing;
import org.sufficientlysecure.keychain.pgp.PgpKeyOperation;
import org.sufficientlysecure.keychain.pgp.UncachedKeyRing;
import org.sufficientlysecure.keychain.pgp.UncachedPublicKey;
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
import org.sufficientlysecure.keychain.provider.KeyWritableRepository;
import org.sufficientlysecure.keychain.service.ChangeUnlockParcel;
import org.sufficientlysecure.keychain.service.PromoteKeyringParcel;
@ -115,8 +115,8 @@ public class PromoteKeyOperationTest {
Assert.assertTrue("promotion must succeed", result.success());
{
CachedPublicKeyRing ring = keyRepository.getCachedPublicKeyRing(mStaticRing.getMasterKeyId());
Assert.assertTrue("key must have a secret now", ring.hasAnySecret());
UnifiedKeyInfo unifiedKeyInfo = keyRepository.getUnifiedKeyInfo(mStaticRing.getMasterKeyId());
Assert.assertTrue("key must have a secret now", unifiedKeyInfo.has_any_secret());
Iterator<UncachedPublicKey> it = mStaticRing.getPublicKeys();
while (it.hasNext()) {

View file

@ -31,6 +31,7 @@ import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.shadows.ShadowLog;
import org.sufficientlysecure.keychain.KeychainTestRunner;
import org.sufficientlysecure.keychain.model.SubKey.UnifiedKeyInfo;
import org.sufficientlysecure.keychain.operations.results.OperationResult.OperationLog;
import org.sufficientlysecure.keychain.operations.results.SaveKeyringResult;
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKeyRing;
@ -113,11 +114,11 @@ public class KeyRepositorySaveTest {
mDatabaseInteractor.savePublicKeyRing(pub);
CachedPublicKeyRing cachedRing = mDatabaseInteractor.getCachedPublicKeyRing(keyId);
UnifiedKeyInfo unifiedKeyInfo = mDatabaseInteractor.getUnifiedKeyInfo(keyId);
CanonicalizedPublicKeyRing pubRing = mDatabaseInteractor.getCanonicalizedPublicKeyRing(keyId);
Assert.assertEquals("master key should be encryption key", keyId, pubRing.getEncryptId());
Assert.assertEquals("master key should be encryption key (cached)", keyId, cachedRing.getEncryptId());
Assert.assertEquals("master key should be encryption key (cached)", keyId, unifiedKeyInfo.has_encrypt_key_int());
Assert.assertEquals("canonicalized key flags should be zero",
0, (long) pubRing.getPublicKey().getKeyUsage());
@ -139,7 +140,6 @@ public class KeyRepositorySaveTest {
// make sure both the CanonicalizedSecretKeyRing as well as the CachedPublicKeyRing correctly
// indicate the secret key type
CachedPublicKeyRing cachedRing = mDatabaseInteractor.getCachedPublicKeyRing(keyId);
CanonicalizedSecretKeyRing secRing = mDatabaseInteractor.getCanonicalizedSecretKeyRing(keyId);
Iterator<CanonicalizedSecretKey> it = secRing.secretKeyIterator().iterator();