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