summaryrefslogtreecommitdiff
path: root/tests/tests/keystore/src/android/keystore/cts/util/TestUtils.java
blob: a30074c5ab7f712b1806fe2ff3e47e45716e403d (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
/*
 * Copyright (C) 2015 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 android.keystore.cts.util;

import static android.security.keystore.KeyProperties.DIGEST_NONE;
import static android.security.keystore.KeyProperties.DIGEST_SHA256;
import static android.security.keystore.KeyProperties.DIGEST_SHA512;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

import android.content.Context;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.SystemProperties;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyInfo;
import android.security.keystore.KeyProperties;
import android.security.keystore.KeyProtection;
import android.test.MoreAsserts;
import android.text.TextUtils;

import androidx.test.platform.app.InstrumentationRegistry;

import com.android.internal.util.HexDump;

import org.junit.Assert;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.Key;
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.SecureRandom;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.ECParameterSpec;
import java.security.spec.EllipticCurve;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;

public class TestUtils {

    public static final String EXPECTED_CRYPTO_OP_PROVIDER_NAME = "AndroidKeyStoreBCWorkaround";
    public static final String EXPECTED_PROVIDER_NAME = "AndroidKeyStore";

    public static final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;

    private TestUtils() {}

    private static Context getContext() {
        return InstrumentationRegistry.getInstrumentation().getTargetContext();
    }

    public static File getFilesDir() {
        Context context = getContext();
        final String packageName = context.getPackageName();
        return new File(context.getFilesDir(), packageName);
    }

    static public void assumeStrongBox() {
        PackageManager packageManager =
                InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager();
        assumeTrue("Can only test if we have StrongBox",
                packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE));
    }

    /**
     * Returns 0 if not implemented. Otherwise returns the feature version.
     */
    public static int getFeatureVersionKeystore(Context appContext, boolean useStrongbox) {
        if (useStrongbox) {
            return getFeatureVersionKeystoreStrongBox(appContext);
        }
        return getFeatureVersionKeystore(appContext);
    }

    /**
     * This function returns the valid digest algorithms supported for a Strongbox or default
     * KeyMint implementation. The isStrongbox parameter specifies the underlying KeyMint
     * implementation. If true, it indicates Strongbox KeyMint, otherwise TEE/Software KeyMint
     * is assumed.
     */
    public static @KeyProperties.DigestEnum String[] getDigestsForKeyMintImplementation(
            boolean isStrongbox) {
        if (isStrongbox) {
            return new String[]{DIGEST_NONE, DIGEST_SHA256};
        }
        return new String[]{DIGEST_NONE, DIGEST_SHA256, DIGEST_SHA512};
    }

    // Returns 0 if not implemented. Otherwise returns the feature version.
    //
    public static int getFeatureVersionKeystore(Context appContext) {
        PackageManager pm = appContext.getPackageManager();

        int featureVersionFromPm = 0;
        if (pm.hasSystemFeature(PackageManager.FEATURE_HARDWARE_KEYSTORE)) {
            FeatureInfo info = null;
            FeatureInfo[] infos = pm.getSystemAvailableFeatures();
            for (int n = 0; n < infos.length; n++) {
                FeatureInfo i = infos[n];
                if (i.name.equals(PackageManager.FEATURE_HARDWARE_KEYSTORE)) {
                    info = i;
                    break;
                }
            }
            if (info != null) {
                featureVersionFromPm = info.version;
            }
        }

        return featureVersionFromPm;
    }

    // Returns 0 if not implemented. Otherwise returns the feature version.
    //
    public static int getFeatureVersionKeystoreStrongBox(Context appContext) {
        PackageManager pm = appContext.getPackageManager();

        int featureVersionFromPm = 0;
        if (pm.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)) {
            FeatureInfo info = null;
            FeatureInfo[] infos = pm.getSystemAvailableFeatures();
            for (int n = 0; n < infos.length; n++) {
                FeatureInfo i = infos[n];
                if (i.name.equals(PackageManager.FEATURE_STRONGBOX_KEYSTORE)) {
                    info = i;
                    break;
                }
            }
            if (info != null) {
                featureVersionFromPm = info.version;
            }
        }

        return featureVersionFromPm;
    }

    /**
     * Asserts that the given key is supported by KeyMint after a given (inclusive) version. The
     * assertion checks that:
     * 1. The current keystore feature version is less than <code>version</code> and
     *    <code>keyInfo</code> is implemented in software.
     *    OR
     * 2. The current keystore feature version is greater than or equal to <code>version</code>,
     *    and <code>keyInfo</code> is implemented by KeyMint.
     */
    public static void assertImplementedByKeyMintAfter(KeyInfo keyInfo, int version)
            throws Exception {
        // ECDSA keys are always implemented in keymaster since v1, so we can use an ECDSA
        // to check whether the backend is implemented in HW or is SW-emulated.
        int ecdsaSecurityLevel;
        try {
            KeyPairGenerator kpg =
                    KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
            kpg.initialize(
                    new KeyGenParameterSpec.Builder("ecdsa-test-key",
                            KeyProperties.PURPOSE_SIGN).build());
            KeyPair kp = kpg.generateKeyPair();
            KeyFactory factory = KeyFactory.getInstance(kp.getPrivate().getAlgorithm(),
                    "AndroidKeyStore");
            ecdsaSecurityLevel = factory.getKeySpec(kp.getPrivate(),
                    KeyInfo.class).getSecurityLevel();
        } finally {
            KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
            keyStore.deleteEntry("ecdsa-test-key");
        }

        Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
        if (getFeatureVersionKeystore(context) >= version) {
            Assert.assertEquals(keyInfo.getSecurityLevel(), ecdsaSecurityLevel);
        } else {
            Assert.assertEquals(keyInfo.getSecurityLevel(),
                    KeyProperties.SECURITY_LEVEL_SOFTWARE);
        }
    }


    /**
     * Returns whether 3DES KeyStore tests should run on this device. 3DES support was added in
     * KeyMaster 4.0 and there should be no software fallback on earlier KeyMaster versions.
     */
    public static boolean supports3DES() {
        return "true".equals(SystemProperties.get("ro.hardware.keystore_desede"));
    }

    /**
     * Returns VSR API level.
     */
    public static int getVendorApiLevel() {
        int vendorApiLevel = SystemProperties.getInt("ro.vendor.api_level", -1);
        if (vendorApiLevel != -1) {
            return vendorApiLevel;
        }

        // Android S and older devices do not define ro.vendor.api_level
        vendorApiLevel = SystemProperties.getInt("ro.board.api_level", -1);
        if (vendorApiLevel == -1) {
            vendorApiLevel = SystemProperties.getInt("ro.board.first_api_level", -1);
        }

        int productApiLevel = SystemProperties.getInt("ro.product.first_api_level", -1);
        if (productApiLevel == -1) {
            productApiLevel = Build.VERSION.SDK_INT;
        }

        // VSR API level is the minimum of vendorApiLevel and productApiLevel.
        if (vendorApiLevel == -1 || vendorApiLevel > productApiLevel) {
            return productApiLevel;
        }
        return vendorApiLevel;
    }

    /**
     * Returns whether the device has a StrongBox backed KeyStore.
     */
    public static boolean hasStrongBox(Context context) {
        return context.getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE);
    }

    /**
     * Asserts the the key algorithm and algorithm-specific parameters of the two keys in the
     * provided pair match.
     */
    public static void assertKeyPairSelfConsistent(KeyPair keyPair) {
        assertKeyPairSelfConsistent(keyPair.getPublic(), keyPair.getPrivate());
    }

    /**
     * Asserts the the key algorithm and public algorithm-specific parameters of the two provided
     * keys match.
     */
    public static void assertKeyPairSelfConsistent(PublicKey publicKey, PrivateKey privateKey) {
        assertNotNull(publicKey);
        assertNotNull(privateKey);
        assertEquals(publicKey.getAlgorithm(), privateKey.getAlgorithm());
        String keyAlgorithm = publicKey.getAlgorithm();
        if ("EC".equalsIgnoreCase(keyAlgorithm)) {
            assertTrue("EC public key must be instanceof ECKey: "
                    + publicKey.getClass().getName(),
                    publicKey instanceof ECKey);
            assertTrue("EC private key must be instanceof ECKey: "
                    + privateKey.getClass().getName(),
                    privateKey instanceof ECKey);
            assertECParameterSpecEqualsIgnoreSeedIfNotPresent(
                    "Private key must have the same EC parameters as public key",
                    ((ECKey) publicKey).getParams(), ((ECKey) privateKey).getParams());
        } else if ("RSA".equalsIgnoreCase(keyAlgorithm)) {
            assertTrue("RSA public key must be instance of RSAKey: "
                    + publicKey.getClass().getName(),
                    publicKey instanceof RSAKey);
            assertTrue("RSA private key must be instance of RSAKey: "
                    + privateKey.getClass().getName(),
                    privateKey instanceof RSAKey);
            assertEquals("Private and public key must have the same RSA modulus",
                    ((RSAKey) publicKey).getModulus(), ((RSAKey) privateKey).getModulus());
        } else if ("XDH".equalsIgnoreCase(keyAlgorithm)) {
            // TODO This block should verify that public and private keys are instance of
            //  java.security.interfaces.XECKey, And below code should be uncommented once
            //  com.android.org.conscrypt.OpenSSLX25519PublicKey implements XECKey (b/214203951)
            /*assertTrue("XDH public key must be instance of XECKey: "
                            + publicKey.getClass().getName(),
                    publicKey instanceof XECKey);
            assertTrue("XDH private key must be instance of XECKey: "
                            + privateKey.getClass().getName(),
                    privateKey instanceof XECKey);*/
            assertFalse("XDH public key must not be instance of RSAKey: "
                            + publicKey.getClass().getName(),
                    publicKey instanceof RSAKey);
            assertFalse("XDH private key must not be instance of RSAKey: "
                            + privateKey.getClass().getName(),
                    privateKey instanceof RSAKey);
            assertFalse("XDH public key must not be instanceof ECKey: "
                            + publicKey.getClass().getName(),
                    publicKey instanceof ECKey);
            assertFalse("XDH private key must not be instanceof ECKey: "
                            + privateKey.getClass().getName(),
                    privateKey instanceof ECKey);
        } else {
            fail("Unsuported key algorithm: " + keyAlgorithm);
        }
    }

    public static int getKeySizeBits(Key key) {
        if (key instanceof ECKey) {
            return ((ECKey) key).getParams().getCurve().getField().getFieldSize();
        } else if (key instanceof RSAKey) {
            return ((RSAKey) key).getModulus().bitLength();
        } else {
            throw new IllegalArgumentException("Unsupported key type: " + key.getClass());
        }
    }

    public static void assertKeySize(int expectedSizeBits, KeyPair keyPair) {
        assertEquals(expectedSizeBits, getKeySizeBits(keyPair.getPrivate()));
        assertEquals(expectedSizeBits, getKeySizeBits(keyPair.getPublic()));
    }

    /**
     * Asserts that the provided key pair is an Android Keystore key pair stored under the provided
     * alias.
     */
    public static void assertKeyStoreKeyPair(KeyStore keyStore, String alias, KeyPair keyPair) {
        assertKeyMaterialExportable(keyPair.getPublic());
        assertKeyMaterialNotExportable(keyPair.getPrivate());
        assertTransparentKey(keyPair.getPublic());
        assertOpaqueKey(keyPair.getPrivate());

        KeyStore.Entry entry;
        Certificate cert;
        try {
            entry = keyStore.getEntry(alias, null);
            cert = keyStore.getCertificate(alias);
        } catch (KeyStoreException | UnrecoverableEntryException | NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to load entry: " + alias, e);
        }
        assertNotNull(entry);

        assertTrue(entry instanceof KeyStore.PrivateKeyEntry);
        KeyStore.PrivateKeyEntry privEntry = (KeyStore.PrivateKeyEntry) entry;
        assertEquals(cert, privEntry.getCertificate());
        assertTrue("Certificate must be an X.509 certificate: " + cert.getClass(),
                cert instanceof X509Certificate);
        final X509Certificate x509Cert = (X509Certificate) cert;

        PrivateKey keystorePrivateKey = privEntry.getPrivateKey();
        PublicKey keystorePublicKey = cert.getPublicKey();
        assertEquals(keyPair.getPrivate(), keystorePrivateKey);
        assertTrue("Key1:\n" + HexDump.dumpHexString(keyPair.getPublic().getEncoded())
                + "\nKey2:\n" + HexDump.dumpHexString(keystorePublicKey.getEncoded()) + "\n",
                Arrays.equals(keyPair.getPublic().getEncoded(), keystorePublicKey.getEncoded()));


        assertEquals(
                "Public key used to sign certificate should have the same algorithm as in KeyPair",
                keystorePublicKey.getAlgorithm(), x509Cert.getPublicKey().getAlgorithm());

        Certificate[] chain = privEntry.getCertificateChain();
        if (chain.length == 0) {
            fail("Empty certificate chain");
            return;
        }
        assertEquals(cert, chain[0]);
    }


    private static void assertKeyMaterialExportable(Key key) {
        if (key instanceof PublicKey) {
            assertEquals("X.509", key.getFormat());
        } else if (key instanceof PrivateKey) {
            assertEquals("PKCS#8", key.getFormat());
        } else if (key instanceof SecretKey) {
            assertEquals("RAW", key.getFormat());
        } else {
            fail("Unsupported key type: " + key.getClass().getName());
        }
        byte[] encodedForm = key.getEncoded();
        assertNotNull(encodedForm);
        if (encodedForm.length == 0) {
            fail("Empty encoded form");
        }
    }

    private static void assertKeyMaterialNotExportable(Key key) {
        assertEquals(null, key.getFormat());
        assertEquals(null, key.getEncoded());
    }

    private static void assertOpaqueKey(Key key) {
        assertFalse(key.getClass().getName() + " is a transparent key", isTransparentKey(key));
    }

    private static void assertTransparentKey(Key key) {
        assertTrue(key.getClass().getName() + " is not a transparent key", isTransparentKey(key));
    }

    private static boolean isTransparentKey(Key key) {
        if (key instanceof PrivateKey) {
            return (key instanceof ECPrivateKey) || (key instanceof RSAPrivateKey);
        } else if (key instanceof PublicKey) {
            return (key instanceof ECPublicKey) || (key instanceof RSAPublicKey);
        } else if (key instanceof SecretKey) {
            return (key instanceof SecretKeySpec);
        } else {
            throw new IllegalArgumentException("Unsupported key type: " + key.getClass().getName());
        }
    }

    public static void assertECParameterSpecEqualsIgnoreSeedIfNotPresent(
            ECParameterSpec expected, ECParameterSpec actual) {
        assertECParameterSpecEqualsIgnoreSeedIfNotPresent(null, expected, actual);
    }

    public static void assertECParameterSpecEqualsIgnoreSeedIfNotPresent(String message,
            ECParameterSpec expected, ECParameterSpec actual) {
        EllipticCurve expectedCurve = expected.getCurve();
        EllipticCurve actualCurve = actual.getCurve();
        String msgPrefix = (message != null) ? message + ": " : "";
        assertEquals(msgPrefix + "curve field", expectedCurve.getField(), actualCurve.getField());
        assertEquals(msgPrefix + "curve A", expectedCurve.getA(), actualCurve.getA());
        assertEquals(msgPrefix + "curve B", expectedCurve.getB(), actualCurve.getB());
        assertEquals(msgPrefix + "order", expected.getOrder(), actual.getOrder());
        assertEquals(msgPrefix + "generator",
                expected.getGenerator(), actual.getGenerator());
        assertEquals(msgPrefix + "cofactor", expected.getCofactor(), actual.getCofactor());

        // If present, the seed must be the same
        byte[] expectedSeed = expectedCurve.getSeed();
        byte[] actualSeed = expectedCurve.getSeed();
        if ((expectedSeed != null) && (actualSeed != null)) {
            MoreAsserts.assertEquals(expectedSeed, actualSeed);
        }
    }

    public static KeyInfo getKeyInfo(Key key) throws InvalidKeySpecException, NoSuchAlgorithmException,
            NoSuchProviderException {
        if ((key instanceof PrivateKey) || (key instanceof PublicKey)) {
            return KeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore")
                    .getKeySpec(key, KeyInfo.class);
        } else if (key instanceof SecretKey) {
            return (KeyInfo) SecretKeyFactory.getInstance(key.getAlgorithm(), "AndroidKeyStore")
                    .getKeySpec((SecretKey) key, KeyInfo.class);
        } else {
            throw new IllegalArgumentException("Unexpected key type: " + key.getClass());
        }
    }

    public static <T> void assertContentsInAnyOrder(Iterable<T> actual, T... expected) {
        assertContentsInAnyOrder(null, actual, expected);
    }

    public static <T> void assertContentsInAnyOrder(String message, Iterable<T> actual, T... expected) {
        Map<T, Integer> actualFreq = getFrequencyTable(actual);
        Map<T, Integer> expectedFreq = getFrequencyTable(expected);
        if (actualFreq.equals(expectedFreq)) {
            return;
        }

        Map<T, Integer> extraneousFreq = new HashMap<T, Integer>();
        for (Map.Entry<T, Integer> actualEntry : actualFreq.entrySet()) {
            int actualCount = actualEntry.getValue();
            Integer expectedCount = expectedFreq.get(actualEntry.getKey());
            int diff = actualCount - ((expectedCount != null) ? expectedCount : 0);
            if (diff > 0) {
                extraneousFreq.put(actualEntry.getKey(), diff);
            }
        }

        Map<T, Integer> missingFreq = new HashMap<T, Integer>();
        for (Map.Entry<T, Integer> expectedEntry : expectedFreq.entrySet()) {
            int expectedCount = expectedEntry.getValue();
            Integer actualCount = actualFreq.get(expectedEntry.getKey());
            int diff = expectedCount - ((actualCount != null) ? actualCount : 0);
            if (diff > 0) {
                missingFreq.put(expectedEntry.getKey(), diff);
            }
        }

        List<T> extraneous = frequencyTableToValues(extraneousFreq);
        List<T> missing = frequencyTableToValues(missingFreq);
        StringBuilder result = new StringBuilder();
        String delimiter = "";
        if (message != null) {
            result.append(message).append(".");
            delimiter = " ";
        }
        if (!missing.isEmpty()) {
            result.append(delimiter).append("missing: " + missing);
            delimiter = ", ";
        }
        if (!extraneous.isEmpty()) {
            result.append(delimiter).append("extraneous: " + extraneous);
        }
        fail(result.toString());
    }

    private static <T> Map<T, Integer> getFrequencyTable(Iterable<T> values) {
        Map<T, Integer> result = new HashMap<T, Integer>();
        for (T value : values) {
            Integer count = result.get(value);
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            result.put(value, count);
        }
        return result;
    }

    private static <T> Map<T, Integer> getFrequencyTable(T... values) {
        Map<T, Integer> result = new HashMap<T, Integer>();
        for (T value : values) {
            Integer count = result.get(value);
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            result.put(value, count);
        }
        return result;
    }

    @SuppressWarnings("rawtypes")
    private static <T> List<T> frequencyTableToValues(Map<T, Integer> table) {
        if (table.isEmpty()) {
            return Collections.emptyList();
        }

        List<T> result = new ArrayList<T>();
        boolean comparableValues = true;
        for (Map.Entry<T, Integer> entry : table.entrySet()) {
            T value = entry.getKey();
            if (!(value instanceof Comparable)) {
                comparableValues = false;
            }
            int frequency = entry.getValue();
            for (int i = 0; i < frequency; i++) {
                result.add(value);
            }
        }

        if (comparableValues) {
            sortAssumingComparable(result);
        }
        return result;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private static void sortAssumingComparable(List<?> values) {
        Collections.sort((List<Comparable>)values);
    }

    public static String[] toLowerCase(String... values) {
        if (values == null) {
            return null;
        }
        String[] result = new String[values.length];
        for (int i = 0; i < values.length; i++) {
            String value = values[i];
            result[i] = (value != null) ? value.toLowerCase() : null;
        }
        return result;
    }

    public static PrivateKey getRawResPrivateKey(Context context, int resId) throws Exception {
        byte[] pkcs8EncodedForm;
        try (InputStream in = context.getResources().openRawResource(resId)) {
            pkcs8EncodedForm = drain(in);
        }
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(pkcs8EncodedForm);

        String[] algorithms = new String[] {"EC", "RSA", "XDH"};
        for (String algo : algorithms) {
            try {
                return KeyFactory.getInstance(algo).generatePrivate(privateKeySpec);
            } catch (InvalidKeySpecException e) {
            }
        }
        throw new InvalidKeySpecException(
                "The key should be one of " + Arrays.toString(algorithms));
    }

    public static X509Certificate getRawResX509Certificate(Context context, int resId) throws Exception {
        try (InputStream in = context.getResources().openRawResource(resId)) {
            return (X509Certificate) CertificateFactory.getInstance("X.509")
                    .generateCertificate(in);
        }
    }

    public static KeyPair importIntoAndroidKeyStore(
            String alias,
            PrivateKey privateKey,
            Certificate certificate,
            KeyProtection keyProtection) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        keyStore.setEntry(alias,
                new KeyStore.PrivateKeyEntry(privateKey, new Certificate[] {certificate}),
                keyProtection);
        return new KeyPair(
                keyStore.getCertificate(alias).getPublicKey(),
                (PrivateKey) keyStore.getKey(alias, null));
    }

    public static ImportedKey importIntoAndroidKeyStore(
            String alias,
            SecretKey key,
            KeyProtection keyProtection) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        keyStore.setEntry(alias,
                new KeyStore.SecretKeyEntry(key),
                keyProtection);
        return new ImportedKey(alias, key, (SecretKey) keyStore.getKey(alias, null));
    }

    public static ImportedKey importIntoAndroidKeyStore(
            String alias, Context context, int privateResId, int certResId, KeyProtection params)
                    throws Exception {
        Certificate originalCert = TestUtils.getRawResX509Certificate(context, certResId);
        PublicKey originalPublicKey = originalCert.getPublicKey();
        PrivateKey originalPrivateKey = TestUtils.getRawResPrivateKey(context, privateResId);

        // Check that the domain parameters match between the private key and the public key. This
        // is to catch accidental errors where a test provides the wrong resource ID as one of the
        // parameters.
        if (!originalPublicKey.getAlgorithm().equalsIgnoreCase(originalPrivateKey.getAlgorithm())) {
            throw new IllegalArgumentException("Key algorithm mismatch."
                    + " Public: " + originalPublicKey.getAlgorithm()
                    + ", private: " + originalPrivateKey.getAlgorithm());
        }
        assertKeyPairSelfConsistent(originalPublicKey, originalPrivateKey);

        KeyPair keystoreBacked = TestUtils.importIntoAndroidKeyStore(
                alias, originalPrivateKey, originalCert,
                params);
        assertKeyPairSelfConsistent(keystoreBacked);
        assertKeyPairSelfConsistent(keystoreBacked.getPublic(), originalPrivateKey);
        return new ImportedKey(
                alias,
                new KeyPair(originalCert.getPublicKey(), originalPrivateKey),
                keystoreBacked);
    }

    /** Returns true if a key with the given alias exists. */
    public static boolean keyExists(String alias) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        try {
            return keyStore.getEntry(alias, null) != null;
        } catch (UnrecoverableKeyException e) {
            return false;
        }
    }

    public static byte[] drain(InputStream in) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[16 * 1024];
        int chunkSize;
        while ((chunkSize = in.read(buffer)) != -1) {
            result.write(buffer, 0, chunkSize);
        }
        return result.toByteArray();
    }

    public static KeyProtection.Builder buildUpon(KeyProtection params) {
        return buildUponInternal(params, null);
    }

    public static KeyProtection.Builder buildUpon(KeyProtection params, int newPurposes) {
        return buildUponInternal(params, newPurposes);
    }

    public static KeyProtection.Builder buildUpon(
            KeyProtection.Builder builder) {
        return buildUponInternal(builder.build(), null);
    }

    public static KeyProtection.Builder buildUpon(
            KeyProtection.Builder builder, int newPurposes) {
        return buildUponInternal(builder.build(), newPurposes);
    }

    private static KeyProtection.Builder buildUponInternal(
            KeyProtection spec, Integer newPurposes) {
        int purposes = (newPurposes == null) ? spec.getPurposes() : newPurposes;
        KeyProtection.Builder result = new KeyProtection.Builder(purposes);
        result.setBlockModes(spec.getBlockModes());
        if (spec.isDigestsSpecified()) {
            result.setDigests(spec.getDigests());
        }
        result.setEncryptionPaddings(spec.getEncryptionPaddings());
        result.setSignaturePaddings(spec.getSignaturePaddings());
        result.setKeyValidityStart(spec.getKeyValidityStart());
        result.setKeyValidityForOriginationEnd(spec.getKeyValidityForOriginationEnd());
        result.setKeyValidityForConsumptionEnd(spec.getKeyValidityForConsumptionEnd());
        result.setRandomizedEncryptionRequired(spec.isRandomizedEncryptionRequired());
        result.setUserAuthenticationRequired(spec.isUserAuthenticationRequired());
        result.setUserAuthenticationValidityDurationSeconds(
                spec.getUserAuthenticationValidityDurationSeconds());
        result.setBoundToSpecificSecureUserId(spec.getBoundToSpecificSecureUserId());
        return result;
    }

    public static KeyGenParameterSpec.Builder buildUpon(KeyGenParameterSpec spec) {
        return buildUponInternal(spec, null);
    }

    public static KeyGenParameterSpec.Builder buildUpon(KeyGenParameterSpec spec, int newPurposes) {
        return buildUponInternal(spec, newPurposes);
    }

    public static KeyGenParameterSpec.Builder buildUpon(
            KeyGenParameterSpec.Builder builder) {
        return buildUponInternal(builder.build(), null);
    }

    public static KeyGenParameterSpec.Builder buildUpon(
            KeyGenParameterSpec.Builder builder, int newPurposes) {
        return buildUponInternal(builder.build(), newPurposes);
    }

    private static KeyGenParameterSpec.Builder buildUponInternal(
            KeyGenParameterSpec spec, Integer newPurposes) {
        int purposes = (newPurposes == null) ? spec.getPurposes() : newPurposes;
        KeyGenParameterSpec.Builder result =
                new KeyGenParameterSpec.Builder(spec.getKeystoreAlias(), purposes);
        if (spec.getKeySize() >= 0) {
            result.setKeySize(spec.getKeySize());
        }
        if (spec.getAlgorithmParameterSpec() != null) {
            result.setAlgorithmParameterSpec(spec.getAlgorithmParameterSpec());
        }
        result.setCertificateNotBefore(spec.getCertificateNotBefore());
        result.setCertificateNotAfter(spec.getCertificateNotAfter());
        result.setCertificateSerialNumber(spec.getCertificateSerialNumber());
        result.setCertificateSubject(spec.getCertificateSubject());
        result.setBlockModes(spec.getBlockModes());
        if (spec.isDigestsSpecified()) {
            result.setDigests(spec.getDigests());
        }
        result.setEncryptionPaddings(spec.getEncryptionPaddings());
        result.setSignaturePaddings(spec.getSignaturePaddings());
        result.setKeyValidityStart(spec.getKeyValidityStart());
        result.setKeyValidityForOriginationEnd(spec.getKeyValidityForOriginationEnd());
        result.setKeyValidityForConsumptionEnd(spec.getKeyValidityForConsumptionEnd());
        result.setRandomizedEncryptionRequired(spec.isRandomizedEncryptionRequired());
        result.setUserAuthenticationRequired(spec.isUserAuthenticationRequired());
        result.setUserAuthenticationValidityDurationSeconds(
                spec.getUserAuthenticationValidityDurationSeconds());
        return result;
    }

    public static KeyPair getKeyPairForKeyAlgorithm(String keyAlgorithm, Iterable<KeyPair> keyPairs) {
        for (KeyPair keyPair : keyPairs) {
            if (keyAlgorithm.equalsIgnoreCase(keyPair.getPublic().getAlgorithm())) {
                return keyPair;
            }
        }
        throw new IllegalArgumentException("No KeyPair for key algorithm " + keyAlgorithm);
    }

    public static Key getKeyForKeyAlgorithm(String keyAlgorithm, Iterable<? extends Key> keys) {
        for (Key key : keys) {
            if (keyAlgorithm.equalsIgnoreCase(key.getAlgorithm())) {
                return key;
            }
        }
        throw new IllegalArgumentException("No Key for key algorithm " + keyAlgorithm);
    }

    public static byte[] generateLargeKatMsg(byte[] seed, int msgSizeBytes) throws Exception {
        byte[] result = new byte[msgSizeBytes];
        MessageDigest digest = MessageDigest.getInstance("SHA-512");
        int resultOffset = 0;
        int resultRemaining = msgSizeBytes;
        while (resultRemaining > 0) {
            seed = digest.digest(seed);
            int chunkSize = Math.min(seed.length, resultRemaining);
            System.arraycopy(seed, 0, result, resultOffset, chunkSize);
            resultOffset += chunkSize;
            resultRemaining -= chunkSize;
        }
        return result;
    }

    public static byte[] leftPadWithZeroBytes(byte[] array, int length) {
        if (array.length >= length) {
            return array;
        }
        byte[] result = new byte[length];
        System.arraycopy(array, 0, result, result.length - array.length, array.length);
        return result;
    }

    public static boolean contains(int[] array, int value) {
        for (int element : array) {
            if (element == value) {
                return true;
            }
        }
        return false;
    }

    public static boolean isHmacAlgorithm(String algorithm) {
        return algorithm.toUpperCase(Locale.US).startsWith("HMAC");
    }

    public static String getHmacAlgorithmDigest(String algorithm) {
        String algorithmUpperCase = algorithm.toUpperCase(Locale.US);
        if (!algorithmUpperCase.startsWith("HMAC")) {
            return null;
        }
        String result = algorithmUpperCase.substring("HMAC".length());
        if (result.startsWith("SHA")) {
            result = "SHA-" + result.substring("SHA".length());
        }
        return result;
    }

    public static String getKeyAlgorithm(String transformation) {
        try {
            return getCipherKeyAlgorithm(transformation);
        } catch (IllegalArgumentException e) {

        }
        try {
            return getSignatureAlgorithmKeyAlgorithm(transformation);
        } catch (IllegalArgumentException e) {

        }
        String transformationUpperCase = transformation.toUpperCase(Locale.US);
        if (transformationUpperCase.equals("EC")) {
            return KeyProperties.KEY_ALGORITHM_EC;
        }
        if (transformationUpperCase.equals("RSA")) {
            return KeyProperties.KEY_ALGORITHM_RSA;
        }
        if (transformationUpperCase.equals("DESEDE")) {
            return KeyProperties.KEY_ALGORITHM_3DES;
        }
        if (transformationUpperCase.equals("AES")) {
            return KeyProperties.KEY_ALGORITHM_AES;
        }
        if (transformationUpperCase.startsWith("HMAC")) {
            if (transformation.endsWith("SHA1")) {
                return KeyProperties.KEY_ALGORITHM_HMAC_SHA1;
            } else if (transformation.endsWith("SHA224")) {
                return KeyProperties.KEY_ALGORITHM_HMAC_SHA224;
            } else if (transformation.endsWith("SHA256")) {
                return KeyProperties.KEY_ALGORITHM_HMAC_SHA256;
            } else if (transformation.endsWith("SHA384")) {
                return KeyProperties.KEY_ALGORITHM_HMAC_SHA384;
            } else if (transformation.endsWith("SHA512")) {
                return KeyProperties.KEY_ALGORITHM_HMAC_SHA512;
            }
        }
        throw new IllegalArgumentException("Unsupported transformation: " + transformation);
    }

    public static String getCipherKeyAlgorithm(String transformation) {
        String transformationUpperCase = transformation.toUpperCase(Locale.US);
        if (transformationUpperCase.startsWith("AES/")) {
            return KeyProperties.KEY_ALGORITHM_AES;
        } else if (transformationUpperCase.startsWith("DESEDE/")) {
            return KeyProperties.KEY_ALGORITHM_3DES;
        } else if (transformationUpperCase.startsWith("RSA/")) {
            return KeyProperties.KEY_ALGORITHM_RSA;
        } else {
            throw new IllegalArgumentException("Unsupported transformation: " + transformation);
        }
    }

    public static boolean isCipherSymmetric(String transformation) {
        String transformationUpperCase = transformation.toUpperCase(Locale.US);
        if (transformationUpperCase.startsWith("AES/") || transformationUpperCase.startsWith(
                "DESEDE/")) {
            return true;
        } else if (transformationUpperCase.startsWith("RSA/")) {
            return false;
        } else {
            throw new IllegalArgumentException("YYZ: Unsupported transformation: " + transformation);
        }
    }

    public static String getCipherDigest(String transformation) {
        String transformationUpperCase = transformation.toUpperCase(Locale.US);
        if (transformationUpperCase.contains("/OAEP")) {
            if (transformationUpperCase.endsWith("/OAEPPADDING")) {
                return KeyProperties.DIGEST_SHA1;
            } else if (transformationUpperCase.endsWith(
                    "/OAEPWITHSHA-1ANDMGF1PADDING")) {
                return KeyProperties.DIGEST_SHA1;
            } else if (transformationUpperCase.endsWith(
                    "/OAEPWITHSHA-224ANDMGF1PADDING")) {
                return KeyProperties.DIGEST_SHA224;
            } else if (transformationUpperCase.endsWith(
                    "/OAEPWITHSHA-256ANDMGF1PADDING")) {
                return KeyProperties.DIGEST_SHA256;
            } else if (transformationUpperCase.endsWith(
                    "/OAEPWITHSHA-384ANDMGF1PADDING")) {
                return KeyProperties.DIGEST_SHA384;
            } else if (transformationUpperCase.endsWith(
                    "/OAEPWITHSHA-512ANDMGF1PADDING")) {
                return KeyProperties.DIGEST_SHA512;
            } else {
                throw new RuntimeException("Unsupported OAEP padding scheme: "
                        + transformation);
            }
        } else {
            return null;
        }
    }

    public static String getCipherEncryptionPadding(String transformation) {
        String transformationUpperCase = transformation.toUpperCase(Locale.US);
        if (transformationUpperCase.endsWith("/NOPADDING")) {
            return KeyProperties.ENCRYPTION_PADDING_NONE;
        } else if (transformationUpperCase.endsWith("/PKCS7PADDING")) {
            return KeyProperties.ENCRYPTION_PADDING_PKCS7;
        } else if (transformationUpperCase.endsWith("/PKCS1PADDING")) {
            return KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1;
        } else if (transformationUpperCase.split("/")[2].startsWith("OAEP")) {
            return KeyProperties.ENCRYPTION_PADDING_RSA_OAEP;
        } else {
            throw new IllegalArgumentException("Unsupported transformation: " + transformation);
        }
    }

    public static String getCipherBlockMode(String transformation) {
        return transformation.split("/")[1].toUpperCase(Locale.US);
    }

    public static String getSignatureAlgorithmDigest(String algorithm) {
        String algorithmUpperCase = algorithm.toUpperCase(Locale.US);
        int withIndex = algorithmUpperCase.indexOf("WITH");
        if (withIndex == -1) {
            throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
        }
        String digest = algorithmUpperCase.substring(0, withIndex);
        if (digest.startsWith("SHA")) {
            digest = "SHA-" + digest.substring("SHA".length());
        }
        return digest;
    }

    public static String getSignatureAlgorithmPadding(String algorithm) {
        String algorithmUpperCase = algorithm.toUpperCase(Locale.US);
        if (algorithmUpperCase.endsWith("WITHECDSA")) {
            return null;
        } else if (algorithmUpperCase.endsWith("WITHRSA")) {
            return KeyProperties.SIGNATURE_PADDING_RSA_PKCS1;
        } else if (algorithmUpperCase.endsWith("WITHRSA/PSS")) {
            return KeyProperties.SIGNATURE_PADDING_RSA_PSS;
        } else {
            throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
        }
    }

    public static String getSignatureAlgorithmKeyAlgorithm(String algorithm) {
        String algorithmUpperCase = algorithm.toUpperCase(Locale.US);
        if (algorithmUpperCase.endsWith("WITHECDSA")) {
            return KeyProperties.KEY_ALGORITHM_EC;
        } else if ((algorithmUpperCase.endsWith("WITHRSA"))
                || (algorithmUpperCase.endsWith("WITHRSA/PSS"))) {
            return KeyProperties.KEY_ALGORITHM_RSA;
        } else {
            throw new IllegalArgumentException("Unsupported algorithm: " + algorithm);
        }
    }

    public static boolean isKeyLongEnoughForSignatureAlgorithm(String algorithm, int keySizeBits) {
        String keyAlgorithm = getSignatureAlgorithmKeyAlgorithm(algorithm);
        if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
            // No length restrictions for ECDSA
            return true;
        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
            String digest = getSignatureAlgorithmDigest(algorithm);
            int digestOutputSizeBits = getDigestOutputSizeBits(digest);
            if (digestOutputSizeBits == -1) {
                // No digesting -- assume the key is long enough for the message
                return true;
            }
            String paddingScheme = getSignatureAlgorithmPadding(algorithm);
            int paddingOverheadBytes;
            if (KeyProperties.SIGNATURE_PADDING_RSA_PKCS1.equalsIgnoreCase(paddingScheme)) {
                paddingOverheadBytes = 30;
            } else if (KeyProperties.SIGNATURE_PADDING_RSA_PSS.equalsIgnoreCase(paddingScheme)) {
                int saltSizeBytes = (digestOutputSizeBits + 7) / 8;
                paddingOverheadBytes = saltSizeBytes + 1;
            } else {
                throw new IllegalArgumentException(
                        "Unsupported signature padding scheme: " + paddingScheme);
            }
            int minKeySizeBytes = paddingOverheadBytes + (digestOutputSizeBits + 7) / 8 + 1;
            int keySizeBytes = keySizeBits / 8;
            return keySizeBytes >= minKeySizeBytes;
        } else {
            throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm);
        }
    }

    public static boolean isKeyLongEnoughForSignatureAlgorithm(String algorithm, Key key) {
        return isKeyLongEnoughForSignatureAlgorithm(algorithm, getKeySizeBits(key));
    }

    public static int getMaxSupportedPlaintextInputSizeBytes(String transformation, int keySizeBits) {
        String encryptionPadding = getCipherEncryptionPadding(transformation);
        int modulusSizeBytes = (keySizeBits + 7) / 8;
        if (KeyProperties.ENCRYPTION_PADDING_NONE.equalsIgnoreCase(encryptionPadding)) {
            return modulusSizeBytes - 1;
        } else if (KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1.equalsIgnoreCase(
                encryptionPadding)) {
            return modulusSizeBytes - 11;
        } else if (KeyProperties.ENCRYPTION_PADDING_RSA_OAEP.equalsIgnoreCase(
                encryptionPadding)) {
            String digest = getCipherDigest(transformation);
            int digestOutputSizeBytes = (getDigestOutputSizeBits(digest) + 7) / 8;
            return modulusSizeBytes - 2 * digestOutputSizeBytes - 2;
        } else {
            throw new IllegalArgumentException(
                    "Unsupported encryption padding scheme: " + encryptionPadding);
        }

    }

    public static int getMaxSupportedPlaintextInputSizeBytes(String transformation, Key key) {
        String keyAlgorithm = getCipherKeyAlgorithm(transformation);
        if (KeyProperties.KEY_ALGORITHM_AES.equalsIgnoreCase(keyAlgorithm)
                || KeyProperties.KEY_ALGORITHM_3DES.equalsIgnoreCase(keyAlgorithm)) {
            return Integer.MAX_VALUE;
        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
            return getMaxSupportedPlaintextInputSizeBytes(transformation, getKeySizeBits(key));
        } else {
            throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm);
        }
    }

    public static int getDigestOutputSizeBits(String digest) {
        if (KeyProperties.DIGEST_NONE.equals(digest)) {
            return -1;
        } else if (KeyProperties.DIGEST_MD5.equals(digest)) {
            return 128;
        } else if (KeyProperties.DIGEST_SHA1.equals(digest)) {
            return 160;
        } else if (KeyProperties.DIGEST_SHA224.equals(digest)) {
            return 224;
        } else if (KeyProperties.DIGEST_SHA256.equals(digest)) {
            return 256;
        } else if (KeyProperties.DIGEST_SHA384.equals(digest)) {
            return 384;
        } else if (KeyProperties.DIGEST_SHA512.equals(digest)) {
            return 512;
        } else {
            throw new IllegalArgumentException("Unsupported digest: " + digest);
        }
    }

    public static byte[] concat(byte[] arr1, byte[] arr2) {
        return concat(arr1, 0, (arr1 != null) ? arr1.length : 0,
                arr2, 0, (arr2 != null) ? arr2.length : 0);
    }

    public static byte[] concat(byte[] arr1, int offset1, int len1,
            byte[] arr2, int offset2, int len2) {
        if (len1 == 0) {
            return subarray(arr2, offset2, len2);
        } else if (len2 == 0) {
            return subarray(arr1, offset1, len1);
        }
        byte[] result = new byte[len1 + len2];
        if (len1 > 0) {
            System.arraycopy(arr1, offset1, result, 0, len1);
        }
        if (len2 > 0) {
            System.arraycopy(arr2, offset2, result, len1, len2);
        }
        return result;
    }

    public static byte[] subarray(byte[] arr, int offset, int len) {
        if (len == 0) {
            return EmptyArray.BYTE;
        }
        if ((offset == 0) && (arr.length == len)) {
            return arr;
        }
        byte[] result = new byte[len];
        System.arraycopy(arr, offset, result, 0, len);
        return result;
    }

    public static KeyProtection getMinimalWorkingImportParametersForSigningingWith(
            String signatureAlgorithm) {
        String keyAlgorithm = getSignatureAlgorithmKeyAlgorithm(signatureAlgorithm);
        String digest = getSignatureAlgorithmDigest(signatureAlgorithm);
        if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
            return new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
                    .setDigests(digest)
                    .build();
        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
            String padding = getSignatureAlgorithmPadding(signatureAlgorithm);
            return new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
                    .setDigests(digest)
                    .setSignaturePaddings(padding)
                    .build();
        } else {
            throw new IllegalArgumentException(
                    "Unsupported signature algorithm: " + signatureAlgorithm);
        }
    }

    public static KeyProtection getMinimalWorkingImportParametersWithLimitedUsageForSigningingWith(
            String signatureAlgorithm, int maxUsageCount) {
        String keyAlgorithm = getSignatureAlgorithmKeyAlgorithm(signatureAlgorithm);
        String digest = getSignatureAlgorithmDigest(signatureAlgorithm);
        if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) {
            return new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
                    .setDigests(digest)
                    .setMaxUsageCount(maxUsageCount)
                    .build();
        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
            String padding = getSignatureAlgorithmPadding(signatureAlgorithm);
            return new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
                    .setDigests(digest)
                    .setSignaturePaddings(padding)
                    .setMaxUsageCount(maxUsageCount)
                    .build();
        } else {
            throw new IllegalArgumentException(
                    "Unsupported signature algorithm: " + signatureAlgorithm);
        }
    }

    public static KeyProtection getMinimalWorkingImportParametersForCipheringWith(
            String transformation, int purposes) {
        return getMinimalWorkingImportParametersForCipheringWith(transformation, purposes, false);
    }

    public static KeyProtection getMinimalWorkingImportParametersForCipheringWith(
            String transformation, int purposes, boolean ivProvidedWhenEncrypting) {
        return getMinimalWorkingImportParametersForCipheringWith(transformation, purposes,
            ivProvidedWhenEncrypting, false, false);
    }

    public static KeyProtection getMinimalWorkingImportParametersForCipheringWith(
            String transformation, int purposes, boolean ivProvidedWhenEncrypting,
            boolean isUnlockedDeviceRequired, boolean isUserAuthRequired) {
        String keyAlgorithm = TestUtils.getCipherKeyAlgorithm(transformation);
        if (KeyProperties.KEY_ALGORITHM_AES.equalsIgnoreCase(keyAlgorithm)
            || KeyProperties.KEY_ALGORITHM_3DES.equalsIgnoreCase(keyAlgorithm)) {
            String encryptionPadding = TestUtils.getCipherEncryptionPadding(transformation);
            String blockMode = TestUtils.getCipherBlockMode(transformation);
            boolean randomizedEncryptionRequired = true;
            if (KeyProperties.BLOCK_MODE_ECB.equalsIgnoreCase(blockMode)) {
                randomizedEncryptionRequired = false;
            } else if ((ivProvidedWhenEncrypting)
                    && ((purposes & KeyProperties.PURPOSE_ENCRYPT) != 0)) {
                randomizedEncryptionRequired = false;
            }
            return new KeyProtection.Builder(
                    purposes)
                    .setBlockModes(blockMode)
                    .setEncryptionPaddings(encryptionPadding)
                    .setRandomizedEncryptionRequired(randomizedEncryptionRequired)
                    .setUnlockedDeviceRequired(isUnlockedDeviceRequired)
                    .setUserAuthenticationRequired(isUserAuthRequired)
                    .setUserAuthenticationValidityDurationSeconds(3600)
                    .build();
        } else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) {
            String digest = TestUtils.getCipherDigest(transformation);
            String encryptionPadding = TestUtils.getCipherEncryptionPadding(transformation);
            boolean randomizedEncryptionRequired =
                    !KeyProperties.ENCRYPTION_PADDING_NONE.equalsIgnoreCase(encryptionPadding);
            // For algorithm transformation such as "RSA/ECB/OAEPWithSHA-224AndMGF1Padding",
            // Some providers uses same digest for OAEP main digest(SHA-224) and
            // MGF1 digest(SHA-224), and some providers uses main digest as (SHA-224) and
            // MGF1 digest as (SHA-1) hence adding both digest for MGF1 digest.
            String[] mgf1DigestList = null;
            if (digest != null) {
                mgf1DigestList = digest.equalsIgnoreCase("SHA-1")
                        ? new String[] {digest} : new String[] {digest, "SHA-1"};
            }
            KeyProtection.Builder keyProtectionBuilder = new KeyProtection.Builder(
                    purposes)
                    .setDigests((digest != null) ? new String[] {digest} : EmptyArray.STRING)
                    .setEncryptionPaddings(encryptionPadding)
                    .setRandomizedEncryptionRequired(randomizedEncryptionRequired)
                    .setUserAuthenticationRequired(isUserAuthRequired)
                    .setUserAuthenticationValidityDurationSeconds(3600)
                    .setUnlockedDeviceRequired(isUnlockedDeviceRequired);
            if (mgf1DigestList != null && android.security.Flags.mgf1DigestSetterV2()) {
                keyProtectionBuilder.setMgf1Digests(mgf1DigestList);
            }
            return keyProtectionBuilder.build();
        } else {
            throw new IllegalArgumentException("Unsupported key algorithm: " + keyAlgorithm);
        }
    }

    public static byte[] getBigIntegerMagnitudeBytes(BigInteger value) {
        return removeLeadingZeroByteIfPresent(value.toByteArray());
    }

    private static byte[] removeLeadingZeroByteIfPresent(byte[] value) {
        if ((value.length < 1) || (value[0] != 0)) {
            return value;
        }
        return TestUtils.subarray(value, 1, value.length - 1);
    }

    public static byte[] generateRandomMessage(int messageSize) {
        byte[] message = new byte[messageSize];
        new SecureRandom().nextBytes(message);
        return message;
    }

    public static boolean isAttestationSupported() {
        return Build.VERSION.DEVICE_INITIAL_SDK_INT >= Build.VERSION_CODES.O;
    }

    public static boolean isPropertyEmptyOrUnknown(String property) {
        return TextUtils.isEmpty(property) || property.equals(Build.UNKNOWN);
    }

    public static boolean hasSecureLockScreen(Context context) {
        PackageManager pm = context.getPackageManager();
        return (pm != null && pm.hasSystemFeature(PackageManager.FEATURE_SECURE_LOCK_SCREEN));
    }

    /**
     * Determines whether running build is GSI or not.
     * @return true if running build is GSI, false otherwise.
     */
    public static boolean isGsiImage() {
        final File initGsiRc = new File("/system/system_ext/etc/init/init.gsi.rc");
        return initGsiRc.exists();
    }

    /**
     * Ed25519 algorithm name is added in Android V. So CTS using this algorithm
     * name should check SDK_INT for Android V/preview.
     * @return true if current SDK_INT is 34 and PREVIEW_SDK_INT >= 1 or SDK_INT >= 35
     */
    public static boolean isEd25519AlgorithmExpectedToSupport() {
        return ((Build.VERSION.SDK_INT == 34 && Build.VERSION.PREVIEW_SDK_INT >= 1)
                || Build.VERSION.SDK_INT >= 35);
    }
}