1 /* 2 * Copyright (C) 2012 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 17 package org.bouncycastle.crypto.digests; 18 19 import java.security.Security; 20 import java.util.Locale; 21 22 import org.bouncycastle.crypto.Digest; 23 24 /** 25 * Level of indirection to let us select OpenSSLDigest implementations 26 * for libcore but fallback to BouncyCastle ones on the RI. 27 */ 28 public final class AndroidDigestFactory { 29 private static final AndroidDigestFactoryInterface CONSCRYPT; 30 private static final AndroidDigestFactoryInterface BC; 31 32 static { 33 BC = new AndroidDigestFactoryBouncyCastle(); 34 if (Security.getProvider("AndroidOpenSSL") != null) { 35 CONSCRYPT = new AndroidDigestFactoryOpenSSL(); 36 } else { 37 if (System.getProperty("java.vendor", "").toLowerCase(Locale.US).contains("android")) { 38 throw new AssertionError("Provider AndroidOpenSSL must exist"); 39 } 40 CONSCRYPT = null; 41 } 42 } 43 44 public static Digest getMD5() { 45 if (CONSCRYPT != null) { 46 try { 47 return CONSCRYPT.getMD5(); 48 } catch (Exception ignored) { 49 } 50 } 51 52 return BC.getMD5(); 53 } 54 55 public static Digest getSHA1() { 56 if (CONSCRYPT != null) { 57 try { 58 return CONSCRYPT.getSHA1(); 59 } catch (Exception ignored) { 60 } 61 } 62 63 return BC.getSHA1(); 64 } 65 66 public static Digest getSHA224() { 67 if (CONSCRYPT != null) { 68 try { 69 return CONSCRYPT.getSHA224(); 70 } catch (Exception ignored) { 71 } 72 } 73 74 return BC.getSHA224(); 75 } 76 77 public static Digest getSHA256() { 78 if (CONSCRYPT != null) { 79 try { 80 return CONSCRYPT.getSHA256(); 81 } catch (Exception ignored) { 82 } 83 } 84 85 return BC.getSHA256(); 86 } 87 88 public static Digest getSHA384() { 89 if (CONSCRYPT != null) { 90 try { 91 return CONSCRYPT.getSHA384(); 92 } catch (Exception ignored) { 93 } 94 } 95 96 return BC.getSHA384(); 97 } 98 99 public static Digest getSHA512() { 100 if (CONSCRYPT != null) { 101 try { 102 return CONSCRYPT.getSHA512(); 103 } catch (Exception ignored) { 104 } 105 } 106 107 return BC.getSHA512(); 108 } 109 } 110