1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
|
/*
* Copyright (C) 2012-2013 Dominik Schürmann <dominik@dominikschuermann.de>
*
* 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 java.security.SignatureException;
import org.spongycastle.bcpg.ArmoredOutputStream;
import org.spongycastle.bcpg.UserAttributePacket;
import org.spongycastle.bcpg.UserAttributeSubpacket;
import android.content.*;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.RemoteException;
import org.spongycastle.bcpg.ArmoredOutputStream;
import org.spongycastle.openpgp.*;
import org.spongycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.pgp.PgpConversionHelper;
import org.sufficientlysecure.keychain.pgp.PgpHelper;
import org.sufficientlysecure.keychain.pgp.PgpKeyHelper;
import org.sufficientlysecure.keychain.provider.KeychainContract.ApiApps;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainContract.Keys;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserIds;
import org.sufficientlysecure.keychain.provider.KeychainContract.Certs;
import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables;
import org.sufficientlysecure.keychain.service.remote.AppSettings;
import org.sufficientlysecure.keychain.util.IterableIterator;
import org.sufficientlysecure.keychain.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class ProviderHelper {
/**
* Private helper method to get PGPKeyRing from database
*/
public static Map<Long, PGPKeyRing> getPGPKeyRings(Context context, Uri queryUri) {
Cursor cursor = context.getContentResolver().query(queryUri,
new String[]{KeyRings._ID, KeyRings.MASTER_KEY_ID, KeyRings.KEY_RING_DATA}, null, null, null);
Map<Long, PGPKeyRing> result = new HashMap<Long, PGPKeyRing>(cursor.getCount());
if (cursor != null && cursor.moveToFirst()) do {
int keyRingDataCol = cursor.getColumnIndex(KeyRings.KEY_RING_DATA);
int masterKeyIdCol = cursor.getColumnIndex(KeyRings.MASTER_KEY_ID);
byte[] data = cursor.getBlob(keyRingDataCol);
if (data != null) {
result.put(cursor.getLong(masterKeyIdCol), PgpConversionHelper.BytesToPGPKeyRing(data));
}
} while(cursor.moveToNext());
if (cursor != null) {
cursor.close();
}
return result;
}
public static PGPKeyRing getPGPKeyRing(Context context, Uri queryUri) {
return getPGPKeyRings(context, queryUri).values().iterator().next();
}
/**
* Retrieves the actual PGPPublicKeyRing object from the database blob based on the rowId
*/
public static PGPPublicKeyRing getPGPPublicKeyRingByRowId(Context context, long rowId) {
Uri queryUri = KeyRings.buildPublicKeyRingsUri(Long.toString(rowId));
return (PGPPublicKeyRing) getPGPKeyRing(context, queryUri);
}
/**
* Retrieves the actual PGPPublicKeyRing object from the database blob based on the masterKeyId
*/
public static PGPPublicKeyRing getPGPPublicKeyRingByMasterKeyId(Context context,
long masterKeyId) {
Uri queryUri = KeyRings.buildPublicKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId));
return (PGPPublicKeyRing) getPGPKeyRing(context, queryUri);
}
/**
* Retrieves the actual PGPPublicKeyRing object from the database blob associated with a key
* with this keyId
*/
public static PGPPublicKeyRing getPGPPublicKeyRingByKeyId(Context context, long keyId) {
Uri queryUri = KeyRings.buildPublicKeyRingsByKeyIdUri(Long.toString(keyId));
return (PGPPublicKeyRing) getPGPKeyRing(context, queryUri);
}
/**
* Retrieves the actual PGPPublicKey object from the database blob associated with a key with
* this keyId
*/
public static PGPPublicKey getPGPPublicKeyByKeyId(Context context, long keyId) {
PGPPublicKeyRing keyRing = getPGPPublicKeyRingByKeyId(context, keyId);
return (keyRing == null) ? null : keyRing.getPublicKey(keyId);
}
/**
* Retrieves the actual PGPSecretKeyRing object from the database blob based on the rowId
*/
public static PGPSecretKeyRing getPGPSecretKeyRingByRowId(Context context, long rowId) {
Uri queryUri = KeyRings.buildSecretKeyRingsUri(Long.toString(rowId));
return (PGPSecretKeyRing) getPGPKeyRing(context, queryUri);
}
/**
* Retrieves the actual PGPSecretKeyRing object from the database blob based on the maserKeyId
*/
public static PGPSecretKeyRing getPGPSecretKeyRingByMasterKeyId(Context context,
long masterKeyId) {
Uri queryUri = KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId));
return (PGPSecretKeyRing) getPGPKeyRing(context, queryUri);
}
/**
* Retrieves the actual PGPSecretKeyRing object from the database blob associated with a key
* with this keyId
*/
public static PGPSecretKeyRing getPGPSecretKeyRingByKeyId(Context context, long keyId) {
Uri queryUri = KeyRings.buildSecretKeyRingsByKeyIdUri(Long.toString(keyId));
return (PGPSecretKeyRing) getPGPKeyRing(context, queryUri);
}
/**
* Retrieves the actual PGPSecretKey object from the database blob associated with a key with
* this keyId
*/
public static PGPSecretKey getPGPSecretKeyByKeyId(Context context, long keyId) {
PGPSecretKeyRing keyRing = getPGPSecretKeyRingByKeyId(context, keyId);
return (keyRing == null) ? null : keyRing.getSecretKey(keyId);
}
/**
* Saves PGPPublicKeyRing with its keys and userIds in DB
*/
@SuppressWarnings("unchecked")
public static void saveKeyRing(Context context, PGPPublicKeyRing keyRing) throws IOException {
PGPPublicKey masterKey = keyRing.getPublicKey();
long masterKeyId = masterKey.getKeyID();
Uri deleteUri = KeyRings.buildPublicKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId));
// get current _ID of key
long currentRowId = -1;
Cursor oldQuery = context.getContentResolver()
.query(deleteUri, new String[]{KeyRings._ID}, null, null, null);
if (oldQuery != null && oldQuery.moveToFirst()) {
currentRowId = oldQuery.getLong(0);
} else {
Log.e(Constants.TAG, "Key could not be found! Something wrong is happening!");
}
// delete old version of this keyRing, which also deletes all keys and userIds on cascade
try {
context.getContentResolver().delete(deleteUri, null, null);
} catch (UnsupportedOperationException e) {
Log.e(Constants.TAG, "Key could not be deleted! Maybe we are creating a new one!", e);
}
ContentValues values = new ContentValues();
// use exactly the same _ID again to replace key in-place.
// NOTE: If we would not use the same _ID again,
// getting back to the ViewKeyActivity would result in Nullpointer,
// because the currently loaded key would be gone from the database
if (currentRowId != -1) {
values.put(KeyRings._ID, currentRowId);
}
values.put(KeyRings.MASTER_KEY_ID, masterKeyId);
values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded());
// insert new version of this keyRing
Uri uri = KeyRings.buildPublicKeyRingsUri();
Uri insertedUri = context.getContentResolver().insert(uri, values);
long keyRingRowId = Long.valueOf(insertedUri.getLastPathSegment());
// save all keys and userIds included in keyRing object in database
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
int rank = 0;
for (PGPPublicKey key : new IterableIterator<PGPPublicKey>(keyRing.getPublicKeys())) {
operations.add(buildPublicKeyOperations(context, keyRingRowId, key, rank));
++rank;
}
// get a list of owned secret keys, for verification filtering
Map<Long, PGPKeyRing> allKeyRings = getPGPKeyRings(context, KeyRings.buildSecretKeyRingsUri());
int userIdRank = 0;
for (String userId : new IterableIterator<String>(masterKey.getUserIDs())) {
operations.add(buildPublicUserIdOperations(context, keyRingRowId, userId, userIdRank));
// look through signatures for this specific key
for (PGPSignature cert : new IterableIterator<PGPSignature>(
masterKey.getSignaturesForID(userId))) {
long certId = cert.getKeyID();
boolean verified = false;
// do verify signatures from our own private keys
if(allKeyRings.containsKey(certId)) try {
// mark them as verified
cert.init(
new JcaPGPContentVerifierBuilderProvider().setProvider(
Constants.BOUNCY_CASTLE_PROVIDER_NAME),
allKeyRings.get(certId).getPublicKey());
verified = cert.verifyCertification(userId, masterKey);
Log.d(Constants.TAG, "Verified sig for " + userId + " " + verified + " from "
+ PgpKeyHelper.convertKeyIdToHex(cert.getKeyID())
);
} catch(SignatureException e) {
Log.e(Constants.TAG, "Signature verification failed! "
+ PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID())
+ " from "
+ PgpKeyHelper.convertKeyIdToHex(cert.getKeyID()), e);
} catch(PGPException e) {
Log.e(Constants.TAG, "Signature verification failed! "
+ PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID())
+ " from "
+ PgpKeyHelper.convertKeyIdToHex(cert.getKeyID()), e);
}
Log.d(Constants.TAG, "sig for " + userId + " from "
+ PgpKeyHelper.convertKeyIdToHex(cert.getKeyID())
);
// regardless of verification, save the certification
operations.add(buildPublicCertOperations(
context, keyRingRowId, userIdRank, masterKey.getKeyID(), cert, verified));
}
++userIdRank;
}
try {
context.getContentResolver().applyBatch(KeychainContract.CONTENT_AUTHORITY, operations);
} catch (RemoteException e) {
Log.e(Constants.TAG, "applyBatch failed!", e);
} catch (OperationApplicationException e) {
Log.e(Constants.TAG, "applyBatch failed!", e);
}
}
/**
* Saves PGPSecretKeyRing with its keys and userIds in DB
*/
@SuppressWarnings("unchecked")
public static void saveKeyRing(Context context, PGPSecretKeyRing keyRing) throws IOException {
PGPSecretKey masterKey = keyRing.getSecretKey();
long masterKeyId = masterKey.getKeyID();
Uri deleteUri = KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId));
// get current _ID of key
long currentRowId = -1;
Cursor oldQuery = context.getContentResolver()
.query(deleteUri, new String[]{KeyRings._ID}, null, null, null);
if (oldQuery != null && oldQuery.moveToFirst()) {
currentRowId = oldQuery.getLong(0);
} else {
Log.e(Constants.TAG, "Key could not be found! Something wrong is happening!");
}
// delete old version of this keyRing, which also deletes all keys and userIds on cascade
try {
context.getContentResolver().delete(deleteUri, null, null);
} catch (UnsupportedOperationException e) {
Log.e(Constants.TAG, "Key could not be deleted! Maybe we are creating a new one!", e);
}
ContentValues values = new ContentValues();
// use exactly the same _ID again to replace key in-place.
// NOTE: If we would not use the same _ID again,
// getting back to the ViewKeyActivity would result in Nullpointer,
// because the currently loaded key would be gone from the database
if (currentRowId != -1) {
values.put(KeyRings._ID, currentRowId);
}
values.put(KeyRings.MASTER_KEY_ID, masterKeyId);
values.put(KeyRings.KEY_RING_DATA, keyRing.getEncoded());
// insert new version of this keyRing
Uri uri = KeyRings.buildSecretKeyRingsUri();
Uri insertedUri = context.getContentResolver().insert(uri, values);
long keyRingRowId = Long.valueOf(insertedUri.getLastPathSegment());
// save all keys and userIds included in keyRing object in database
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
int rank = 0;
for (PGPSecretKey key : new IterableIterator<PGPSecretKey>(keyRing.getSecretKeys())) {
operations.add(buildSecretKeyOperations(context, keyRingRowId, key, rank));
++rank;
}
int userIdRank = 0;
for (String userId : new IterableIterator<String>(masterKey.getUserIDs())) {
operations.add(buildSecretUserIdOperations(context, keyRingRowId, userId, userIdRank));
++userIdRank;
}
try {
context.getContentResolver().applyBatch(KeychainContract.CONTENT_AUTHORITY, operations);
} catch (RemoteException e) {
Log.e(Constants.TAG, "applyBatch failed!", e);
} catch (OperationApplicationException e) {
Log.e(Constants.TAG, "applyBatch failed!", e);
}
}
/**
* Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing
*/
private static ContentProviderOperation buildPublicKeyOperations(Context context,
long keyRingRowId, PGPPublicKey key, int rank) throws IOException {
ContentValues values = new ContentValues();
values.put(Keys.KEY_ID, key.getKeyID());
values.put(Keys.IS_MASTER_KEY, key.isMasterKey());
values.put(Keys.ALGORITHM, key.getAlgorithm());
values.put(Keys.KEY_SIZE, key.getBitStrength());
values.put(Keys.CAN_SIGN, PgpKeyHelper.isSigningKey(key));
values.put(Keys.CAN_ENCRYPT, PgpKeyHelper.isEncryptionKey(key));
values.put(Keys.IS_REVOKED, key.isRevoked());
values.put(Keys.CREATION, PgpKeyHelper.getCreationDate(key).getTime() / 1000);
Date expiryDate = PgpKeyHelper.getExpiryDate(key);
if (expiryDate != null) {
values.put(Keys.EXPIRY, expiryDate.getTime() / 1000);
}
values.put(Keys.KEY_RING_ROW_ID, keyRingRowId);
values.put(Keys.KEY_DATA, key.getEncoded());
values.put(Keys.RANK, rank);
values.put(Keys.FINGERPRINT, key.getFingerprint());
Uri uri = Keys.buildPublicKeysUri(Long.toString(keyRingRowId));
return ContentProviderOperation.newInsert(uri).withValues(values).build();
}
/**
* Build ContentProviderOperation to add PGPPublicKey to database corresponding to a keyRing
*/
private static ContentProviderOperation buildPublicCertOperations(Context context,
long keyRingRowId,
int rank,
long keyId,
PGPSignature cert,
boolean verified)
throws IOException {
ContentValues values = new ContentValues();
values.put(Certs.KEY_RING_ROW_ID, keyRingRowId);
values.put(Certs.RANK, rank);
values.put(Certs.KEY_ID, keyId);
values.put(Certs.KEY_ID_CERTIFIER, cert.getKeyID());
values.put(Certs.CREATION, cert.getCreationTime().getTime() / 1000);
values.put(Certs.VERIFIED, verified);
values.put(Certs.KEY_DATA, cert.getEncoded());
Uri uri = Certs.buildCertsByKeyRowIdUri(Long.toString(keyRingRowId));
return ContentProviderOperation.newInsert(uri).withValues(values).build();
}
/**
* Build ContentProviderOperation to add PublicUserIds to database corresponding to a keyRing
*/
private static ContentProviderOperation buildPublicUserIdOperations(Context context,
long keyRingRowId, String userId, int rank) {
ContentValues values = new ContentValues();
values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId);
values.put(UserIds.USER_ID, userId);
values.put(UserIds.RANK, rank);
Uri uri = UserIds.buildPublicUserIdsUri(Long.toString(keyRingRowId));
return ContentProviderOperation.newInsert(uri).withValues(values).build();
}
/**
* Build ContentProviderOperation to add PGPSecretKey to database corresponding to a keyRing
*/
private static ContentProviderOperation buildSecretKeyOperations(Context context,
long keyRingRowId, PGPSecretKey key, int rank) throws IOException {
ContentValues values = new ContentValues();
boolean hasPrivate = true;
if (key.isMasterKey()) {
if (key.isPrivateKeyEmpty()) {
hasPrivate = false;
}
}
values.put(Keys.KEY_ID, key.getKeyID());
values.put(Keys.IS_MASTER_KEY, key.isMasterKey());
values.put(Keys.ALGORITHM, key.getPublicKey().getAlgorithm());
values.put(Keys.KEY_SIZE, key.getPublicKey().getBitStrength());
values.put(Keys.CAN_CERTIFY, (PgpKeyHelper.isCertificationKey(key) && hasPrivate));
values.put(Keys.CAN_SIGN, (PgpKeyHelper.isSigningKey(key) && hasPrivate));
values.put(Keys.CAN_ENCRYPT, PgpKeyHelper.isEncryptionKey(key));
values.put(Keys.IS_REVOKED, key.getPublicKey().isRevoked());
values.put(Keys.CREATION, PgpKeyHelper.getCreationDate(key).getTime() / 1000);
Date expiryDate = PgpKeyHelper.getExpiryDate(key);
if (expiryDate != null) {
values.put(Keys.EXPIRY, expiryDate.getTime() / 1000);
}
values.put(Keys.KEY_RING_ROW_ID, keyRingRowId);
values.put(Keys.KEY_DATA, key.getEncoded());
values.put(Keys.RANK, rank);
values.put(Keys.FINGERPRINT, key.getPublicKey().getFingerprint());
Uri uri = Keys.buildSecretKeysUri(Long.toString(keyRingRowId));
return ContentProviderOperation.newInsert(uri).withValues(values).build();
}
/**
* Build ContentProviderOperation to add SecretUserIds to database corresponding to a keyRing
*/
private static ContentProviderOperation buildSecretUserIdOperations(Context context,
long keyRingRowId, String userId, int rank) {
ContentValues values = new ContentValues();
values.put(UserIds.KEY_RING_ROW_ID, keyRingRowId);
values.put(UserIds.USER_ID, userId);
values.put(UserIds.RANK, rank);
Uri uri = UserIds.buildSecretUserIdsUri(Long.toString(keyRingRowId));
return ContentProviderOperation.newInsert(uri).withValues(values).build();
}
/**
* Private helper method
*/
private static ArrayList<Long> getKeyRingsMasterKeyIds(Context context, Uri queryUri) {
Cursor cursor = context.getContentResolver().query(queryUri,
new String[]{KeyRings.MASTER_KEY_ID}, null, null, null);
ArrayList<Long> masterKeyIds = new ArrayList<Long>();
if (cursor != null) {
int masterKeyIdCol = cursor.getColumnIndex(KeyRings.MASTER_KEY_ID);
if (cursor.moveToFirst()) {
do {
masterKeyIds.add(cursor.getLong(masterKeyIdCol));
} while (cursor.moveToNext());
}
}
if (cursor != null) {
cursor.close();
}
return masterKeyIds;
}
/**
* Private helper method
*/
private static ArrayList<Long> getKeyRingsRowIds(Context context, Uri queryUri) {
Cursor cursor = context.getContentResolver().query(queryUri,
new String[]{KeyRings._ID}, null, null, null);
ArrayList<Long> rowIds = new ArrayList<Long>();
if (cursor != null) {
int idCol = cursor.getColumnIndex(KeyRings._ID);
if (cursor.moveToFirst()) {
do {
rowIds.add(cursor.getLong(idCol));
} while (cursor.moveToNext());
}
}
if (cursor != null) {
cursor.close();
}
return rowIds;
}
/**
* Retrieves ids of all SecretKeyRings
*/
public static ArrayList<Long> getSecretKeyRingsMasterKeyIds(Context context) {
Uri queryUri = KeyRings.buildSecretKeyRingsUri();
return getKeyRingsMasterKeyIds(context, queryUri);
}
/**
* Retrieves ids of all PublicKeyRings
*/
public static ArrayList<Long> getPublicKeyRingsMasterKeyIds(Context context) {
Uri queryUri = KeyRings.buildPublicKeyRingsUri();
return getKeyRingsMasterKeyIds(context, queryUri);
}
/**
* Retrieves ids of all SecretKeyRings
*/
public static ArrayList<Long> getSecretKeyRingsRowIds(Context context) {
Uri queryUri = KeyRings.buildSecretKeyRingsUri();
return getKeyRingsRowIds(context, queryUri);
}
/**
* Retrieves ids of all PublicKeyRings
*/
public static ArrayList<Long> getPublicKeyRingsRowIds(Context context) {
Uri queryUri = KeyRings.buildPublicKeyRingsUri();
return getKeyRingsRowIds(context, queryUri);
}
public static void deletePublicKeyRing(Context context, long rowId) {
ContentResolver cr = context.getContentResolver();
cr.delete(KeyRings.buildPublicKeyRingsUri(Long.toString(rowId)), null, null);
}
public static void deleteSecretKeyRing(Context context, long rowId) {
ContentResolver cr = context.getContentResolver();
cr.delete(KeyRings.buildSecretKeyRingsUri(Long.toString(rowId)), null, null);
}
/**
* Get master key id of keyring by its row id
*/
public static long getPublicMasterKeyId(Context context, long keyRingRowId) {
Uri queryUri = KeyRings.buildPublicKeyRingsUri(String.valueOf(keyRingRowId));
return getMasterKeyId(context, queryUri);
}
/**
* Get empty status of master key of keyring by its row id
*/
public static boolean getSecretMasterKeyCanSign(Context context, long keyRingRowId) {
Uri queryUri = KeyRings.buildSecretKeyRingsUri(String.valueOf(keyRingRowId));
return getMasterKeyCanSign(context, queryUri);
}
/**
* Private helper method to get master key private empty status of keyring by its row id
*/
public static boolean getMasterKeyCanSign(Context context, Uri queryUri) {
String[] projection = new String[]{
KeyRings.MASTER_KEY_ID,
"(SELECT COUNT(sign_keys." + Keys._ID + ") FROM " + Tables.KEYS
+ " AS sign_keys WHERE sign_keys." + Keys.KEY_RING_ROW_ID + " = "
+ KeychainDatabase.Tables.KEY_RINGS + "." + KeyRings._ID
+ " AND sign_keys." + Keys.CAN_SIGN + " = '1' AND " + Keys.IS_MASTER_KEY
+ " = 1) AS sign", };
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(queryUri, projection, null, null, null);
long masterKeyId = -1;
if (cursor != null && cursor.moveToFirst()) {
int masterKeyIdCol = cursor.getColumnIndex("sign");
masterKeyId = cursor.getLong(masterKeyIdCol);
}
if (cursor != null) {
cursor.close();
}
return (masterKeyId > 0);
}
public static boolean hasSecretKeyByMasterKeyId(Context context, long masterKeyId) {
Uri queryUri = KeyRings.buildSecretKeyRingsByMasterKeyIdUri(Long.toString(masterKeyId));
// see if we can get our master key id back from the uri
return getMasterKeyId(context, queryUri) == masterKeyId;
}
/**
* Get master key id of keyring by its row id
*/
public static long getSecretMasterKeyId(Context context, long keyRingRowId) {
Uri queryUri = KeyRings.buildSecretKeyRingsUri(String.valueOf(keyRingRowId));
return getMasterKeyId(context, queryUri);
}
/**
* Get master key id of key
*/
public static long getMasterKeyId(Context context, Uri queryUri) {
String[] projection = new String[]{KeyRings.MASTER_KEY_ID};
Cursor cursor = context.getContentResolver().query(queryUri, projection, null, null, null);
long masterKeyId = 0;
try {
if (cursor != null && cursor.moveToFirst()) {
int masterKeyIdCol = cursor.getColumnIndexOrThrow(KeyRings.MASTER_KEY_ID);
masterKeyId = cursor.getLong(masterKeyIdCol);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return masterKeyId;
}
public static long getRowId(Context context, Uri queryUri) {
String[] projection = new String[]{KeyRings._ID};
Cursor cursor = context.getContentResolver().query(queryUri, projection, null, null, null);
long rowId = 0;
try {
if (cursor != null && cursor.moveToFirst()) {
int idCol = cursor.getColumnIndexOrThrow(KeyRings._ID);
rowId = cursor.getLong(idCol);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return rowId;
}
/**
* Get fingerprint of key
*/
public static byte[] getFingerprint(Context context, Uri queryUri) {
String[] projection = new String[]{Keys.FINGERPRINT};
Cursor cursor = context.getContentResolver().query(queryUri, projection, null, null, null);
byte[] fingerprint = null;
try {
if (cursor != null && cursor.moveToFirst()) {
int col = cursor.getColumnIndexOrThrow(Keys.FINGERPRINT);
fingerprint = cursor.getBlob(col);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// FALLBACK: If fingerprint is not in database, get it from key blob!
// this could happen if the key was saved by a previous version of Keychain!
if (fingerprint == null) {
Log.d(Constants.TAG, "FALLBACK: fingerprint is not in database, get it from key blob!");
// get master key id
projection = new String[]{KeyRings.MASTER_KEY_ID};
cursor = context.getContentResolver().query(queryUri, projection, null, null, null);
long masterKeyId = 0;
try {
if (cursor != null && cursor.moveToFirst()) {
int col = cursor.getColumnIndexOrThrow(KeyRings.MASTER_KEY_ID);
masterKeyId = cursor.getLong(col);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
PGPPublicKey key = ProviderHelper.getPGPPublicKeyByKeyId(context, masterKeyId);
// if it is no public key get it from your own keys...
if (key == null) {
PGPSecretKey secretKey = ProviderHelper.getPGPSecretKeyByKeyId(context, masterKeyId);
if (secretKey == null) {
Log.e(Constants.TAG, "Key could not be found!");
return null;
}
key = secretKey.getPublicKey();
}
fingerprint = key.getFingerprint();
}
return fingerprint;
}
public static String getUserId(Context context, Uri queryUri) {
String[] projection = new String[]{UserIds.USER_ID};
Cursor cursor = context.getContentResolver().query(queryUri, projection, null, null, null);
String userId = null;
try {
if (cursor != null && cursor.moveToFirst()) {
int col = cursor.getColumnIndexOrThrow(UserIds.USER_ID);
userId = cursor.getString(col);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return userId;
}
public static ArrayList<String> getKeyRingsAsArmoredString(Context context, Uri uri,
long[] masterKeyIds) {
ArrayList<String> output = new ArrayList<String>();
if (masterKeyIds != null && masterKeyIds.length > 0) {
Cursor cursor = getCursorWithSelectedKeyringMasterKeyIds(context, uri, masterKeyIds);
if (cursor != null) {
int masterIdCol = cursor.getColumnIndex(KeyRings.MASTER_KEY_ID);
int dataCol = cursor.getColumnIndex(KeyRings.KEY_RING_DATA);
if (cursor.moveToFirst()) {
do {
Log.d(Constants.TAG, "masterKeyId: " + cursor.getLong(masterIdCol));
// get actual keyring data blob and write it to ByteArrayOutputStream
try {
Object keyRing = null;
byte[] data = cursor.getBlob(dataCol);
if (data != null) {
keyRing = PgpConversionHelper.BytesToPGPKeyRing(data);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ArmoredOutputStream aos = new ArmoredOutputStream(bos);
aos.setHeader("Version", PgpHelper.getFullVersion(context));
if (keyRing instanceof PGPSecretKeyRing) {
aos.write(((PGPSecretKeyRing) keyRing).getEncoded());
} else if (keyRing instanceof PGPPublicKeyRing) {
aos.write(((PGPPublicKeyRing) keyRing).getEncoded());
}
aos.close();
String armoredKey = bos.toString("UTF-8");
Log.d(Constants.TAG, "armoredKey:" + armoredKey);
output.add(armoredKey);
} catch (IOException e) {
Log.e(Constants.TAG, "IOException", e);
}
} while (cursor.moveToNext());
}
}
if (cursor != null) {
cursor.close();
}
} else {
Log.e(Constants.TAG, "No master keys given!");
}
if (output.size() > 0) {
return output;
} else {
return null;
}
}
public static byte[] getKeyRingsAsByteArray(Context context, Uri uri, long[] masterKeyIds) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (masterKeyIds != null && masterKeyIds.length > 0) {
Cursor cursor = getCursorWithSelectedKeyringMasterKeyIds(context, uri, masterKeyIds);
if (cursor != null) {
int masterIdCol = cursor.getColumnIndex(KeyRings.MASTER_KEY_ID);
int dataCol = cursor.getColumnIndex(KeyRings.KEY_RING_DATA);
if (cursor.moveToFirst()) {
do {
Log.d(Constants.TAG, "masterKeyId: " + cursor.getLong(masterIdCol));
// get actual keyring data blob and write it to ByteArrayOutputStream
try {
bos.write(cursor.getBlob(dataCol));
} catch (IOException e) {
Log.e(Constants.TAG, "IOException", e);
}
} while (cursor.moveToNext());
}
}
if (cursor != null) {
cursor.close();
}
} else {
Log.e(Constants.TAG, "No master keys given!");
}
return bos.toByteArray();
}
private static Cursor getCursorWithSelectedKeyringMasterKeyIds(Context context, Uri baseUri,
long[] masterKeyIds) {
Cursor cursor = null;
if (masterKeyIds != null && masterKeyIds.length > 0) {
String inMasterKeyList = KeyRings.MASTER_KEY_ID + " IN (";
for (int i = 0; i < masterKeyIds.length; ++i) {
if (i != 0) {
inMasterKeyList += ", ";
}
inMasterKeyList += DatabaseUtils.sqlEscapeString("" + masterKeyIds[i]);
}
inMasterKeyList += ")";
cursor = context.getContentResolver().query(baseUri,
new String[]{KeyRings._ID, KeyRings.MASTER_KEY_ID, KeyRings.KEY_RING_DATA},
inMasterKeyList, null, null);
}
return cursor;
}
public static ArrayList<String> getRegisteredApiApps(Context context) {
Cursor cursor = context.getContentResolver().query(ApiApps.CONTENT_URI, null, null, null,
null);
ArrayList<String> packageNames = new ArrayList<String>();
if (cursor != null) {
int packageNameCol = cursor.getColumnIndex(ApiApps.PACKAGE_NAME);
if (cursor.moveToFirst()) {
do {
packageNames.add(cursor.getString(packageNameCol));
} while (cursor.moveToNext());
}
}
if (cursor != null) {
cursor.close();
}
return packageNames;
}
private static ContentValues contentValueForApiApps(AppSettings appSettings) {
ContentValues values = new ContentValues();
values.put(ApiApps.PACKAGE_NAME, appSettings.getPackageName());
values.put(ApiApps.PACKAGE_SIGNATURE, appSettings.getPackageSignature());
values.put(ApiApps.KEY_ID, appSettings.getKeyId());
values.put(ApiApps.COMPRESSION, appSettings.getCompression());
values.put(ApiApps.ENCRYPTION_ALGORITHM, appSettings.getEncryptionAlgorithm());
values.put(ApiApps.HASH_ALORITHM, appSettings.getHashAlgorithm());
return values;
}
public static void insertApiApp(Context context, AppSettings appSettings) {
context.getContentResolver().insert(ApiApps.CONTENT_URI,
contentValueForApiApps(appSettings));
}
public static void updateApiApp(Context context, AppSettings appSettings, Uri uri) {
if (context.getContentResolver().update(uri, contentValueForApiApps(appSettings), null,
null) <= 0) {
throw new RuntimeException();
}
}
public static AppSettings getApiAppSettings(Context context, Uri uri) {
AppSettings settings = null;
Cursor cur = context.getContentResolver().query(uri, null, null, null, null);
if (cur != null && cur.moveToFirst()) {
settings = new AppSettings();
settings.setPackageName(cur.getString(cur
.getColumnIndex(KeychainContract.ApiApps.PACKAGE_NAME)));
settings.setPackageSignature(cur.getBlob(cur
.getColumnIndex(KeychainContract.ApiApps.PACKAGE_SIGNATURE)));
settings.setKeyId(cur.getLong(cur.getColumnIndex(KeychainContract.ApiApps.KEY_ID)));
settings.setCompression(cur.getInt(cur
.getColumnIndexOrThrow(KeychainContract.ApiApps.COMPRESSION)));
settings.setHashAlgorithm(cur.getInt(cur
.getColumnIndexOrThrow(KeychainContract.ApiApps.HASH_ALORITHM)));
settings.setEncryptionAlgorithm(cur.getInt(cur
.getColumnIndexOrThrow(KeychainContract.ApiApps.ENCRYPTION_ALGORITHM)));
}
return settings;
}
public static byte[] getApiAppSignature(Context context, String packageName) {
Uri queryUri = KeychainContract.ApiApps.buildByPackageNameUri(packageName);
String[] projection = new String[]{ApiApps.PACKAGE_SIGNATURE};
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(queryUri, projection, null, null, null);
byte[] signature = null;
if (cursor != null && cursor.moveToFirst()) {
int signatureCol = 0;
signature = cursor.getBlob(signatureCol);
}
if (cursor != null) {
cursor.close();
}
return signature;
}
}
|