SSLUtils.java revision 724c3a81cd3649b48ab47c6e49cb42f73f20c815
1/* 2 * Copyright (C) 2010 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.emailcommon.utility; 18 19import android.net.SSLCertificateSocketFactory; 20 21import javax.net.ssl.SSLSocketFactory; 22 23public class SSLUtils { 24 private static SSLSocketFactory sInsecureFactory; 25 private static SSLSocketFactory sSecureFactory; 26 27 /** 28 * Returns a {@link SSLSocketFactory}. Optionally bypass all SSL certificate checks. 29 * 30 * @param insecure if true, bypass all SSL certificate checks 31 */ 32 public synchronized static final SSLSocketFactory getSSLSocketFactory(boolean insecure) { 33 if (insecure) { 34 if (sInsecureFactory == null) { 35 sInsecureFactory = SSLCertificateSocketFactory.getInsecure(0, null); 36 } 37 return sInsecureFactory; 38 } else { 39 if (sSecureFactory == null) { 40 sSecureFactory = SSLCertificateSocketFactory.getDefault(0, null); 41 } 42 return sSecureFactory; 43 } 44 } 45 46 /** 47 * Escapes the contents a string to be used as a safe scheme name in the URI according to 48 * http://tools.ietf.org/html/rfc3986#section-3.1 49 * 50 * This does not ensure that the first character is a letter (which is required by the RFC). 51 */ 52 public static String escapeForSchemeName(String s) { 53 // According to the RFC, scheme names are case-insensitive. 54 s = s.toLowerCase(); 55 56 StringBuilder sb = new StringBuilder(); 57 for (int i = 0; i < s.length(); i++) { 58 char c = s.charAt(i); 59 if (Character.isLetter(c) || Character.isDigit(c) 60 || ('-' == c) || ('.' == c)) { 61 // Safe - use as is. 62 sb.append(c); 63 } else if ('+' == c) { 64 // + is used as our escape character, so double it up. 65 sb.append("++"); 66 } else { 67 // Unsafe - escape. 68 sb.append('+').append((int) c); 69 } 70 } 71 return sb.toString(); 72 } 73} 74