1 // Copyright 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.net; 6 7 import static org.chromium.net.test.util.CertTestUtil.CERTS_DIRECTORY; 8 9 import androidx.test.filters.MediumTest; 10 11 import org.junit.Assert; 12 import org.junit.Before; 13 import org.junit.Test; 14 import org.junit.runner.RunWith; 15 16 import org.chromium.base.test.BaseJUnit4ClassRunner; 17 import org.chromium.net.test.util.CertTestUtil; 18 19 import java.io.IOException; 20 import java.io.RandomAccessFile; 21 import java.security.GeneralSecurityException; 22 import java.util.Arrays; 23 24 /** 25 * Tests for org.chromium.net.X509Util. 26 */ 27 @RunWith(BaseJUnit4ClassRunner.class) 28 public class X509UtilTest { 29 private static final String BAD_EKU_TEST_ROOT = "eku-test-root.pem"; 30 private static final String CRITICAL_CODE_SIGNING_EE = "crit-codeSigning-chain.pem"; 31 private static final String NON_CRITICAL_CODE_SIGNING_EE = "non-crit-codeSigning-chain.pem"; 32 private static final String WEB_CLIENT_AUTH_EE = "invalid_key_usage_cert.der"; 33 private static final String OK_CERT = "ok_cert.pem"; 34 private static final String GOOD_ROOT_CA = "root_ca_cert.pem"; 35 36 readFileBytes(String pathname)37 private static byte[] readFileBytes(String pathname) throws IOException { 38 RandomAccessFile file = new RandomAccessFile(pathname, "r"); 39 byte[] bytes = new byte[(int) file.length()]; 40 int bytesRead = file.read(bytes); 41 if (bytesRead != bytes.length) { 42 return Arrays.copyOfRange(bytes, 0, bytesRead); 43 } 44 return bytes; 45 } 46 47 @Before setUp()48 public void setUp() { 49 X509Util.setDisableNativeCodeForTest(true); 50 } 51 52 @Test 53 @MediumTest testEkusVerified()54 public void testEkusVerified() throws GeneralSecurityException, IOException { 55 X509Util.addTestRootCertificate(CertTestUtil.pemToDer(CERTS_DIRECTORY + BAD_EKU_TEST_ROOT)); 56 X509Util.addTestRootCertificate(CertTestUtil.pemToDer(CERTS_DIRECTORY + GOOD_ROOT_CA)); 57 58 Assert.assertFalse(X509Util.verifyKeyUsage(X509Util.createCertificateFromBytes( 59 CertTestUtil.pemToDer(CERTS_DIRECTORY + CRITICAL_CODE_SIGNING_EE)))); 60 61 Assert.assertFalse(X509Util.verifyKeyUsage(X509Util.createCertificateFromBytes( 62 CertTestUtil.pemToDer(CERTS_DIRECTORY + NON_CRITICAL_CODE_SIGNING_EE)))); 63 64 Assert.assertFalse(X509Util.verifyKeyUsage(X509Util.createCertificateFromBytes( 65 readFileBytes(CERTS_DIRECTORY + WEB_CLIENT_AUTH_EE)))); 66 67 Assert.assertTrue(X509Util.verifyKeyUsage(X509Util.createCertificateFromBytes( 68 CertTestUtil.pemToDer(CERTS_DIRECTORY + OK_CERT)))); 69 70 try { 71 X509Util.clearTestRootCertificates(); 72 } catch (Exception e) { 73 Assert.fail("Could not clear test root certificates: " + e.toString()); 74 } 75 } 76 } 77 78