Home | History | Annotate | Download | only in conscrypt
      1 /*
      2  * Copyright (C) 2008 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.conscrypt;
     18 
     19 import java.io.FileDescriptor;
     20 import java.io.IOException;
     21 import java.io.OutputStream;
     22 import java.net.SocketTimeoutException;
     23 import java.security.MessageDigest;
     24 import java.security.NoSuchAlgorithmException;
     25 import java.security.SignatureException;
     26 import java.security.cert.CertificateEncodingException;
     27 import java.security.cert.CertificateException;
     28 import java.security.cert.CertificateParsingException;
     29 import java.security.interfaces.DSAPrivateKey;
     30 import java.security.interfaces.ECPrivateKey;
     31 import java.security.interfaces.RSAPrivateKey;
     32 import java.util.ArrayList;
     33 import java.util.Calendar;
     34 import java.util.HashMap;
     35 import java.util.LinkedHashMap;
     36 import java.util.List;
     37 import java.util.Map;
     38 import javax.crypto.BadPaddingException;
     39 import javax.crypto.IllegalBlockSizeException;
     40 import javax.net.ssl.SSLException;
     41 import javax.security.auth.x500.X500Principal;
     42 
     43 /**
     44  * Provides the Java side of our JNI glue for OpenSSL.
     45  */
     46 public final class NativeCrypto {
     47 
     48     // --- OpenSSL library initialization --------------------------------------
     49     static {
     50         /*
     51          * If we're compiled as part of Android, should use a different JNI
     52          * library name. Detect this by looking for the jarjar'd package name.
     53          */
     54         if ("com.android.org.conscrypt".equals(NativeCrypto.class.getPackage().getName())) {
     55             System.loadLibrary("javacrypto");
     56         } else if ("com.google.android.gms.org.conscrypt".equals(NativeCrypto.class.getPackage().getName())) {
     57             System.loadLibrary("gmscore");
     58             System.loadLibrary("conscrypt_gmscore_jni");
     59         } else {
     60             System.loadLibrary("conscrypt_jni");
     61         }
     62 
     63         clinit();
     64     }
     65 
     66     private native static void clinit();
     67 
     68     // --- ENGINE functions ----------------------------------------------------
     69     public static native void ENGINE_load_dynamic();
     70 
     71     public static native long ENGINE_by_id(String id);
     72 
     73     public static native int ENGINE_add(long e);
     74 
     75     public static native int ENGINE_init(long e);
     76 
     77     public static native int ENGINE_finish(long e);
     78 
     79     public static native int ENGINE_free(long e);
     80 
     81     public static native long ENGINE_load_private_key(long e, String key_id);
     82 
     83     public static native String ENGINE_get_id(long engineRef);
     84 
     85     public static native int ENGINE_ctrl_cmd_string(long engineRef, String cmd, String arg,
     86             int cmd_optional);
     87 
     88     // --- DSA/RSA public/private key handling functions -----------------------
     89 
     90     public static native long EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g,
     91                                                byte[] pub_key, byte[] priv_key);
     92 
     93     public static native long EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q,
     94             byte[] dmp1, byte[] dmq1, byte[] iqmp);
     95 
     96     public static native long EVP_PKEY_new_mac_key(int type, byte[] key);
     97 
     98     public static native int EVP_PKEY_size(long pkey);
     99 
    100     public static native int EVP_PKEY_type(long pkey);
    101 
    102     public static native String EVP_PKEY_print_public(long pkeyRef);
    103 
    104     public static native String EVP_PKEY_print_private(long pkeyRef);
    105 
    106     public static native void EVP_PKEY_free(long pkey);
    107 
    108     public static native int EVP_PKEY_cmp(long pkey1, long pkey2);
    109 
    110     public static native byte[] i2d_PKCS8_PRIV_KEY_INFO(long pkey);
    111 
    112     public static native long d2i_PKCS8_PRIV_KEY_INFO(byte[] data);
    113 
    114     public static native byte[] i2d_PUBKEY(long pkey);
    115 
    116     public static native long d2i_PUBKEY(byte[] data);
    117 
    118     public static native long getRSAPrivateKeyWrapper(RSAPrivateKey key, byte[] modulus);
    119 
    120     public static native long getDSAPrivateKeyWrapper(DSAPrivateKey key);
    121 
    122     public static native long getECPrivateKeyWrapper(ECPrivateKey key, long ecGroupRef);
    123 
    124     public static native long RSA_generate_key_ex(int modulusBits, byte[] publicExponent);
    125 
    126     public static native int RSA_size(long pkey);
    127 
    128     public static native int RSA_private_encrypt(int flen, byte[] from, byte[] to, long pkey,
    129             int padding);
    130 
    131     public static native int RSA_public_decrypt(int flen, byte[] from, byte[] to, long pkey,
    132             int padding) throws BadPaddingException, SignatureException;
    133 
    134     public static native int RSA_public_encrypt(int flen, byte[] from, byte[] to, long pkey,
    135             int padding);
    136 
    137     public static native int RSA_private_decrypt(int flen, byte[] from, byte[] to, long pkey,
    138             int padding) throws BadPaddingException, SignatureException;
    139 
    140     /**
    141      * @return array of {n, e}
    142      */
    143     public static native byte[][] get_RSA_public_params(long rsa);
    144 
    145     /**
    146      * @return array of {n, e, d, p, q, dmp1, dmq1, iqmp}
    147      */
    148     public static native byte[][] get_RSA_private_params(long rsa);
    149 
    150     public static native long DSA_generate_key(int primeBits, byte[] seed, byte[] g, byte[] p,
    151             byte[] q);
    152 
    153     /**
    154      * @return array of {g, p, q, y(pub), x(priv)}
    155      */
    156     public static native byte[][] get_DSA_params(long dsa);
    157 
    158     public static native void set_DSA_flag_nonce_from_hash(long dsa);
    159 
    160     public static native byte[] i2d_RSAPublicKey(long rsa);
    161 
    162     public static native byte[] i2d_RSAPrivateKey(long rsa);
    163 
    164     public static native byte[] i2d_DSAPublicKey(long dsa);
    165 
    166     public static native byte[] i2d_DSAPrivateKey(long dsa);
    167 
    168     // --- DH public/private key handling functions ----------------------------
    169 
    170     public static native long EVP_PKEY_new_DH(byte[] p, byte[] g, byte[] pub_key, byte[] priv_key);
    171 
    172     public static native long DH_generate_parameters_ex(int primeBits, long generator);
    173 
    174     public static native void DH_generate_key(long pkeyRef);
    175 
    176     /**
    177      * @return array of {p, g, y(pub), x(priv)}
    178      */
    179     public static native byte[][] get_DH_params(long dh);
    180 
    181     // --- EC functions --------------------------
    182 
    183     /**
    184      * Used to request EC_GROUP_new_curve_GFp to EC_GROUP_new_curve
    185      */
    186     public static final int EC_CURVE_GFP = 1;
    187 
    188     /**
    189      * Used to request EC_GROUP_new_curve_GF2m to EC_GROUP_new_curve
    190      */
    191     public static final int EC_CURVE_GF2M = 2;
    192 
    193     /**
    194      * EC_GROUP_set_asn1_flag: indicates an EC_GROUP is a NamedCurve.
    195      */
    196     public static final int OPENSSL_EC_NAMED_CURVE = 0x001;
    197 
    198     /**
    199      * EC_GROUP_set_point_conversion_form: indicates compressed ASN.1 format
    200      */
    201     public static final int POINT_CONVERSION_COMPRESSED = 2;
    202 
    203     /**
    204      * EC_GROUP_set_point_conversion_form: indicates uncompressed ASN.1 format
    205      */
    206     public static final int POINT_CONVERSION_UNCOMPRESSED = 4;
    207 
    208     /**
    209      * EC_GROUP_set_point_conversion_form: indicates hybrid ASN.1 format
    210      */
    211     public static final int POINT_CONVERSION_HYBRID = 4;
    212 
    213     public static native long EVP_PKEY_new_EC_KEY(long groupRef, long pubkeyRef, byte[] privkey);
    214 
    215     public static native long EC_GROUP_new_by_curve_name(String curveName);
    216 
    217     public static native long EC_GROUP_new_curve(int type, byte[] p, byte[] a, byte[] b);
    218 
    219     public static native long EC_GROUP_dup(long groupRef);
    220 
    221     public static native void EC_GROUP_set_asn1_flag(long groupRef, int flag);
    222 
    223     public static native void EC_GROUP_set_point_conversion_form(long groupRef, int form);
    224 
    225     public static native String EC_GROUP_get_curve_name(long groupRef);
    226 
    227     public static native byte[][] EC_GROUP_get_curve(long groupRef);
    228 
    229     public static native void EC_GROUP_clear_free(long ctx);
    230 
    231     public static native boolean EC_GROUP_cmp(long ctx1, long ctx2);
    232 
    233     public static native void EC_GROUP_set_generator(long groupCtx, long pointCtx, byte[] n, byte[] h);
    234 
    235     public static native long EC_GROUP_get_generator(long groupCtx);
    236 
    237     public static native int get_EC_GROUP_type(long groupCtx);
    238 
    239     public static native byte[] EC_GROUP_get_order(long groupCtx);
    240 
    241     public static native int EC_GROUP_get_degree(long groupCtx);
    242 
    243     public static native byte[] EC_GROUP_get_cofactor(long groupCtx);
    244 
    245     public static native long EC_POINT_new(long groupRef);
    246 
    247     public static native void EC_POINT_clear_free(long pointRef);
    248 
    249     public static native boolean EC_POINT_cmp(long groupRef, long pointRef1, long pointRef2);
    250 
    251     public static native byte[][] EC_POINT_get_affine_coordinates(long groupCtx, long pointCtx);
    252 
    253     public static native void EC_POINT_set_affine_coordinates(long groupCtx, long pointCtx, byte[] x,
    254             byte[] y);
    255 
    256     public static native long EC_KEY_generate_key(long groupRef);
    257 
    258     public static native long EC_KEY_get0_group(long pkeyRef);
    259 
    260     public static native byte[] EC_KEY_get_private_key(long keyRef);
    261 
    262     public static native long EC_KEY_get_public_key(long keyRef);
    263 
    264     public static native void EC_KEY_set_nonce_from_hash(long keyRef, boolean enabled);
    265 
    266     public static native int ECDH_compute_key(
    267             byte[] out, int outOffset, long publicKeyRef, long privateKeyRef);
    268 
    269     // --- Message digest functions --------------
    270 
    271     public static native long EVP_get_digestbyname(String name);
    272 
    273     public static native int EVP_MD_size(long evp_md);
    274 
    275     public static native int EVP_MD_block_size(long evp_md);
    276 
    277     // --- Message digest context functions --------------
    278 
    279     public static native long EVP_MD_CTX_create();
    280 
    281     public static native void EVP_MD_CTX_init(OpenSSLDigestContext ctx);
    282 
    283     public static native void EVP_MD_CTX_destroy(long ctx);
    284 
    285     public static native int EVP_MD_CTX_copy(OpenSSLDigestContext dst_ctx,
    286             OpenSSLDigestContext src_ctx);
    287 
    288     // --- Digest handling functions -------------------------------------------
    289 
    290     public static native int EVP_DigestInit(OpenSSLDigestContext ctx, long evp_md);
    291 
    292     public static native void EVP_DigestUpdate(OpenSSLDigestContext ctx, byte[] buffer,
    293             int offset, int length);
    294 
    295     public static native int EVP_DigestFinal(OpenSSLDigestContext ctx, byte[] hash, int offset);
    296 
    297     // --- MAC handling functions ----------------------------------------------
    298 
    299     public static native void EVP_DigestSignInit(OpenSSLDigestContext evp_md_ctx, long evp_md,
    300             long evp_pkey);
    301 
    302     public static native void EVP_DigestSignUpdate(OpenSSLDigestContext evp_md_ctx, byte[] in);
    303 
    304     public static native byte[] EVP_DigestSignFinal(OpenSSLDigestContext evp_md_ctx);
    305 
    306     // --- Signature handling functions ----------------------------------------
    307 
    308     public static native int EVP_SignInit(OpenSSLDigestContext ctx, long evpRef);
    309 
    310     public static native void EVP_SignUpdate(OpenSSLDigestContext ctx, byte[] buffer,
    311                                                int offset, int length);
    312 
    313     public static native int EVP_SignFinal(OpenSSLDigestContext ctx, byte[] signature, int offset,
    314             long key);
    315 
    316     public static native int EVP_VerifyInit(OpenSSLDigestContext ctx, long evpRef);
    317 
    318     public static native void EVP_VerifyUpdate(OpenSSLDigestContext ctx, byte[] buffer,
    319                                                int offset, int length);
    320 
    321     public static native int EVP_VerifyFinal(OpenSSLDigestContext ctx, byte[] signature,
    322                                              int offset, int length, long key);
    323 
    324 
    325     // --- Block ciphers -------------------------------------------------------
    326 
    327     public static native long EVP_get_cipherbyname(String string);
    328 
    329     public static native void EVP_CipherInit_ex(long ctx, long evpCipher, byte[] key, byte[] iv,
    330             boolean encrypting);
    331 
    332     public static native int EVP_CipherUpdate(long ctx, byte[] out, int outOffset, byte[] in,
    333             int inOffset, int inLength);
    334 
    335     public static native int EVP_CipherFinal_ex(long ctx, byte[] out, int outOffset)
    336             throws BadPaddingException, IllegalBlockSizeException;
    337 
    338     public static native int EVP_CIPHER_iv_length(long evpCipher);
    339 
    340     public static native long EVP_CIPHER_CTX_new();
    341 
    342     public static native int EVP_CIPHER_CTX_block_size(long ctx);
    343 
    344     public static native int get_EVP_CIPHER_CTX_buf_len(long ctx);
    345 
    346     public static native void EVP_CIPHER_CTX_set_padding(long ctx, boolean enablePadding);
    347 
    348     public static native void EVP_CIPHER_CTX_set_key_length(long ctx, int keyBitSize);
    349 
    350     public static native void EVP_CIPHER_CTX_cleanup(long ctx);
    351 
    352     // --- RAND seeding --------------------------------------------------------
    353 
    354     public static final int RAND_SEED_LENGTH_IN_BYTES = 1024;
    355 
    356     public static native void RAND_seed(byte[] seed);
    357 
    358     public static native int RAND_load_file(String filename, long max_bytes);
    359 
    360     public static native void RAND_bytes(byte[] output);
    361 
    362     // --- ASN.1 objects -------------------------------------------------------
    363 
    364     public static native int OBJ_txt2nid(String oid);
    365 
    366     public static native String OBJ_txt2nid_longName(String oid);
    367 
    368     public static native String OBJ_txt2nid_oid(String oid);
    369 
    370     // --- X509_NAME -----------------------------------------------------------
    371 
    372     public static int X509_NAME_hash(X500Principal principal) {
    373         return X509_NAME_hash(principal, "SHA1");
    374     }
    375     public static int X509_NAME_hash_old(X500Principal principal) {
    376         return X509_NAME_hash(principal, "MD5");
    377     }
    378     private static int X509_NAME_hash(X500Principal principal, String algorithm) {
    379         try {
    380             byte[] digest = MessageDigest.getInstance(algorithm).digest(principal.getEncoded());
    381             int offset = 0;
    382             return (((digest[offset++] & 0xff) <<  0) |
    383                     ((digest[offset++] & 0xff) <<  8) |
    384                     ((digest[offset++] & 0xff) << 16) |
    385                     ((digest[offset  ] & 0xff) << 24));
    386         } catch (NoSuchAlgorithmException e) {
    387             throw new AssertionError(e);
    388         }
    389     }
    390 
    391     public static native String X509_NAME_print_ex(long x509nameCtx, long flags);
    392 
    393     // --- X509 ----------------------------------------------------------------
    394 
    395     /** Used to request get_X509_GENERAL_NAME_stack get the "altname" field. */
    396     public static final int GN_STACK_SUBJECT_ALT_NAME = 1;
    397 
    398     /**
    399      * Used to request get_X509_GENERAL_NAME_stack get the issuerAlternativeName
    400      * extension.
    401      */
    402     public static final int GN_STACK_ISSUER_ALT_NAME = 2;
    403 
    404     /**
    405      * Used to request only non-critical types in get_X509*_ext_oids.
    406      */
    407     public static final int EXTENSION_TYPE_NON_CRITICAL = 0;
    408 
    409     /**
    410      * Used to request only critical types in get_X509*_ext_oids.
    411      */
    412     public static final int EXTENSION_TYPE_CRITICAL = 1;
    413 
    414     public static native long d2i_X509_bio(long bioCtx);
    415 
    416     public static native long d2i_X509(byte[] encoded);
    417 
    418     public static native long PEM_read_bio_X509(long bioCtx);
    419 
    420     public static native byte[] i2d_X509(long x509ctx);
    421 
    422     /** Takes an X509 context not an X509_PUBKEY context. */
    423     public static native byte[] i2d_X509_PUBKEY(long x509ctx);
    424 
    425     public static native byte[] ASN1_seq_pack_X509(long[] x509CertRefs);
    426 
    427     public static native long[] ASN1_seq_unpack_X509_bio(long bioRef);
    428 
    429     public static native void X509_free(long x509ctx);
    430 
    431     public static native int X509_cmp(long x509ctx1, long x509ctx2);
    432 
    433     public static native int get_X509_hashCode(long x509ctx);
    434 
    435     public static native void X509_print_ex(long bioCtx, long x509ctx, long nmflag, long certflag);
    436 
    437     public static native byte[] X509_get_issuer_name(long x509ctx);
    438 
    439     public static native byte[] X509_get_subject_name(long x509ctx);
    440 
    441     public static native String get_X509_sig_alg_oid(long x509ctx);
    442 
    443     public static native byte[] get_X509_sig_alg_parameter(long x509ctx);
    444 
    445     public static native boolean[] get_X509_issuerUID(long x509ctx);
    446 
    447     public static native boolean[] get_X509_subjectUID(long x509ctx);
    448 
    449     public static native long X509_get_pubkey(long x509ctx) throws NoSuchAlgorithmException;
    450 
    451     public static native String get_X509_pubkey_oid(long x509ctx);
    452 
    453     public static native byte[] X509_get_ext_oid(long x509ctx, String oid);
    454 
    455     public static native String[] get_X509_ext_oids(long x509ctx, int critical);
    456 
    457     public static native Object[][] get_X509_GENERAL_NAME_stack(long x509ctx, int type)
    458             throws CertificateParsingException;
    459 
    460     public static native boolean[] get_X509_ex_kusage(long x509ctx);
    461 
    462     public static native String[] get_X509_ex_xkusage(long x509ctx);
    463 
    464     public static native int get_X509_ex_pathlen(long x509ctx);
    465 
    466     public static native long X509_get_notBefore(long x509ctx);
    467 
    468     public static native long X509_get_notAfter(long x509ctx);
    469 
    470     public static native long X509_get_version(long x509ctx);
    471 
    472     public static native byte[] X509_get_serialNumber(long x509ctx);
    473 
    474     public static native void X509_verify(long x509ctx, long pkeyCtx) throws BadPaddingException;
    475 
    476     public static native byte[] get_X509_cert_info_enc(long x509ctx);
    477 
    478     public static native byte[] get_X509_signature(long x509ctx);
    479 
    480     public static native int get_X509_ex_flags(long x509ctx);
    481 
    482     public static native int X509_check_issued(long ctx, long ctx2);
    483 
    484     // --- X509 EXFLAG ---------------------------------------------------------
    485 
    486     public static final int EXFLAG_CA = 0x10;
    487 
    488     public static final int EXFLAG_CRITICAL = 0x200;
    489 
    490     // --- PKCS7 ---------------------------------------------------------------
    491 
    492     /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
    493     public static final int PKCS7_CERTS = 1;
    494 
    495     /** Used as the "which" field in d2i_PKCS7_bio and PEM_read_bio_PKCS7. */
    496     public static final int PKCS7_CRLS = 2;
    497 
    498     /** Returns an array of X509 or X509_CRL pointers. */
    499     public static native long[] d2i_PKCS7_bio(long bioCtx, int which);
    500 
    501     /** Returns an array of X509 or X509_CRL pointers. */
    502     public static native byte[] i2d_PKCS7(long[] certs);
    503 
    504     /** Returns an array of X509 or X509_CRL pointers. */
    505     public static native long[] PEM_read_bio_PKCS7(long bioCtx, int which);
    506 
    507     // --- X509_CRL ------------------------------------------------------------
    508 
    509     public static native long d2i_X509_CRL_bio(long bioCtx);
    510 
    511     public static native long PEM_read_bio_X509_CRL(long bioCtx);
    512 
    513     public static native byte[] i2d_X509_CRL(long x509CrlCtx);
    514 
    515     public static native void X509_CRL_free(long x509CrlCtx);
    516 
    517     public static native void X509_CRL_print(long bioCtx, long x509CrlCtx);
    518 
    519     public static native String get_X509_CRL_sig_alg_oid(long x509CrlCtx);
    520 
    521     public static native byte[] get_X509_CRL_sig_alg_parameter(long x509CrlCtx);
    522 
    523     public static native byte[] X509_CRL_get_issuer_name(long x509CrlCtx);
    524 
    525     /** Returns X509_REVOKED reference that is not duplicated! */
    526     public static native long X509_CRL_get0_by_cert(long x509CrlCtx, long x509Ctx);
    527 
    528     /** Returns X509_REVOKED reference that is not duplicated! */
    529     public static native long X509_CRL_get0_by_serial(long x509CrlCtx, byte[] serial);
    530 
    531     /** Returns an array of X509_REVOKED that are owned by the caller. */
    532     public static native long[] X509_CRL_get_REVOKED(long x509CrlCtx);
    533 
    534     public static native String[] get_X509_CRL_ext_oids(long x509ctx, int critical);
    535 
    536     public static native byte[] X509_CRL_get_ext_oid(long x509CrlCtx, String oid);
    537 
    538     public static native long X509_CRL_get_version(long x509CrlCtx);
    539 
    540     public static native long X509_CRL_get_ext(long x509CrlCtx, String oid);
    541 
    542     public static native byte[] get_X509_CRL_signature(long x509ctx);
    543 
    544     public static native void X509_CRL_verify(long x509CrlCtx, long pkeyCtx);
    545 
    546     public static native byte[] get_X509_CRL_crl_enc(long x509CrlCtx);
    547 
    548     public static native long X509_CRL_get_lastUpdate(long x509CrlCtx);
    549 
    550     public static native long X509_CRL_get_nextUpdate(long x509CrlCtx);
    551 
    552     // --- X509_REVOKED --------------------------------------------------------
    553 
    554     public static native long X509_REVOKED_dup(long x509RevokedCtx);
    555 
    556     public static native byte[] i2d_X509_REVOKED(long x509RevokedCtx);
    557 
    558     public static native String[] get_X509_REVOKED_ext_oids(long x509ctx, int critical);
    559 
    560     public static native byte[] X509_REVOKED_get_ext_oid(long x509RevokedCtx, String oid);
    561 
    562     public static native byte[] X509_REVOKED_get_serialNumber(long x509RevokedCtx);
    563 
    564     public static native long X509_REVOKED_get_ext(long x509RevokedCtx, String oid);
    565 
    566     /** Returns ASN1_TIME reference. */
    567     public static native long get_X509_REVOKED_revocationDate(long x509RevokedCtx);
    568 
    569     public static native void X509_REVOKED_print(long bioRef, long x509RevokedCtx);
    570 
    571     // --- X509_EXTENSION ------------------------------------------------------
    572 
    573     public static native int X509_supported_extension(long x509ExtensionRef);
    574 
    575     // --- ASN1_TIME -----------------------------------------------------------
    576 
    577     public static native void ASN1_TIME_to_Calendar(long asn1TimeCtx, Calendar cal);
    578 
    579     // --- BIO stream creation -------------------------------------------------
    580 
    581     public static native long create_BIO_InputStream(OpenSSLBIOInputStream is);
    582 
    583     public static native long create_BIO_OutputStream(OutputStream os);
    584 
    585     public static native int BIO_read(long bioRef, byte[] buffer);
    586 
    587     public static native void BIO_write(long bioRef, byte[] buffer, int offset, int length)
    588             throws IOException;
    589 
    590     public static native void BIO_free_all(long bioRef);
    591 
    592     // --- SSL handling --------------------------------------------------------
    593 
    594     private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
    595     private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
    596     private static final String SUPPORTED_PROTOCOL_TLSV1_1 = "TLSv1.1";
    597     private static final String SUPPORTED_PROTOCOL_TLSV1_2 = "TLSv1.2";
    598 
    599     public static final Map<String, String> OPENSSL_TO_STANDARD_CIPHER_SUITES
    600             = new HashMap<String, String>();
    601     public static final Map<String, String> STANDARD_TO_OPENSSL_CIPHER_SUITES
    602             = new LinkedHashMap<String, String>();
    603 
    604     private static void add(String standard, String openssl) {
    605         OPENSSL_TO_STANDARD_CIPHER_SUITES.put(openssl, standard);
    606         STANDARD_TO_OPENSSL_CIPHER_SUITES.put(standard, openssl);
    607     }
    608 
    609     /**
    610      * TLS_EMPTY_RENEGOTIATION_INFO_SCSV is RFC 5746's renegotiation
    611      * indication signaling cipher suite value. It is not a real
    612      * cipher suite. It is just an indication in the default and
    613      * supported cipher suite lists indicates that the implementation
    614      * supports secure renegotiation.
    615      *
    616      * In the RI, its presence means that the SCSV is sent in the
    617      * cipher suite list to indicate secure renegotiation support and
    618      * its absense means to send an empty TLS renegotiation info
    619      * extension instead.
    620      *
    621      * However, OpenSSL doesn't provide an API to give this level of
    622      * control, instead always sending the SCSV and always including
    623      * the empty renegotiation info if TLS is used (as opposed to
    624      * SSL). So we simply allow TLS_EMPTY_RENEGOTIATION_INFO_SCSV to
    625      * be passed for compatibility as to provide the hint that we
    626      * support secure renegotiation.
    627      */
    628     public static final String TLS_EMPTY_RENEGOTIATION_INFO_SCSV
    629             = "TLS_EMPTY_RENEGOTIATION_INFO_SCSV";
    630 
    631     /**
    632      * TLS_FALLBACK_SCSV is from
    633      * https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
    634      * to indicate to the server that this is a fallback protocol
    635      * request.
    636      */
    637     public static final String TLS_FALLBACK_SCSV = "TLS_FALLBACK_SCSV";
    638 
    639     static {
    640         add("SSL_RSA_WITH_RC4_128_MD5",              "RC4-MD5");
    641         add("SSL_RSA_WITH_RC4_128_SHA",              "RC4-SHA");
    642         add("TLS_RSA_WITH_AES_128_CBC_SHA",          "AES128-SHA");
    643         add("TLS_RSA_WITH_AES_256_CBC_SHA",          "AES256-SHA");
    644         add("TLS_ECDH_ECDSA_WITH_RC4_128_SHA",       "ECDH-ECDSA-RC4-SHA");
    645         add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",   "ECDH-ECDSA-AES128-SHA");
    646         add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",   "ECDH-ECDSA-AES256-SHA");
    647         add("TLS_ECDH_RSA_WITH_RC4_128_SHA",         "ECDH-RSA-RC4-SHA");
    648         add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",     "ECDH-RSA-AES128-SHA");
    649         add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",     "ECDH-RSA-AES256-SHA");
    650         add("TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",      "ECDHE-ECDSA-RC4-SHA");
    651         add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",  "ECDHE-ECDSA-AES128-SHA");
    652         add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",  "ECDHE-ECDSA-AES256-SHA");
    653         add("TLS_ECDHE_RSA_WITH_RC4_128_SHA",        "ECDHE-RSA-RC4-SHA");
    654         add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",    "ECDHE-RSA-AES128-SHA");
    655         add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",    "ECDHE-RSA-AES256-SHA");
    656         add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA",      "DHE-RSA-AES128-SHA");
    657         add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA",      "DHE-RSA-AES256-SHA");
    658         add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA",      "DHE-DSS-AES128-SHA");
    659         add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA",      "DHE-DSS-AES256-SHA");
    660         add("SSL_RSA_WITH_3DES_EDE_CBC_SHA",         "DES-CBC3-SHA");
    661         add("TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA",  "ECDH-ECDSA-DES-CBC3-SHA");
    662         add("TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",    "ECDH-RSA-DES-CBC3-SHA");
    663         add("TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", "ECDHE-ECDSA-DES-CBC3-SHA");
    664         add("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",   "ECDHE-RSA-DES-CBC3-SHA");
    665         add("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",     "EDH-RSA-DES-CBC3-SHA");
    666         add("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",     "EDH-DSS-DES-CBC3-SHA");
    667         add("SSL_RSA_WITH_DES_CBC_SHA",              "DES-CBC-SHA");
    668         add("SSL_DHE_RSA_WITH_DES_CBC_SHA",          "EDH-RSA-DES-CBC-SHA");
    669         add("SSL_DHE_DSS_WITH_DES_CBC_SHA",          "EDH-DSS-DES-CBC-SHA");
    670         add("SSL_RSA_EXPORT_WITH_RC4_40_MD5",        "EXP-RC4-MD5");
    671         add("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",     "EXP-DES-CBC-SHA");
    672         add("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-RSA-DES-CBC-SHA");
    673         add("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", "EXP-EDH-DSS-DES-CBC-SHA");
    674         add("SSL_RSA_WITH_NULL_MD5",                 "NULL-MD5");
    675         add("SSL_RSA_WITH_NULL_SHA",                 "NULL-SHA");
    676         add("TLS_ECDH_ECDSA_WITH_NULL_SHA",          "ECDH-ECDSA-NULL-SHA");
    677         add("TLS_ECDH_RSA_WITH_NULL_SHA",            "ECDH-RSA-NULL-SHA");
    678         add("TLS_ECDHE_ECDSA_WITH_NULL_SHA",         "ECDHE-ECDSA-NULL-SHA");
    679         add("TLS_ECDHE_RSA_WITH_NULL_SHA",           "ECDHE-RSA-NULL-SHA");
    680         add("SSL_DH_anon_WITH_RC4_128_MD5",          "ADH-RC4-MD5");
    681         add("TLS_DH_anon_WITH_AES_128_CBC_SHA",      "ADH-AES128-SHA");
    682         add("TLS_DH_anon_WITH_AES_256_CBC_SHA",      "ADH-AES256-SHA");
    683         add("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA",     "ADH-DES-CBC3-SHA");
    684         add("SSL_DH_anon_WITH_DES_CBC_SHA",          "ADH-DES-CBC-SHA");
    685         add("TLS_ECDH_anon_WITH_RC4_128_SHA",        "AECDH-RC4-SHA");
    686         add("TLS_ECDH_anon_WITH_AES_128_CBC_SHA",    "AECDH-AES128-SHA");
    687         add("TLS_ECDH_anon_WITH_AES_256_CBC_SHA",    "AECDH-AES256-SHA");
    688         add("TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",   "AECDH-DES-CBC3-SHA");
    689         add("SSL_DH_anon_EXPORT_WITH_RC4_40_MD5",    "EXP-ADH-RC4-MD5");
    690         add("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA", "EXP-ADH-DES-CBC-SHA");
    691         add("TLS_ECDH_anon_WITH_NULL_SHA",           "AECDH-NULL-SHA");
    692 
    693         // TLSv1.2 cipher suites
    694         add("TLS_RSA_WITH_NULL_SHA256",                "NULL-SHA256");
    695         add("TLS_RSA_WITH_AES_128_CBC_SHA256",         "AES128-SHA256");
    696         add("TLS_RSA_WITH_AES_256_CBC_SHA256",         "AES256-SHA256");
    697         add("TLS_RSA_WITH_AES_128_GCM_SHA256",         "AES128-GCM-SHA256");
    698         add("TLS_RSA_WITH_AES_256_GCM_SHA384",         "AES256-GCM-SHA384");
    699         add("TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",     "DHE-RSA-AES128-SHA256");
    700         add("TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",     "DHE-RSA-AES256-SHA256");
    701         add("TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",     "DHE-RSA-AES128-GCM-SHA256");
    702         add("TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",     "DHE-RSA-AES256-GCM-SHA384");
    703         add("TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",     "DHE-DSS-AES128-SHA256");
    704         add("TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",     "DHE-DSS-AES256-SHA256");
    705         add("TLS_DHE_DSS_WITH_AES_128_GCM_SHA256",     "DHE-DSS-AES128-GCM-SHA256");
    706         add("TLS_DHE_DSS_WITH_AES_256_GCM_SHA384",     "DHE-DSS-AES256-GCM-SHA384");
    707         add("TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",    "ECDH-RSA-AES128-SHA256");
    708         add("TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",    "ECDH-RSA-AES256-SHA384");
    709         add("TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",    "ECDH-RSA-AES128-GCM-SHA256");
    710         add("TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",    "ECDH-RSA-AES256-GCM-SHA384");
    711         add("TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",  "ECDH-ECDSA-AES128-SHA256");
    712         add("TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",  "ECDH-ECDSA-AES256-SHA384");
    713         add("TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",  "ECDH-ECDSA-AES128-GCM-SHA256");
    714         add("TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",  "ECDH-ECDSA-AES256-GCM-SHA384");
    715         add("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",   "ECDHE-RSA-AES128-SHA256");
    716         add("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",   "ECDHE-RSA-AES256-SHA384");
    717         add("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",   "ECDHE-RSA-AES128-GCM-SHA256");
    718         add("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",   "ECDHE-RSA-AES256-GCM-SHA384");
    719         add("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "ECDHE-ECDSA-AES128-SHA256");
    720         add("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", "ECDHE-ECDSA-AES256-SHA384");
    721         add("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "ECDHE-ECDSA-AES128-GCM-SHA256");
    722         add("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "ECDHE-ECDSA-AES256-GCM-SHA384");
    723         add("TLS_DH_anon_WITH_AES_128_CBC_SHA256",     "ADH-AES128-SHA256");
    724         add("TLS_DH_anon_WITH_AES_256_CBC_SHA256",     "ADH-AES256-SHA256");
    725         add("TLS_DH_anon_WITH_AES_128_GCM_SHA256",     "ADH-AES128-GCM-SHA256");
    726         add("TLS_DH_anon_WITH_AES_256_GCM_SHA384",     "ADH-AES256-GCM-SHA384");
    727 
    728         // No Kerberos in Android
    729         // add("TLS_KRB5_WITH_RC4_128_SHA",           "KRB5-RC4-SHA");
    730         // add("TLS_KRB5_WITH_RC4_128_MD5",           "KRB5-RC4-MD5");
    731         // add("TLS_KRB5_WITH_3DES_EDE_CBC_SHA",      "KRB5-DES-CBC3-SHA");
    732         // add("TLS_KRB5_WITH_3DES_EDE_CBC_MD5",      "KRB5-DES-CBC3-MD5");
    733         // add("TLS_KRB5_WITH_DES_CBC_SHA",           "KRB5-DES-CBC-SHA");
    734         // add("TLS_KRB5_WITH_DES_CBC_MD5",           "KRB5-DES-CBC-MD5");
    735         // add("TLS_KRB5_EXPORT_WITH_RC4_40_SHA",     "EXP-KRB5-RC4-SHA");
    736         // add("TLS_KRB5_EXPORT_WITH_RC4_40_MD5",     "EXP-KRB5-RC4-MD5");
    737         // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA", "EXP-KRB5-DES-CBC-SHA");
    738         // add("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5", "EXP-KRB5-DES-CBC-MD5");
    739 
    740         // not implemented by either RI or OpenSSL
    741         // add("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", null);
    742         // add("SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", null);
    743 
    744         // EXPORT1024 suites were never standardized but were widely implemented.
    745         // OpenSSL 0.9.8c and later have disabled TLS1_ALLOW_EXPERIMENTAL_CIPHERSUITES
    746         // add("SSL_RSA_EXPORT1024_WITH_DES_CBC_SHA", "EXP1024-DES-CBC-SHA");
    747         // add("SSL_RSA_EXPORT1024_WITH_RC4_56_SHA",  "EXP1024-RC4-SHA");
    748 
    749         // No RC2
    750         // add("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5",  "EXP-RC2-CBC-MD5");
    751         // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA", "EXP-KRB5-RC2-CBC-SHA");
    752         // add("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5", "EXP-KRB5-RC2-CBC-MD5");
    753 
    754         // Pre-Shared Key (PSK) cipher suites
    755         add("TLS_PSK_WITH_3DES_EDE_CBC_SHA", "PSK-3DES-EDE-CBC-SHA");
    756         add("TLS_PSK_WITH_AES_128_CBC_SHA", "PSK-AES128-CBC-SHA");
    757         add("TLS_PSK_WITH_AES_256_CBC_SHA", "PSK-AES256-CBC-SHA");
    758         add("TLS_PSK_WITH_RC4_128_SHA", "PSK-RC4-SHA");
    759         add("TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA", "ECDHE-PSK-AES128-CBC-SHA");
    760         add("TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA", "ECDHE-PSK-AES256-CBC-SHA");
    761 
    762         // Signaling Cipher Suite Value for secure renegotiation handled as special case.
    763         // add("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", null);
    764 
    765         // Similarly, the fallback SCSV is handled as a special case.
    766         // add("TLS_FALLBACK_SCSV", null);
    767     }
    768 
    769     private static final String[] SUPPORTED_CIPHER_SUITES;
    770     static {
    771         int size = STANDARD_TO_OPENSSL_CIPHER_SUITES.size();
    772         SUPPORTED_CIPHER_SUITES = new String[size + 2];
    773         STANDARD_TO_OPENSSL_CIPHER_SUITES.keySet().toArray(SUPPORTED_CIPHER_SUITES);
    774         SUPPORTED_CIPHER_SUITES[size] = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
    775         SUPPORTED_CIPHER_SUITES[size + 1] = TLS_FALLBACK_SCSV;
    776     }
    777 
    778     // EVP_PKEY types from evp.h and objects.h
    779     public static final int EVP_PKEY_RSA  = 6;   // NID_rsaEcnryption
    780     public static final int EVP_PKEY_DSA  = 116; // NID_dsa
    781     public static final int EVP_PKEY_DH   = 28;  // NID_dhKeyAgreement
    782     public static final int EVP_PKEY_EC   = 408; // NID_X9_62_id_ecPublicKey
    783     public static final int EVP_PKEY_HMAC = 855; // NID_hmac
    784     public static final int EVP_PKEY_CMAC = 894; // NID_cmac
    785 
    786     // RSA padding modes from rsa.h
    787     public static final int RSA_PKCS1_PADDING = 1;
    788     public static final int RSA_NO_PADDING    = 3;
    789 
    790     // SSL mode from ssl.h
    791     public static final long SSL_MODE_HANDSHAKE_CUTTHROUGH = 0x00000080L;
    792     public static final long SSL_MODE_CBC_RECORD_SPLITTING = 0x00000100L;
    793     public static final long SSL_MODE_SEND_FALLBACK_SCSV   = 0x00000200L;
    794 
    795     // SSL options from ssl.h
    796     public static final long SSL_OP_TLSEXT_PADDING                         = 0x00000010L;
    797     public static final long SSL_OP_NO_TICKET                              = 0x00004000L;
    798     public static final long SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 0x00010000L;
    799     public static final long SSL_OP_NO_SSLv3                               = 0x02000000L;
    800     public static final long SSL_OP_NO_TLSv1                               = 0x04000000L;
    801     public static final long SSL_OP_NO_TLSv1_1                             = 0x10000000L;
    802     public static final long SSL_OP_NO_TLSv1_2                             = 0x08000000L;
    803 
    804     /*
    805      * Client certificate types as defined in
    806      * TLS 1.0 spec., 7.4.4. Certificate request.
    807      * EC constants from RFC 4492.
    808      * OpenSSL constants from ssl/tls1.h.
    809      */
    810     public static final byte TLS_CT_RSA_SIGN = 1;
    811     public static final byte TLS_CT_DSS_SIGN = 2;
    812     public static final byte TLS_CT_RSA_FIXED_DH = 3;
    813     public static final byte TLS_CT_DSS_FIXED_DH = 4;
    814     public static final byte TLS_CT_ECDSA_SIGN = 64;
    815     public static final byte TLS_CT_RSA_FIXED_ECDH = 65;
    816     public static final byte TLS_CT_ECDSA_FIXED_ECDH = 66;
    817 
    818     /*
    819      * Used in the SSL_get_shutdown and SSL_set_shutdown functions.
    820      */
    821     public static final int SSL_SENT_SHUTDOWN = 1;
    822     public static final int SSL_RECEIVED_SHUTDOWN = 2;
    823 
    824     public static native long SSL_CTX_new();
    825 
    826     // IMPLEMENTATION NOTE: The default list of cipher suites is a trade-off between what we'd like
    827     // to use and what servers currently support. We strive to be secure enough by default. We thus
    828     // avoid unacceptably weak suites (e.g., those with bulk cipher secret key shorter than 128
    829     // bits), while maintaining the capability to connect to the majority of servers.
    830     //
    831     // Cipher suites are listed in preference order (favorite choice first) of the client. However,
    832     // servers are not required to honor the order. The key rules governing the preference order
    833     // are:
    834     // * Prefer Forward Secrecy (i.e., cipher suites that use ECDHE and DHE for key agreement).
    835     // * Prefer AES-GCM to AES-CBC whose MAC-pad-then-encrypt approach leads to weaknesses (e.g.,
    836     //   Lucky 13).
    837     // * Prefer AES to RC4 whose foundations are a bit shaky. See http://www.isg.rhul.ac.uk/tls/.
    838     //   BEAST and Lucky13 mitigations are enabled.
    839     // * Prefer 128-bit bulk encryption to 256-bit one, because 128-bit is safe enough while
    840     //   consuming less CPU/time/energy.
    841     //
    842     // NOTE: Removing cipher suites from this list needs to be done with caution, because this may
    843     // prevent apps from connecting to servers they were previously able to connect to.
    844 
    845     /** X.509 based cipher suites enabled by default (if requested), in preference order. */
    846     static final String[] DEFAULT_X509_CIPHER_SUITES = new String[] {
    847         "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
    848         "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
    849         "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
    850         "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
    851         "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
    852         "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
    853         "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
    854         "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
    855         "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
    856         "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
    857         "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
    858         "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
    859         "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
    860         "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
    861         "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
    862         "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
    863         "TLS_RSA_WITH_AES_128_GCM_SHA256",
    864         "TLS_RSA_WITH_AES_256_GCM_SHA384",
    865         "TLS_RSA_WITH_AES_128_CBC_SHA",
    866         "TLS_RSA_WITH_AES_256_CBC_SHA",
    867         "SSL_RSA_WITH_RC4_128_SHA",
    868     };
    869 
    870     /** TLS-PSK cipher suites enabled by default (if requested), in preference order. */
    871     static final String[] DEFAULT_PSK_CIPHER_SUITES = new String[] {
    872         "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA",
    873         "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA",
    874         "TLS_PSK_WITH_AES_128_CBC_SHA",
    875         "TLS_PSK_WITH_AES_256_CBC_SHA",
    876     };
    877 
    878     public static String[] getSupportedCipherSuites() {
    879         return SUPPORTED_CIPHER_SUITES.clone();
    880     }
    881 
    882     public static native void SSL_CTX_free(long ssl_ctx);
    883 
    884     public static native void SSL_CTX_set_session_id_context(long ssl_ctx, byte[] sid_ctx);
    885 
    886     public static native long SSL_new(long ssl_ctx) throws SSLException;
    887 
    888     public static native void SSL_enable_tls_channel_id(long ssl) throws SSLException;
    889 
    890     public static native byte[] SSL_get_tls_channel_id(long ssl) throws SSLException;
    891 
    892     public static native void SSL_set1_tls_channel_id(long ssl, long pkey);
    893 
    894     public static native void SSL_use_certificate(long ssl, long[] x509refs);
    895 
    896     public static native void SSL_use_PrivateKey(long ssl, long pkey);
    897 
    898     public static native void SSL_check_private_key(long ssl) throws SSLException;
    899 
    900     public static native void SSL_set_client_CA_list(long ssl, byte[][] asn1DerEncodedX500Principals);
    901 
    902     public static native long SSL_get_mode(long ssl);
    903 
    904     public static native long SSL_set_mode(long ssl, long mode);
    905 
    906     public static native long SSL_clear_mode(long ssl, long mode);
    907 
    908     public static native long SSL_get_options(long ssl);
    909 
    910     public static native long SSL_set_options(long ssl, long options);
    911 
    912     public static native long SSL_clear_options(long ssl, long options);
    913 
    914     public static native void SSL_use_psk_identity_hint(long ssl, String identityHint)
    915             throws SSLException;
    916 
    917     public static native void set_SSL_psk_client_callback_enabled(long ssl, boolean enabled);
    918 
    919     public static native void set_SSL_psk_server_callback_enabled(long ssl, boolean enabled);
    920 
    921     public static final String[] DEFAULT_PROTOCOLS = new String[] {
    922         SUPPORTED_PROTOCOL_SSLV3,
    923         SUPPORTED_PROTOCOL_TLSV1,
    924         SUPPORTED_PROTOCOL_TLSV1_1,
    925         SUPPORTED_PROTOCOL_TLSV1_2,
    926     };
    927 
    928     public static String[] getSupportedProtocols() {
    929         return new String[] { SUPPORTED_PROTOCOL_SSLV3,
    930                               SUPPORTED_PROTOCOL_TLSV1,
    931                               SUPPORTED_PROTOCOL_TLSV1_1,
    932                               SUPPORTED_PROTOCOL_TLSV1_2,
    933         };
    934     }
    935 
    936     public static void setEnabledProtocols(long ssl, String[] protocols) {
    937         checkEnabledProtocols(protocols);
    938         // openssl uses negative logic letting you disable protocols.
    939         // so first, assume we need to set all (disable all) and clear none (enable none).
    940         // in the loop, selectively move bits from set to clear (from disable to enable)
    941         long optionsToSet = (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2);
    942         long optionsToClear = 0;
    943         for (int i = 0; i < protocols.length; i++) {
    944             String protocol = protocols[i];
    945             if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
    946                 optionsToSet &= ~SSL_OP_NO_SSLv3;
    947                 optionsToClear |= SSL_OP_NO_SSLv3;
    948             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
    949                 optionsToSet &= ~SSL_OP_NO_TLSv1;
    950                 optionsToClear |= SSL_OP_NO_TLSv1;
    951             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1)) {
    952                 optionsToSet &= ~SSL_OP_NO_TLSv1_1;
    953                 optionsToClear |= SSL_OP_NO_TLSv1_1;
    954             } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2)) {
    955                 optionsToSet &= ~SSL_OP_NO_TLSv1_2;
    956                 optionsToClear |= SSL_OP_NO_TLSv1_2;
    957             } else {
    958                 // error checked by checkEnabledProtocols
    959                 throw new IllegalStateException();
    960             }
    961         }
    962 
    963         SSL_set_options(ssl, optionsToSet);
    964         SSL_clear_options(ssl, optionsToClear);
    965     }
    966 
    967     public static String[] checkEnabledProtocols(String[] protocols) {
    968         if (protocols == null) {
    969             throw new IllegalArgumentException("protocols == null");
    970         }
    971         for (int i = 0; i < protocols.length; i++) {
    972             String protocol = protocols[i];
    973             if (protocol == null) {
    974                 throw new IllegalArgumentException("protocols[" + i + "] == null");
    975             }
    976             if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
    977                     && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))
    978                     && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_1))
    979                     && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1_2))) {
    980                 throw new IllegalArgumentException("protocol " + protocol
    981                                                    + " is not supported");
    982             }
    983         }
    984         return protocols;
    985     }
    986 
    987     public static native void SSL_set_cipher_lists(long ssl, String[] ciphers);
    988 
    989     /**
    990      * Gets the list of cipher suites enabled for the provided {@code SSL} instance.
    991      *
    992      * @return array of {@code SSL_CIPHER} references.
    993      */
    994     public static native long[] SSL_get_ciphers(long ssl);
    995 
    996     /*
    997      * Constants for SSL_CIPHER algorithm_mkey (key exchange algorithm).
    998      * OpenSSL constants from ssl/ssl_locl.h.
    999      */
   1000     /** RSA key exchange */
   1001     public static final int SSL_kRSA =   0x00000001;
   1002     /** DH cert, RSA CA cert -- no such ciphersuite supported! */
   1003     public static final int SSL_kDHr =   0x00000002;
   1004     /** DH cert, DSA CA cert -- no such ciphersuite supported! */
   1005     public static final int SSL_kDHd =   0x00000004;
   1006     /** tmp DH key no DH cert */
   1007     public static final int SSL_kEDH =   0x00000008;
   1008     /** Kerberos5 key exchange */
   1009     public static final int SSL_kKRB5 =  0x00000010;
   1010     /** ECDH cert, RSA CA cert */
   1011     public static final int SSL_kECDHr = 0x00000020;
   1012     /** ECDH cert, ECDSA CA cert */
   1013     public static final int SSL_kECDHe = 0x00000040;
   1014     /** ephemeral ECDH */
   1015     public static final int SSL_kEECDH = 0x00000080;
   1016     /** PSK */
   1017     public static final int SSL_kPSK =   0x00000100;
   1018     /** GOST key exchange */
   1019     public static final int SSL_kGOST =  0x00000200;
   1020     /** SRP */
   1021     public static final int SSL_kSRP =   0x00000400;
   1022 
   1023     /*
   1024      * Constants for SSL_CIPHER algorithm_auth (server authentication).
   1025      * OpenSSL constants from ssl/ssl_locl.h.
   1026      */
   1027     /** RSA auth */
   1028     public static final int SSL_aRSA =    0x00000001;
   1029     /** DSS auth */
   1030     public static final int SSL_aDSS =    0x00000002;
   1031     /** no auth (i.e. use ADH or AECDH) */
   1032     public static final int SSL_aNULL =   0x00000004;
   1033     /** Fixed DH auth (kDHd or kDHr) -- no such ciphersuites supported! */
   1034     public static final int SSL_aDH =     0x00000008;
   1035     /** Fixed ECDH auth (kECDHe or kECDHr) */
   1036     public static final int SSL_aECDH =   0x00000010;
   1037     /** KRB5 auth */
   1038     public static final int SSL_aKRB5 =   0x00000020;
   1039     /** ECDSA auth*/
   1040     public static final int SSL_aECDSA =  0x00000040;
   1041     /** PSK auth */
   1042     public static final int SSL_aPSK =    0x00000080;
   1043     /** GOST R 34.10-94 signature auth */
   1044     public static final int SSL_aGOST94 = 0x00000100;
   1045     /** GOST R 34.10-2001 signature auth */
   1046     public static final int SSL_aGOST01 = 0x00000200;
   1047 
   1048     public static native int get_SSL_CIPHER_algorithm_mkey(long sslCipher);
   1049     public static native int get_SSL_CIPHER_algorithm_auth(long sslCipher);
   1050 
   1051     public static void setEnabledCipherSuites(long ssl, String[] cipherSuites) {
   1052         checkEnabledCipherSuites(cipherSuites);
   1053         List<String> opensslSuites = new ArrayList<String>();
   1054         for (int i = 0; i < cipherSuites.length; i++) {
   1055             String cipherSuite = cipherSuites[i];
   1056             if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV)) {
   1057                 continue;
   1058             }
   1059             if (cipherSuite.equals(TLS_FALLBACK_SCSV)) {
   1060                 SSL_set_mode(ssl, SSL_MODE_SEND_FALLBACK_SCSV);
   1061                 continue;
   1062             }
   1063             String openssl = STANDARD_TO_OPENSSL_CIPHER_SUITES.get(cipherSuite);
   1064             String cs = (openssl == null) ? cipherSuite : openssl;
   1065             opensslSuites.add(cs);
   1066         }
   1067         SSL_set_cipher_lists(ssl, opensslSuites.toArray(new String[opensslSuites.size()]));
   1068     }
   1069 
   1070     public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
   1071         if (cipherSuites == null) {
   1072             throw new IllegalArgumentException("cipherSuites == null");
   1073         }
   1074         // makes sure all suites are valid, throwing on error
   1075         for (int i = 0; i < cipherSuites.length; i++) {
   1076             String cipherSuite = cipherSuites[i];
   1077             if (cipherSuite == null) {
   1078                 throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
   1079             }
   1080             if (cipherSuite.equals(TLS_EMPTY_RENEGOTIATION_INFO_SCSV) ||
   1081                     cipherSuite.equals(TLS_FALLBACK_SCSV)) {
   1082                 continue;
   1083             }
   1084             if (STANDARD_TO_OPENSSL_CIPHER_SUITES.containsKey(cipherSuite)) {
   1085                 continue;
   1086             }
   1087             if (OPENSSL_TO_STANDARD_CIPHER_SUITES.containsKey(cipherSuite)) {
   1088                 // TODO log warning about using backward compatability
   1089                 continue;
   1090             }
   1091             throw new IllegalArgumentException("cipherSuite " + cipherSuite + " is not supported.");
   1092         }
   1093         return cipherSuites;
   1094     }
   1095 
   1096     /*
   1097      * See the OpenSSL ssl.h header file for more information.
   1098      */
   1099     public static final int SSL_VERIFY_NONE =                 0x00;
   1100     public static final int SSL_VERIFY_PEER =                 0x01;
   1101     public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
   1102 
   1103     public static native void SSL_set_accept_state(long sslNativePointer);
   1104 
   1105     public static native void SSL_set_connect_state(long sslNativePointer);
   1106 
   1107     public static native void SSL_set_verify(long sslNativePointer, int mode);
   1108 
   1109     public static native void SSL_set_session(long sslNativePointer, long sslSessionNativePointer)
   1110         throws SSLException;
   1111 
   1112     public static native void SSL_set_session_creation_enabled(
   1113             long sslNativePointer, boolean creationEnabled) throws SSLException;
   1114 
   1115     public static native void SSL_set_tlsext_host_name(long sslNativePointer, String hostname)
   1116             throws SSLException;
   1117     public static native String SSL_get_servername(long sslNativePointer);
   1118 
   1119     /**
   1120      * Enables NPN for all SSL connections in the context.
   1121      *
   1122      * <p>For clients this causes the NPN extension to be included in the
   1123      * ClientHello message.
   1124      *
   1125      * <p>For servers this causes the NPN extension to be included in the
   1126      * ServerHello message. The NPN extension will not be included in the
   1127      * ServerHello response if the client didn't include it in the ClientHello
   1128      * request.
   1129      *
   1130      * <p>In either case the caller should pass a non-null byte array of NPN
   1131      * protocols to {@link #SSL_do_handshake}.
   1132      */
   1133     public static native void SSL_CTX_enable_npn(long sslCtxNativePointer);
   1134 
   1135     /**
   1136      * Disables NPN for all SSL connections in the context.
   1137      */
   1138     public static native void SSL_CTX_disable_npn(long sslCtxNativePointer);
   1139 
   1140     /**
   1141      * For clients, sets the list of supported ALPN protocols in wire-format
   1142      * (length-prefixed 8-bit strings).
   1143      */
   1144     public static native int SSL_set_alpn_protos(long sslPointer, byte[] protos);
   1145 
   1146     /**
   1147      * Returns the selected ALPN protocol. If the server did not select a
   1148      * protocol, {@code null} will be returned.
   1149      */
   1150     public static native byte[] SSL_get0_alpn_selected(long sslPointer);
   1151 
   1152     /**
   1153      * Returns the sslSessionNativePointer of the negotiated session. If this is
   1154      * a server negotiation, supplying the {@code alpnProtocols} will enable
   1155      * ALPN negotiation.
   1156      */
   1157     public static native long SSL_do_handshake(long sslNativePointer,
   1158                                                FileDescriptor fd,
   1159                                                SSLHandshakeCallbacks shc,
   1160                                                int timeoutMillis,
   1161                                                boolean client_mode,
   1162                                                byte[] npnProtocols,
   1163                                                byte[] alpnProtocols)
   1164         throws SSLException, SocketTimeoutException, CertificateException;
   1165 
   1166     /**
   1167      * Returns the sslSessionNativePointer of the negotiated session. If this is
   1168      * a server negotiation, supplying the {@code alpnProtocols} will enable
   1169      * ALPN negotiation.
   1170      */
   1171     public static native long SSL_do_handshake_bio(long sslNativePointer,
   1172                                                    long sourceBioRef,
   1173                                                    long sinkBioRef,
   1174                                                    SSLHandshakeCallbacks shc,
   1175                                                    boolean client_mode,
   1176                                                    byte[] npnProtocols,
   1177                                                    byte[] alpnProtocols)
   1178         throws SSLException, SocketTimeoutException, CertificateException;
   1179 
   1180     public static native byte[] SSL_get_npn_negotiated_protocol(long sslNativePointer);
   1181 
   1182     /**
   1183      * Currently only intended for forcing renegotiation for testing.
   1184      * Not used within OpenSSLSocketImpl.
   1185      */
   1186     public static native void SSL_renegotiate(long sslNativePointer) throws SSLException;
   1187 
   1188     /**
   1189      * Returns the local X509 certificate references. Must X509_free when done.
   1190      */
   1191     public static native long[] SSL_get_certificate(long sslNativePointer);
   1192 
   1193     /**
   1194      * Returns the peer X509 certificate references. Must X509_free when done.
   1195      */
   1196     public static native long[] SSL_get_peer_cert_chain(long sslNativePointer);
   1197 
   1198     /**
   1199      * Reads with the native SSL_read function from the encrypted data stream
   1200      * @return -1 if error or the end of the stream is reached.
   1201      */
   1202     public static native int SSL_read(long sslNativePointer,
   1203                                       FileDescriptor fd,
   1204                                       SSLHandshakeCallbacks shc,
   1205                                       byte[] b, int off, int len, int readTimeoutMillis)
   1206         throws IOException;
   1207 
   1208     public static native int SSL_read_BIO(long sslNativePointer,
   1209                                           byte[] dest,
   1210                                           int destOffset,
   1211                                           int destLength,
   1212                                           long sourceBioRef,
   1213                                           long sinkBioRef,
   1214                                           SSLHandshakeCallbacks shc)
   1215         throws IOException;
   1216 
   1217     /**
   1218      * Writes with the native SSL_write function to the encrypted data stream.
   1219      */
   1220     public static native void SSL_write(long sslNativePointer,
   1221                                         FileDescriptor fd,
   1222                                         SSLHandshakeCallbacks shc,
   1223                                         byte[] b, int off, int len, int writeTimeoutMillis)
   1224         throws IOException;
   1225 
   1226     public static native int SSL_write_BIO(long sslNativePointer,
   1227                                            byte[] source,
   1228                                            int length,
   1229                                            long sinkBioRef,
   1230                                            SSLHandshakeCallbacks shc)
   1231         throws IOException;
   1232 
   1233     public static native void SSL_interrupt(long sslNativePointer);
   1234     public static native void SSL_shutdown(long sslNativePointer,
   1235                                            FileDescriptor fd,
   1236                                            SSLHandshakeCallbacks shc) throws IOException;
   1237 
   1238     public static native void SSL_shutdown_BIO(long sslNativePointer,
   1239                                                long sourceBioRef, long sinkBioRef,
   1240                                                SSLHandshakeCallbacks shc) throws IOException;
   1241 
   1242     public static native int SSL_get_shutdown(long sslNativePointer);
   1243 
   1244     public static native void SSL_free(long sslNativePointer);
   1245 
   1246     public static native byte[] SSL_SESSION_session_id(long sslSessionNativePointer);
   1247 
   1248     public static native long SSL_SESSION_get_time(long sslSessionNativePointer);
   1249 
   1250     public static native String SSL_SESSION_get_version(long sslSessionNativePointer);
   1251 
   1252     public static native String SSL_SESSION_cipher(long sslSessionNativePointer);
   1253 
   1254     public static native void SSL_SESSION_free(long sslSessionNativePointer);
   1255 
   1256     public static native byte[] i2d_SSL_SESSION(long sslSessionNativePointer);
   1257 
   1258     public static native long d2i_SSL_SESSION(byte[] data);
   1259 
   1260     /**
   1261      * A collection of callbacks from the native OpenSSL code that are
   1262      * related to the SSL handshake initiated by SSL_do_handshake.
   1263      */
   1264     public interface SSLHandshakeCallbacks {
   1265         /**
   1266          * Verify that we trust the certificate chain is trusted.
   1267          *
   1268          * @param sslSessionNativePtr pointer to a reference of the SSL_SESSION
   1269          * @param certificateChainRefs chain of X.509 certificate references
   1270          * @param authMethod auth algorithm name
   1271          *
   1272          * @throws CertificateException if the certificate is untrusted
   1273          */
   1274         public void verifyCertificateChain(long sslSessionNativePtr, long[] certificateChainRefs,
   1275                 String authMethod) throws CertificateException;
   1276 
   1277         /**
   1278          * Called on an SSL client when the server requests (or
   1279          * requires a certificate). The client can respond by using
   1280          * SSL_use_certificate and SSL_use_PrivateKey to set a
   1281          * certificate if has an appropriate one available, similar to
   1282          * how the server provides its certificate.
   1283          *
   1284          * @param keyTypes key types supported by the server,
   1285          * convertible to strings with #keyType
   1286          * @param asn1DerEncodedX500Principals CAs known to the server
   1287          */
   1288         public void clientCertificateRequested(byte[] keyTypes,
   1289                                                byte[][] asn1DerEncodedX500Principals)
   1290             throws CertificateEncodingException, SSLException;
   1291 
   1292         /**
   1293          * Gets the key to be used in client mode for this connection in Pre-Shared Key (PSK) key
   1294          * exchange.
   1295          *
   1296          * @param identityHint PSK identity hint provided by the server or {@code null} if no hint
   1297          *        provided.
   1298          * @param identity buffer to be populated with PSK identity (NULL-terminated modified UTF-8)
   1299          *        by this method. This identity will be provided to the server.
   1300          * @param key buffer to be populated with key material by this method.
   1301          *
   1302          * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
   1303          *         error occurred in which case the handshake will be aborted.
   1304          */
   1305         public int clientPSKKeyRequested(String identityHint, byte[] identity, byte[] key);
   1306 
   1307         /**
   1308          * Gets the key to be used in server mode for this connection in Pre-Shared Key (PSK) key
   1309          * exchange.
   1310          *
   1311          * @param identityHint PSK identity hint provided by this server to the client or
   1312          *        {@code null} if no hint was provided.
   1313          * @param identity PSK identity provided by the client.
   1314          * @param key buffer to be populated with key material by this method.
   1315          *
   1316          * @return number of bytes this method stored in the {@code key} buffer or {@code 0} if an
   1317          *         error occurred in which case the handshake will be aborted.
   1318          */
   1319         public int serverPSKKeyRequested(String identityHint, String identity, byte[] key);
   1320 
   1321         /**
   1322          * Called when SSL state changes. This could be handshake completion.
   1323          */
   1324         public void onSSLStateChange(long sslSessionNativePtr, int type, int val);
   1325     }
   1326 
   1327     // Values used in the SSLHandshakeCallbacks#onSSLStateChange as the {@code type}.
   1328     public static final int SSL_ST_CONNECT = 0x1000;
   1329     public static final int SSL_ST_ACCEPT = 0x2000;
   1330     public static final int SSL_ST_MASK = 0x0FFF;
   1331     public static final int SSL_ST_INIT = (SSL_ST_CONNECT | SSL_ST_ACCEPT);
   1332     public static final int SSL_ST_BEFORE = 0x4000;
   1333     public static final int SSL_ST_OK = 0x03;
   1334     public static final int SSL_ST_RENEGOTIATE = (0x04 | SSL_ST_INIT);
   1335 
   1336     public static final int SSL_CB_LOOP = 0x01;
   1337     public static final int SSL_CB_EXIT = 0x02;
   1338     public static final int SSL_CB_READ = 0x04;
   1339     public static final int SSL_CB_WRITE = 0x08;
   1340     public static final int SSL_CB_ALERT = 0x4000;
   1341     public static final int SSL_CB_READ_ALERT = (SSL_CB_ALERT | SSL_CB_READ);
   1342     public static final int SSL_CB_WRITE_ALERT = (SSL_CB_ALERT | SSL_CB_WRITE);
   1343     public static final int SSL_CB_ACCEPT_LOOP = (SSL_ST_ACCEPT | SSL_CB_LOOP);
   1344     public static final int SSL_CB_ACCEPT_EXIT = (SSL_ST_ACCEPT | SSL_CB_EXIT);
   1345     public static final int SSL_CB_CONNECT_LOOP = (SSL_ST_CONNECT | SSL_CB_LOOP);
   1346     public static final int SSL_CB_CONNECT_EXIT = (SSL_ST_CONNECT | SSL_CB_EXIT);
   1347     public static final int SSL_CB_HANDSHAKE_START = 0x10;
   1348     public static final int SSL_CB_HANDSHAKE_DONE = 0x20;
   1349 
   1350     /*
   1351      * From ssl/ssl3.h
   1352      */
   1353     public static final int SSL3_RT_HEADER_LENGTH = 5;
   1354     public static final int SSL_RT_MAX_CIPHER_BLOCK_SIZE = 16;
   1355     public static final int SSL3_RT_MAX_MD_SIZE = 64;
   1356     public static final int SSL3_RT_MAX_PLAIN_LENGTH = 16384;
   1357     public static final int SSL3_RT_MAX_ENCRYPTED_OVERHEAD = 256 + SSL3_RT_MAX_MD_SIZE;
   1358     public static final int SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD = SSL_RT_MAX_CIPHER_BLOCK_SIZE
   1359             + SSL3_RT_MAX_MD_SIZE;
   1360     public static final int SSL3_RT_MAX_COMPRESSED_LENGTH = SSL3_RT_MAX_PLAIN_LENGTH;
   1361     public static final int SSL3_RT_MAX_ENCRYPTED_LENGTH = SSL3_RT_MAX_ENCRYPTED_OVERHEAD
   1362             + SSL3_RT_MAX_COMPRESSED_LENGTH;
   1363     public static final int SSL3_RT_MAX_PACKET_SIZE = SSL3_RT_MAX_ENCRYPTED_LENGTH
   1364             + SSL3_RT_HEADER_LENGTH;
   1365 
   1366     public static native long ERR_peek_last_error();
   1367 }
   1368