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