1 // Copyright 2015 The Chromium Authors 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.test.util; 6 7 import android.util.Base64; 8 9 import org.chromium.base.test.util.UrlUtils; 10 11 import java.io.BufferedReader; 12 import java.io.FileReader; 13 import java.io.IOException; 14 import java.security.MessageDigest; 15 import java.security.NoSuchAlgorithmException; 16 import java.security.cert.Certificate; 17 18 /** 19 * Certificate related utility methods. 20 */ 21 public class CertTestUtil { 22 /** 23 * The location of the directory that contains certificates for testing. 24 */ 25 public static final String CERTS_DIRECTORY = 26 UrlUtils.getIsolatedTestFilePath("net/data/ssl/certificates/"); 27 28 private static final String BEGIN_MARKER = "-----BEGIN CERTIFICATE-----"; 29 private static final String END_MARKER = "-----END CERTIFICATE-----"; 30 CertTestUtil()31 private CertTestUtil() {} 32 33 /** 34 * Converts a PEM formatted cert in a given file to the binary DER format. 35 * 36 * @param pemPathname the location of the certificate to convert. 37 * @return array of bytes that represent the certificate in DER format. 38 * @throws IOException if the file cannot be read. 39 */ pemToDer(String pemPathname)40 public static byte[] pemToDer(String pemPathname) throws IOException { 41 BufferedReader reader = new BufferedReader(new FileReader(pemPathname)); 42 StringBuilder builder = new StringBuilder(); 43 44 // Skip past leading junk lines, if any. 45 String line = reader.readLine(); 46 while (line != null && !line.contains(BEGIN_MARKER)) line = reader.readLine(); 47 48 // Then skip the BEGIN_MARKER itself, if present. 49 while (line != null && line.contains(BEGIN_MARKER)) line = reader.readLine(); 50 51 // Now gather the data lines into the builder. 52 while (line != null && !line.contains(END_MARKER)) { 53 builder.append(line.trim()); 54 line = reader.readLine(); 55 } 56 57 reader.close(); 58 return Base64.decode(builder.toString(), Base64.DEFAULT); 59 } 60 61 /** 62 * Returns SHA256 hash of the public key of a given certificate. 63 * 64 * @param cert the cert that should be used to retrieve the public key from. 65 * @return SHA256 hash of the public key. 66 */ getPublicKeySha256(Certificate cert)67 public static byte[] getPublicKeySha256(Certificate cert) { 68 try { 69 byte[] publicKey = cert.getPublicKey().getEncoded(); 70 MessageDigest digest = MessageDigest.getInstance("SHA-256"); 71 return digest.digest(publicKey); 72 } catch (NoSuchAlgorithmException ex) { 73 // This exception should never happen since SHA-256 is known algorithm 74 throw new RuntimeException(ex); 75 } 76 } 77 } 78