1/* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.wifi.hotspot2; 18 19import android.util.Log; 20 21import java.io.File; 22import java.io.FileInputStream; 23import java.io.IOException; 24import java.security.cert.Certificate; 25import java.security.cert.CertificateException; 26import java.security.cert.CertificateFactory; 27import java.security.cert.X509Certificate; 28import java.util.HashSet; 29import java.util.Set; 30 31/** 32 * Provides static method to build certificate set from cert files 33 */ 34public class WfaCertBuilder { 35 36 private static final String TAG = "WfaCertBuilder"; 37 38 /** 39 * Returns a set of X509 Certificates from a set of WFA cert files 40 * @param directory the location where the cert files are stored 41 * @return Set<X509Certificate> certificates obtained from the files 42 */ 43 public static Set<X509Certificate> loadCertsFromDisk(String directory) { 44 Set<X509Certificate> certs = new HashSet<>(); 45 try { 46 File certDir = new File(directory); 47 File[] certFiles = certDir.listFiles(); 48 if (certFiles == null || certFiles.length <= 0) { 49 return certs; 50 } 51 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 52 for (File certFile : certFiles) { 53 FileInputStream fis = new FileInputStream(certFile); 54 Certificate cert = certFactory.generateCertificate(fis); 55 if (cert instanceof X509Certificate) { 56 certs.add((X509Certificate) cert); 57 } 58 fis.close(); 59 } 60 } catch (CertificateException | IOException | SecurityException e) { 61 Log.e(TAG, "Unable to read cert " + e.getMessage()); 62 } 63 return certs; 64 } 65} 66