/
Util.java
2089 lines (1919 loc) · 84 KB
/
Util.java
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.identity;
import android.content.Context;
import android.security.keystore.KeyProperties;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequenceGenerator;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import co.nstant.in.cbor.CborBuilder;
import co.nstant.in.cbor.CborDecoder;
import co.nstant.in.cbor.CborEncoder;
import co.nstant.in.cbor.CborException;
import co.nstant.in.cbor.builder.ArrayBuilder;
import co.nstant.in.cbor.builder.MapBuilder;
import co.nstant.in.cbor.model.AbstractFloat;
import co.nstant.in.cbor.model.Array;
import co.nstant.in.cbor.model.ByteString;
import co.nstant.in.cbor.model.DataItem;
import co.nstant.in.cbor.model.DoublePrecisionFloat;
import co.nstant.in.cbor.model.MajorType;
import co.nstant.in.cbor.model.Map;
import co.nstant.in.cbor.model.NegativeInteger;
import co.nstant.in.cbor.model.Number;
import co.nstant.in.cbor.model.SimpleValue;
import co.nstant.in.cbor.model.SimpleValueType;
import co.nstant.in.cbor.model.SpecialType;
import co.nstant.in.cbor.model.UnicodeString;
import co.nstant.in.cbor.model.UnsignedInteger;
/**
* Utility functions.
*/
class Util {
private static final String TAG = "Util";
private static final long COSE_LABEL_ALG = 1;
private static final long COSE_LABEL_X5CHAIN = 33; // temporary identifier
// From RFC 8152: Table 5: ECDSA Algorithm Values
private static final long COSE_ALG_ECDSA_256 = -7;
private static final long COSE_ALG_ECDSA_384 = -35;
private static final long COSE_ALG_ECDSA_512 = -36;
private static final long COSE_ALG_HMAC_256_256 = 5;
private static final long CBOR_SEMANTIC_TAG_ENCODED_CBOR = 24;
private static final long COSE_KEY_KTY = 1;
private static final long COSE_KEY_TYPE_EC2 = 2;
private static final long COSE_KEY_EC2_CRV = -1;
private static final long COSE_KEY_EC2_X = -2;
private static final long COSE_KEY_EC2_Y = -3;
private static final long COSE_KEY_EC2_CRV_P256 = 1;
// Not called.
private Util() {
}
/* TODO: add cborBuildDate() which generates a full-date where
*
* full-date = #6.1004(tstr),
*
* and where tag 1004 is specified in RFC 8943.
*/
static @NonNull
byte[] fromHex(@NonNull String stringWithHex) {
int stringLength = stringWithHex.length();
if ((stringLength % 2) != 0) {
throw new IllegalArgumentException("Invalid length of hex string: " + stringLength);
}
int numBytes = stringLength / 2;
byte[] data = new byte[numBytes];
for (int n = 0; n < numBytes; n++) {
String byteStr = stringWithHex.substring(2 * n, 2 * n + 2);
data[n] = (byte) Integer.parseInt(byteStr, 16);
}
return data;
}
static @NonNull
String toHex(@NonNull byte[] bytes) {
return toHex(bytes, 0, bytes.length);
}
@VisibleForTesting
static @NonNull String toHex(@NonNull byte[] bytes, int from, int to) {
if (from < 0 || to > bytes.length || from > to) {
String msg = String.format(Locale.US, "Expected 0 <= from <= to <= %d, got %d, %d.",
bytes.length, from, to);
throw new IllegalArgumentException(msg);
}
StringBuilder sb = new StringBuilder();
for (int n = from; n < to; n++) {
byte b = bytes[n];
sb.append(String.format("%02x", b));
}
return sb.toString();
}
static void dumpHex(@NonNull String tag, @NonNull String message,
@NonNull byte[] bytes) {
Log.i(tag, message + " (" + bytes.length + " bytes)");
final int chunkSize = 1024;
for (int offset = 0; offset < bytes.length; offset += chunkSize) {
String s = toHex(bytes, offset, Math.min(bytes.length, offset + chunkSize));
Log.i(tag, "data: " + s);
}
}
static @NonNull
String base16(@NonNull byte[] bytes) {
return toHex(bytes).toUpperCase(Locale.ROOT);
}
static @NonNull
byte[] cborEncode(@NonNull DataItem dataItem) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
new CborEncoder(baos).encode(dataItem);
} catch (CborException e) {
// This should never happen and we don't want cborEncode() to throw since that
// would complicate all callers. Log it instead.
throw new IllegalStateException("Unexpected failure encoding data", e);
}
return baos.toByteArray();
}
static @NonNull
byte[] cborEncodeWithoutCanonicalizing(@NonNull DataItem dataItem) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
new CborEncoder(baos).nonCanonical().encode(dataItem);
} catch (CborException e) {
// This should never happen and we don't want cborEncode() to throw since that
// would complicate all callers. Log it instead.
throw new IllegalStateException("Unexpected failure encoding data", e);
}
return baos.toByteArray();
}
static @NonNull
byte[] cborEncodeBoolean(boolean value) {
return cborEncode(new CborBuilder().add(value).build().get(0));
}
static @NonNull
byte[] cborEncodeString(@NonNull String value) {
return cborEncode(new CborBuilder().add(value).build().get(0));
}
static @NonNull
byte[] cborEncodeNumber(long value) {
return cborEncode(new CborBuilder().add(value).build().get(0));
}
static @NonNull
byte[] cborEncodeBytestring(@NonNull byte[] value) {
return cborEncode(new CborBuilder().add(value).build().get(0));
}
static @NonNull
byte[] cborEncodeDateTime(@NonNull Timestamp timestamp) {
return cborEncode(cborBuildDateTime(timestamp));
}
static @NonNull
byte[] cborEncodeDateTimeFor18013_5(@NonNull Timestamp timestamp) {
return cborEncode(cborBuildDateTimeFor18013_5(timestamp));
}
/**
* Returns #6.0(tstr) where tstr is the ISO 8601 encoding of the given point in time.
* Only supports UTC times.
*/
static @NonNull
DataItem cborBuildDateTime(@NonNull Timestamp timestamp) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US);
if (timestamp.toEpochMilli() % 1000 != 0) {
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US);
}
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date val = new Date(timestamp.toEpochMilli());
String dateString = df.format(val);
DataItem dataItem = new UnicodeString(dateString);
dataItem.setTag(0);
return dataItem;
}
static @NonNull
DataItem cborBuildDateTimeFor18013_5(@NonNull Timestamp timestamp) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date val = new Date(timestamp.toEpochMilli());
String dateString = df.format(val);
DataItem dataItem = new UnicodeString(dateString);
dataItem.setTag(0);
return dataItem;
}
static @NonNull
DataItem cborDecode(@NonNull byte[] encodedBytes) {
ByteArrayInputStream bais = new ByteArrayInputStream(encodedBytes);
List<DataItem> dataItems = null;
try {
dataItems = new CborDecoder(bais).decode();
} catch (CborException e) {
throw new IllegalArgumentException("Error decoding CBOR", e);
}
if (dataItems.size() != 1) {
throw new IllegalArgumentException("Unexpected number of items, expected 1 got "
+ dataItems.size());
}
return dataItems.get(0);
}
static boolean cborDecodeBoolean(@NonNull byte[] data) {
SimpleValue simple = (SimpleValue) cborDecode(data);
return simple.getSimpleValueType() == SimpleValueType.TRUE;
}
static @NonNull
String cborDecodeString(@NonNull byte[] data) {
DataItem dataItem = cborDecode(data);
return castTo(UnicodeString.class, dataItem).getString();
}
static long cborDecodeLong(@NonNull byte[] data) {
DataItem dataItem = cborDecode(data);
return castTo(Number.class, dataItem).getValue().longValue();
}
static @NonNull
byte[] cborDecodeByteString(@NonNull byte[] data) {
DataItem dataItem = cborDecode(data);
return castTo(ByteString.class, dataItem).getBytes();
}
static @NonNull
Timestamp cborDecodeDateTime(@NonNull byte[] data) {
return cborDecodeDateTime(cborDecode(data));
}
static @NonNull
Timestamp cborDecodeDateTime(DataItem di) {
if (!(di instanceof co.nstant.in.cbor.model.UnicodeString)) {
throw new IllegalArgumentException("Passed in data is not a Unicode-string");
}
if (!di.hasTag() || di.getTag().getValue() != 0) {
throw new IllegalArgumentException("Passed in data is not tagged with tag 0");
}
String dateString = ((co.nstant.in.cbor.model.UnicodeString) di).getString();
// Manually parse the timezone
TimeZone parsedTz = TimeZone.getTimeZone("UTC");
if (!dateString.endsWith("Z")) {
String timeZoneSubstr = dateString.substring(dateString.length() - 6);
parsedTz = TimeZone.getTimeZone("GMT" + timeZoneSubstr);
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
df.setTimeZone(parsedTz);
Date date = null;
try {
date = df.parse(dateString);
} catch (ParseException e) {
// Try again, this time without the milliseconds
df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
df.setTimeZone(parsedTz);
try {
date = df.parse(dateString);
} catch (ParseException e2) {
throw new RuntimeException("Error parsing string", e2);
}
}
return Timestamp.ofEpochMilli(date.getTime());
}
/**
* Similar to a typecast of {@code value} to the given type {@code clazz}, except:
* <ul>
* <li>Throws {@code IllegalArgumentException} instead of {@code ClassCastException} if
* {@code !clazz.isAssignableFrom(value.getClass())}.</li>
* <li>Also throws {@code IllegalArgumentException} if {@code value == null}.</li>
* </ul>
*/
static @NonNull<T extends V, V> T castTo(Class<T> clazz, V value) {
if (value == null || !clazz.isAssignableFrom(value.getClass())) {
String valueStr = (value == null) ? "null" : value.getClass().toString();
throw new IllegalArgumentException("Expected type " + clazz + ", got type " + valueStr);
} else {
return (T) value;
}
}
/**
* Helper function to check if a given certificate chain is valid.
*
* NOTE NOTE NOTE: We only check that the certificates in the chain sign each other. We
* <em>specifically</em> don't check that each certificate is also a CA certificate.
*
* @param certificateChain the chain to validate.
* @return <code>true</code> if valid, <code>false</code> otherwise.
*/
static boolean validateCertificateChain(
@NonNull Collection<X509Certificate> certificateChain) {
// First check that each certificate signs the previous one...
X509Certificate prevCertificate = null;
for (X509Certificate certificate : certificateChain) {
if (prevCertificate != null) {
// We're not the leaf certificate...
//
// Check the previous certificate was signed by this one.
try {
prevCertificate.verify(certificate.getPublicKey());
} catch (CertificateException
| InvalidKeyException
| NoSuchAlgorithmException
| NoSuchProviderException
| SignatureException e) {
return false;
}
} else {
// we're the leaf certificate so we're not signing anything nor
// do we need to be e.g. a CA certificate.
}
prevCertificate = certificate;
}
return true;
}
/**
* Computes an HKDF.
*
* This is based on https://github.com/google/tink/blob/master/java/src/main/java/com/google
* /crypto/tink/subtle/Hkdf.java
* which is also Copyright (c) Google and also licensed under the Apache 2 license.
*
* @param macAlgorithm the MAC algorithm used for computing the Hkdf. I.e., "HMACSHA1" or
* "HMACSHA256".
* @param ikm the input keying material.
* @param salt optional salt. A possibly non-secret random value. If no salt is
* provided (i.e. if
* salt has length 0) then an array of 0s of the same size as the hash
* digest is used as salt.
* @param info optional context and application specific information.
* @param size The length of the generated pseudorandom string in bytes. The maximal
* size is
* 255.DigestSize, where DigestSize is the size of the underlying HMAC.
* @return size pseudorandom bytes.
*/
static @NonNull
byte[] computeHkdf(
@NonNull String macAlgorithm, @NonNull final byte[] ikm, @NonNull final byte[] salt,
@NonNull final byte[] info, int size) {
Mac mac = null;
try {
mac = Mac.getInstance(macAlgorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No such algorithm: " + macAlgorithm, e);
}
if (size > 255 * mac.getMacLength()) {
throw new IllegalArgumentException("size too large");
}
try {
if (salt == null || salt.length == 0) {
// According to RFC 5869, Section 2.2 the salt is optional. If no salt is provided
// then HKDF uses a salt that is an array of zeros of the same length as the hash
// digest.
mac.init(new SecretKeySpec(new byte[mac.getMacLength()], macAlgorithm));
} else {
mac.init(new SecretKeySpec(salt, macAlgorithm));
}
byte[] prk = mac.doFinal(ikm);
byte[] result = new byte[size];
int ctr = 1;
int pos = 0;
mac.init(new SecretKeySpec(prk, macAlgorithm));
byte[] digest = new byte[0];
while (true) {
mac.update(digest);
mac.update(info);
mac.update((byte) ctr);
digest = mac.doFinal();
if (pos + digest.length < size) {
System.arraycopy(digest, 0, result, pos, digest.length);
pos += digest.length;
ctr++;
} else {
System.arraycopy(digest, 0, result, pos, size - pos);
break;
}
}
return result;
} catch (InvalidKeyException e) {
throw new IllegalStateException("Error MACing", e);
}
}
private static byte[] coseBuildToBeSigned(byte[] encodedProtectedHeaders,
byte[] payload,
byte[] detachedContent) {
CborBuilder sigStructure = new CborBuilder();
ArrayBuilder<CborBuilder> array = sigStructure.addArray();
array.add("Signature1");
array.add(encodedProtectedHeaders);
// We currently don't support Externally Supplied Data (RFC 8152 section 4.3)
// so external_aad is the empty bstr
byte[] emptyExternalAad = new byte[0];
array.add(emptyExternalAad);
// Next field is the payload, independently of how it's transported (RFC
// 8152 section 4.4). Since our API specifies only one of |data| and
// |detachedContent| can be non-empty, it's simply just the non-empty one.
if (payload != null && payload.length > 0) {
array.add(payload);
} else {
array.add(detachedContent);
}
array.end();
return cborEncode(sigStructure.build().get(0));
}
/*
* From RFC 8152 section 8.1 ECDSA:
*
* The signature algorithm results in a pair of integers (R, S). These
* integers will be the same length as the length of the key used for
* the signature process. The signature is encoded by converting the
* integers into byte strings of the same length as the key size. The
* length is rounded up to the nearest byte and is left padded with zero
* bits to get to the correct length. The two integers are then
* concatenated together to form a byte string that is the resulting
* signature.
*/
private static byte[] signatureDerToCose(byte[] signature, int keySize) {
ASN1Primitive asn1;
try {
asn1 = new ASN1InputStream(new ByteArrayInputStream(signature)).readObject();
} catch (IOException e) {
throw new IllegalArgumentException("Error decoding DER signature", e);
}
ASN1Encodable[] asn1Encodables = castTo(ASN1Sequence.class, asn1).toArray();
if (asn1Encodables.length != 2) {
throw new IllegalArgumentException("Expected two items in sequence");
}
BigInteger r = castTo(ASN1Integer.class, asn1Encodables[0].toASN1Primitive()).getValue();
BigInteger s = castTo(ASN1Integer.class, asn1Encodables[1].toASN1Primitive()).getValue();
byte[] rBytes = stripLeadingZeroes(r.toByteArray());
byte[] sBytes = stripLeadingZeroes(s.toByteArray());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
for (int n = 0; n < keySize - rBytes.length; n++) {
baos.write(0x00);
}
baos.write(rBytes);
for (int n = 0; n < keySize - sBytes.length; n++) {
baos.write(0x00);
}
baos.write(sBytes);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return baos.toByteArray();
}
private static byte[] signatureCoseToDer(byte[] signature) {
// r and s are always positive and may use all bits so use the constructor which
// parses them as unsigned.
BigInteger r = new BigInteger(1, Arrays.copyOfRange(
signature, 0, signature.length / 2));
BigInteger s = new BigInteger(1, Arrays.copyOfRange(
signature, signature.length / 2, signature.length));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
DERSequenceGenerator seq = new DERSequenceGenerator(baos);
seq.addObject(new ASN1Integer(r.toByteArray()));
seq.addObject(new ASN1Integer(s.toByteArray()));
seq.close();
} catch (IOException e) {
throw new IllegalStateException("Error generating DER signature", e);
}
return baos.toByteArray();
}
static @NonNull
DataItem coseSign1Sign(@NonNull Signature s,
@Nullable byte[] data,
@Nullable byte[] detachedContent,
@Nullable Collection<X509Certificate> certificateChain) {
int dataLen = (data != null ? data.length : 0);
int detachedContentLen = (detachedContent != null ? detachedContent.length : 0);
if (dataLen > 0 && detachedContentLen > 0) {
throw new IllegalArgumentException("data and detachedContent cannot both be non-empty");
}
int keySize;
long alg;
if (s.getAlgorithm().equals("SHA256withECDSA")) {
keySize = 32;
alg = COSE_ALG_ECDSA_256;
} else if (s.getAlgorithm().equals("SHA384withECDSA")) {
keySize = 48;
alg = COSE_ALG_ECDSA_384;
} else if (s.getAlgorithm().equals("SHA512withECDSA")) {
keySize = 64;
alg = COSE_ALG_ECDSA_512;
} else {
throw new IllegalArgumentException("Unsupported algorithm " + s.getAlgorithm());
}
CborBuilder protectedHeaders = new CborBuilder();
MapBuilder<CborBuilder> protectedHeadersMap = protectedHeaders.addMap();
protectedHeadersMap.put(COSE_LABEL_ALG, alg);
byte[] protectedHeadersBytes = cborEncode(protectedHeaders.build().get(0));
byte[] toBeSigned = coseBuildToBeSigned(protectedHeadersBytes, data, detachedContent);
byte[] coseSignature = null;
try {
s.update(toBeSigned);
byte[] derSignature = s.sign();
coseSignature = signatureDerToCose(derSignature, keySize);
} catch (SignatureException e) {
throw new IllegalStateException("Error signing data", e);
}
CborBuilder builder = new CborBuilder();
ArrayBuilder<CborBuilder> array = builder.addArray();
array.add(protectedHeadersBytes);
MapBuilder<ArrayBuilder<CborBuilder>> unprotectedHeaders = array.addMap();
try {
if (certificateChain != null && certificateChain.size() > 0) {
if (certificateChain.size() == 1) {
X509Certificate cert = certificateChain.iterator().next();
unprotectedHeaders.put(COSE_LABEL_X5CHAIN, cert.getEncoded());
} else {
ArrayBuilder<MapBuilder<ArrayBuilder<CborBuilder>>> x5chainsArray =
unprotectedHeaders.putArray(COSE_LABEL_X5CHAIN);
for (X509Certificate cert : certificateChain) {
x5chainsArray.add(cert.getEncoded());
}
}
}
} catch (CertificateEncodingException e) {
throw new IllegalStateException("Error encoding certificate", e);
}
if (data == null || data.length == 0) {
array.add(new SimpleValue(SimpleValueType.NULL));
} else {
array.add(data);
}
array.add(coseSignature);
return builder.build().get(0);
}
/**
* Note: this uses the default JCA provider which may not support a lot of curves, for
* example it doesn't support Brainpool curves. If you need to use such curves, use
* {@link #coseSign1Sign(Signature, byte[], byte[], Collection)} instead with a
* Signature created using a provider that does have support.
*
* Currently only ECDSA signatures are supported.
*
* TODO: add support and tests for Ed25519 and Ed448.
*/
static @NonNull
DataItem coseSign1Sign(@NonNull PrivateKey key,
@NonNull String algorithm, @Nullable byte[] data,
@Nullable byte[] additionalData,
@Nullable Collection<X509Certificate> certificateChain) {
try {
Signature s = Signature.getInstance(algorithm);
s.initSign(key);
return coseSign1Sign(s, data, additionalData, certificateChain);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException("Caught exception", e);
}
}
/**
* Currently only ECDSA signatures are supported.
*
* TODO: add support and tests for Ed25519 and Ed448.
*/
static boolean coseSign1CheckSignature(@NonNull DataItem coseSign1,
@NonNull byte[] detachedContent, @NonNull PublicKey publicKey) {
if (coseSign1.getMajorType() != MajorType.ARRAY) {
throw new IllegalArgumentException("Data item is not an array");
}
List<DataItem> items = ((co.nstant.in.cbor.model.Array) coseSign1).getDataItems();
if (items.size() < 4) {
throw new IllegalArgumentException("Expected at least four items in COSE_Sign1 array");
}
if (items.get(0).getMajorType() != MajorType.BYTE_STRING) {
throw new IllegalArgumentException("Item 0 (protected headers) is not a byte-string");
}
byte[] encodedProtectedHeaders = ((co.nstant.in.cbor.model.ByteString) items.get(
0)).getBytes();
byte[] payload = new byte[0];
if (items.get(2).getMajorType() == MajorType.SPECIAL) {
if (((co.nstant.in.cbor.model.Special) items.get(2)).getSpecialType()
!= SpecialType.SIMPLE_VALUE) {
throw new IllegalArgumentException(
"Item 2 (payload) is a special but not a simple value");
}
SimpleValue simple = (co.nstant.in.cbor.model.SimpleValue) items.get(2);
if (simple.getSimpleValueType() != SimpleValueType.NULL) {
throw new IllegalArgumentException(
"Item 2 (payload) is a simple but not the value null");
}
} else if (items.get(2).getMajorType() == MajorType.BYTE_STRING) {
payload = ((co.nstant.in.cbor.model.ByteString) items.get(2)).getBytes();
} else {
throw new IllegalArgumentException("Item 2 (payload) is not nil or byte-string");
}
if (items.get(3).getMajorType() != MajorType.BYTE_STRING) {
throw new IllegalArgumentException("Item 3 (signature) is not a byte-string");
}
byte[] coseSignature = ((co.nstant.in.cbor.model.ByteString) items.get(3)).getBytes();
byte[] derSignature = signatureCoseToDer(coseSignature);
int dataLen = payload.length;
int detachedContentLen = (detachedContent != null ? detachedContent.length : 0);
if (dataLen > 0 && detachedContentLen > 0) {
throw new IllegalArgumentException("data and detachedContent cannot both be non-empty");
}
DataItem protectedHeaders = cborDecode(encodedProtectedHeaders);
long alg = cborMapExtractNumber((Map) protectedHeaders, COSE_LABEL_ALG);
String signature;
if (alg == COSE_ALG_ECDSA_256) {
signature = "SHA256withECDSA";
} else if (alg == COSE_ALG_ECDSA_384) {
signature = "SHA384withECDSA";
} else if (alg == COSE_ALG_ECDSA_512) {
signature = "SHA512withECDSA";
} else {
throw new IllegalArgumentException("Unsupported COSE alg " + alg);
}
byte[] toBeSigned = Util.coseBuildToBeSigned(encodedProtectedHeaders, payload,
detachedContent);
try {
// Use BouncyCastle provider for verification since it supports a lot more curves than
// the default provider, including the brainpool curves
//
Signature verifier = Signature.getInstance(signature,
new org.bouncycastle.jce.provider.BouncyCastleProvider());
verifier.initVerify(publicKey);
verifier.update(toBeSigned);
return verifier.verify(derSignature);
} catch (SignatureException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException("Error verifying signature", e);
}
}
private static @NonNull
byte[] coseBuildToBeMACed(@NonNull byte[] encodedProtectedHeaders,
@NonNull byte[] payload,
@NonNull byte[] detachedContent) {
CborBuilder macStructure = new CborBuilder();
ArrayBuilder<CborBuilder> array = macStructure.addArray();
array.add("MAC0");
array.add(encodedProtectedHeaders);
// We currently don't support Externally Supplied Data (RFC 8152 section 4.3)
// so external_aad is the empty bstr
byte[] emptyExternalAad = new byte[0];
array.add(emptyExternalAad);
// Next field is the payload, independently of how it's transported (RFC
// 8152 section 4.4). Since our API specifies only one of |data| and
// |detachedContent| can be non-empty, it's simply just the non-empty one.
if (payload != null && payload.length > 0) {
array.add(payload);
} else {
array.add(detachedContent);
}
return cborEncode(macStructure.build().get(0));
}
static @NonNull
DataItem coseMac0(@NonNull SecretKey key,
@Nullable byte[] data,
@Nullable byte[] detachedContent) {
int dataLen = (data != null ? data.length : 0);
int detachedContentLen = (detachedContent != null ? detachedContent.length : 0);
if (dataLen > 0 && detachedContentLen > 0) {
throw new IllegalArgumentException("data and detachedContent cannot both be non-empty");
}
CborBuilder protectedHeaders = new CborBuilder();
MapBuilder<CborBuilder> protectedHeadersMap = protectedHeaders.addMap();
protectedHeadersMap.put(COSE_LABEL_ALG, COSE_ALG_HMAC_256_256);
byte[] protectedHeadersBytes = cborEncode(protectedHeaders.build().get(0));
byte[] toBeMACed = coseBuildToBeMACed(protectedHeadersBytes, data, detachedContent);
byte[] mac;
try {
Mac m = Mac.getInstance("HmacSHA256");
m.init(key);
m.update(toBeMACed);
mac = m.doFinal();
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new IllegalStateException("Unexpected error", e);
}
CborBuilder builder = new CborBuilder();
ArrayBuilder<CborBuilder> array = builder.addArray();
array.add(protectedHeadersBytes);
/* MapBuilder<ArrayBuilder<CborBuilder>> unprotectedHeaders = */
array.addMap();
if (data == null || data.length == 0) {
array.add(new SimpleValue(SimpleValueType.NULL));
} else {
array.add(data);
}
array.add(mac);
return builder.build().get(0);
}
static @NonNull
byte[] coseMac0GetTag(@NonNull DataItem coseMac0) {
List<DataItem> items = castTo(Array.class, coseMac0).getDataItems();
if (items.size() < 4) {
throw new IllegalArgumentException("coseMac0 have less than 4 elements");
}
DataItem tagItem = items.get(3);
return castTo(ByteString.class, tagItem).getBytes();
}
/**
* Brute-force but good enough since users will only pass relatively small amounts of data.
*/
static boolean hasSubByteArray(@NonNull byte[] haystack, @NonNull byte[] needle) {
int n = 0;
while (needle.length + n <= haystack.length) {
boolean found = true;
for (int m = 0; m < needle.length; m++) {
if (needle[m] != haystack[n + m]) {
found = false;
break;
}
}
if (found) {
return true;
}
n++;
}
return false;
}
static @NonNull
byte[] stripLeadingZeroes(@NonNull byte[] value) {
int n = 0;
while (n < value.length && value[n] == 0) {
n++;
}
int newLen = value.length - n;
byte[] ret = new byte[newLen];
int m = 0;
while (n < value.length) {
ret[m++] = value[n++];
}
return ret;
}
/**
* Returns #6.24(bstr) of the given already encoded CBOR
*/
static @NonNull
DataItem cborBuildTaggedByteString(@NonNull byte[] encodedCbor) {
DataItem item = new ByteString(encodedCbor);
item.setTag(CBOR_SEMANTIC_TAG_ENCODED_CBOR);
return item;
}
/**
* For a #6.24(bstr), extracts the bytes.
*/
static @NonNull
byte[] cborExtractTaggedCbor(@NonNull byte[] encodedTaggedBytestring) {
DataItem item = cborDecode(encodedTaggedBytestring);
ByteString itemByteString = castTo(ByteString.class, item);
if (!item.hasTag() || item.getTag().getValue() != CBOR_SEMANTIC_TAG_ENCODED_CBOR) {
throw new IllegalArgumentException("ByteString is not tagged with tag 24");
}
return itemByteString.getBytes();
}
/**
* For a #6.24(bstr), extracts the bytes and decodes it and returns
* the decoded CBOR as a DataItem.
*/
static @NonNull
DataItem cborExtractTaggedAndEncodedCbor(@NonNull DataItem item) {
ByteString itemByteString = castTo(ByteString.class, item);
if (!item.hasTag() || item.getTag().getValue() != CBOR_SEMANTIC_TAG_ENCODED_CBOR) {
throw new IllegalArgumentException("ByteString is not tagged with tag 24");
}
byte[] encodedCbor = itemByteString.getBytes();
DataItem embeddedItem = cborDecode(encodedCbor);
return embeddedItem;
}
/**
* Returns the empty byte-array if no data is included in the structure.
*/
static @NonNull
byte[] coseSign1GetData(@NonNull DataItem coseSign1) {
if (coseSign1.getMajorType() != MajorType.ARRAY) {
throw new IllegalArgumentException("Data item is not an array");
}
List<DataItem> items = castTo(co.nstant.in.cbor.model.Array.class, coseSign1).getDataItems();
if (items.size() < 4) {
throw new IllegalArgumentException("Expected at least four items in COSE_Sign1 array");
}
byte[] payload = new byte[0];
if (items.get(2).getMajorType() == MajorType.SPECIAL) {
if (((co.nstant.in.cbor.model.Special) items.get(2)).getSpecialType()
!= SpecialType.SIMPLE_VALUE) {
throw new IllegalArgumentException(
"Item 2 (payload) is a special but not a simple value");
}
SimpleValue simple = castTo(co.nstant.in.cbor.model.SimpleValue.class, items.get(2));
if (simple.getSimpleValueType() != SimpleValueType.NULL) {
throw new IllegalArgumentException(
"Item 2 (payload) is a simple but not the value null");
}
} else if (items.get(2).getMajorType() == MajorType.BYTE_STRING) {
payload = castTo(co.nstant.in.cbor.model.ByteString.class, items.get(2)).getBytes();
} else {
throw new IllegalArgumentException("Item 2 (payload) is not nil or byte-string");
}
return payload;
}
/**
* Returns the empty collection if no x5chain is included in the structure.
*
* Throws exception if the given bytes aren't valid COSE_Sign1.
*/
static @NonNull
List<X509Certificate> coseSign1GetX5Chain(
@NonNull DataItem coseSign1) {
ArrayList<X509Certificate> ret = new ArrayList<>();
if (coseSign1.getMajorType() != MajorType.ARRAY) {
throw new IllegalArgumentException("Data item is not an array");
}
List<DataItem> items = castTo(co.nstant.in.cbor.model.Array.class, coseSign1).getDataItems();
if (items.size() < 4) {
throw new IllegalArgumentException("Expected at least four items in COSE_Sign1 array");
}
if (items.get(1).getMajorType() != MajorType.MAP) {
throw new IllegalArgumentException("Item 1 (unprotected headers) is not a map");
}
co.nstant.in.cbor.model.Map map = (co.nstant.in.cbor.model.Map) items.get(1);
DataItem x5chainItem = map.get(new UnsignedInteger(COSE_LABEL_X5CHAIN));
if (x5chainItem != null) {
try {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
if (x5chainItem instanceof ByteString) {
ByteArrayInputStream certBais = new ByteArrayInputStream(
castTo(ByteString.class, x5chainItem).getBytes());
ret.add((X509Certificate) factory.generateCertificate(certBais));
} else if (x5chainItem instanceof Array) {
for (DataItem certItem : castTo(Array.class, x5chainItem).getDataItems()) {
ByteArrayInputStream certBais = new ByteArrayInputStream(
castTo(ByteString.class, certItem).getBytes());
ret.add((X509Certificate) factory.generateCertificate(certBais));
}
} else {
throw new IllegalArgumentException("Unexpected type for x5chain value");
}
} catch (CertificateException e) {
throw new IllegalArgumentException("Unexpected error", e);
}
}
return ret;
}
static @NonNull
DataItem cborBuildCoseKey(@NonNull PublicKey key) {
ECPublicKey ecKey = (ECPublicKey) key;
ECPoint w = ecKey.getW();
// X and Y are always positive so for interop we remove any leading zeroes
// inserted by the BigInteger encoder.
byte[] x = stripLeadingZeroes(w.getAffineX().toByteArray());
byte[] y = stripLeadingZeroes(w.getAffineY().toByteArray());
DataItem item = new CborBuilder()
.addMap()
.put(COSE_KEY_KTY, COSE_KEY_TYPE_EC2)
.put(COSE_KEY_EC2_CRV, COSE_KEY_EC2_CRV_P256)
.put(COSE_KEY_EC2_X, x)
.put(COSE_KEY_EC2_Y, y)
.end()
.build().get(0);
return item;
}
static boolean cborMapHasKey(@NonNull DataItem map, @NonNull String key) {
DataItem item = castTo(Map.class, map).get(new UnicodeString(key));
return item != null;
}
static boolean cborMapHasKey(@NonNull DataItem map, long key) {
DataItem keyDataItem = key >= 0 ? new UnsignedInteger(key) : new NegativeInteger(key);
DataItem item = castTo(Map.class, map).get(keyDataItem);
return item != null;
}
static long cborMapExtractNumber(@NonNull DataItem map, long key) {