Skip to content

Commit d9ccccc

Browse files
schulzpNorman Maurer
authored andcommitted
[netty#2718] Added private key decryption to JDK SSL server context.
Motivation: Currently it is not possible to load an encrypted private key when creating a JDK based SSL server context. Modifications: - Added static method to JdkSslServerContext which handles key spec generation for (encrypted) private keys and make use of it. -Added tests for creating a SSL server context based on a (encrypted) private key. Result: It is now possible to create a JDK based SSL server context with an encrypted (password protected) private key.
1 parent 039cace commit d9ccccc

5 files changed

Lines changed: 187 additions & 26 deletions

File tree

handler/src/main/java/io/netty/handler/ssl/JdkSslServerContext.java

Lines changed: 68 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,15 @@
1313
* License for the specific language governing permissions and limitations
1414
* under the License.
1515
*/
16-
1716
package io.netty.handler.ssl;
1817

19-
import io.netty.buffer.ByteBuf;
20-
import io.netty.buffer.ByteBufInputStream;
21-
22-
import javax.net.ssl.KeyManagerFactory;
23-
import javax.net.ssl.SSLContext;
24-
import javax.net.ssl.SSLException;
25-
import javax.net.ssl.SSLSessionContext;
2618
import java.io.File;
19+
import java.io.IOException;
20+
import java.security.InvalidAlgorithmParameterException;
21+
import java.security.InvalidKeyException;
2722
import java.security.KeyFactory;
2823
import java.security.KeyStore;
24+
import java.security.NoSuchAlgorithmException;
2925
import java.security.PrivateKey;
3026
import java.security.Security;
3127
import java.security.cert.Certificate;
@@ -36,6 +32,20 @@
3632
import java.util.Collections;
3733
import java.util.List;
3834

35+
import javax.crypto.Cipher;
36+
import javax.crypto.EncryptedPrivateKeyInfo;
37+
import javax.crypto.NoSuchPaddingException;
38+
import javax.crypto.SecretKey;
39+
import javax.crypto.SecretKeyFactory;
40+
import javax.crypto.spec.PBEKeySpec;
41+
import javax.net.ssl.KeyManagerFactory;
42+
import javax.net.ssl.SSLContext;
43+
import javax.net.ssl.SSLException;
44+
import javax.net.ssl.SSLSessionContext;
45+
46+
import io.netty.buffer.ByteBuf;
47+
import io.netty.buffer.ByteBufInputStream;
48+
3949
/**
4050
* A server-side {@link SslContext} which uses JDK's SSL/TLS implementation.
4151
*/
@@ -59,8 +69,7 @@ public JdkSslServerContext(File certChainFile, File keyFile) throws SSLException
5969
*
6070
* @param certChainFile an X.509 certificate chain file in PEM format
6171
* @param keyFile a PKCS#8 private key file in PEM format
62-
* @param keyPassword the password of the {@code keyFile}.
63-
* {@code null} if it's not password-protected.
72+
* @param keyPassword the password of the {@code keyFile}. {@code null} if it's not password-protected.
6473
*/
6574
public JdkSslServerContext(File certChainFile, File keyFile, String keyPassword) throws SSLException {
6675
this(certChainFile, keyFile, keyPassword, null, null, 0, 0);
@@ -71,16 +80,15 @@ public JdkSslServerContext(File certChainFile, File keyFile, String keyPassword)
7180
*
7281
* @param certChainFile an X.509 certificate chain file in PEM format
7382
* @param keyFile a PKCS#8 private key file in PEM format
74-
* @param keyPassword the password of the {@code keyFile}.
75-
* {@code null} if it's not password-protected.
76-
* @param ciphers the cipher suites to enable, in the order of preference.
77-
* {@code null} to use the default cipher suites.
78-
* @param nextProtocols the application layer protocols to accept, in the order of preference.
79-
* {@code null} to disable TLS NPN/ALPN extension.
80-
* @param sessionCacheSize the size of the cache used for storing SSL session objects.
81-
* {@code 0} to use the default value.
82-
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds.
83-
* {@code 0} to use the default value.
83+
* @param keyPassword the password of the {@code keyFile}. {@code null} if it's not password-protected.
84+
* @param ciphers the cipher suites to enable, in the order of preference. {@code null} to use the default cipher
85+
* suites.
86+
* @param nextProtocols the application layer protocols to accept, in the order of preference. {@code null} to
87+
* disable TLS NPN/ALPN extension.
88+
* @param sessionCacheSize the size of the cache used for storing SSL session objects. {@code 0} to use the default
89+
* value.
90+
* @param sessionTimeout the timeout for the cached SSL session objects, in seconds. {@code 0} to use the default
91+
* value.
8492
*/
8593
public JdkSslServerContext(
8694
File certChainFile, File keyFile, String keyPassword,
@@ -106,7 +114,7 @@ public JdkSslServerContext(
106114
}
107115

108116
List<String> list = new ArrayList<String>();
109-
for (String p: nextProtocols) {
117+
for (String p : nextProtocols) {
110118
if (p == null) {
111119
break;
112120
}
@@ -133,7 +141,9 @@ public JdkSslServerContext(
133141
ByteBuf encodedKeyBuf = PemReader.readPrivateKey(keyFile);
134142
byte[] encodedKey = new byte[encodedKeyBuf.readableBytes()];
135143
encodedKeyBuf.readBytes(encodedKey).release();
136-
PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(encodedKey);
144+
145+
char[] keyPasswordChars = keyPassword.toCharArray();
146+
PKCS8EncodedKeySpec encodedKeySpec = generateKeySpec(keyPasswordChars, encodedKey);
137147

138148
PrivateKey key;
139149
try {
@@ -145,20 +155,20 @@ public JdkSslServerContext(
145155
List<Certificate> certChain = new ArrayList<Certificate>();
146156
ByteBuf[] certs = PemReader.readCertificates(certChainFile);
147157
try {
148-
for (ByteBuf buf: certs) {
158+
for (ByteBuf buf : certs) {
149159
certChain.add(cf.generateCertificate(new ByteBufInputStream(buf)));
150160
}
151161
} finally {
152-
for (ByteBuf buf: certs) {
162+
for (ByteBuf buf : certs) {
153163
buf.release();
154164
}
155165
}
156166

157-
ks.setKeyEntry("key", key, keyPassword.toCharArray(), certChain.toArray(new Certificate[certChain.size()]));
167+
ks.setKeyEntry("key", key, keyPasswordChars, certChain.toArray(new Certificate[certChain.size()]));
158168

159169
// Set up key manager factory to use our key store
160170
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
161-
kmf.init(ks, keyPassword.toCharArray());
171+
kmf.init(ks, keyPasswordChars);
162172

163173
// Initialize the SSLContext to work with our key managers.
164174
ctx = SSLContext.getInstance(PROTOCOL);
@@ -190,4 +200,36 @@ public List<String> nextProtocols() {
190200
public SSLContext context() {
191201
return ctx;
192202
}
203+
204+
/**
205+
* Generates a key specification for an (encrypted) private key.
206+
*
207+
* @param password characters, if {@code null} or empty an unencrypted key is assumed
208+
* @param key bytes of the DER encoded private key
209+
* @return a key specification
210+
* @throws IOException if parsing {@code key} fails
211+
* @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
212+
* @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown
213+
* @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
214+
* @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt {@code key}
215+
* @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
216+
*/
217+
private static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key) throws IOException,
218+
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
219+
InvalidAlgorithmParameterException {
220+
221+
if (password == null || password.length == 0) {
222+
return new PKCS8EncodedKeySpec(key);
223+
}
224+
225+
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
226+
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
227+
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
228+
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
229+
230+
Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
231+
cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());
232+
233+
return encryptedPrivateKeyInfo.getKeySpec(cipher);
234+
}
193235
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* Copyright 2014 The Netty Project
3+
*
4+
* The Netty Project licenses this file to you under the Apache License,
5+
* version 2.0 (the "License"); you may not use this file except in compliance
6+
* with the License. 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, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations
14+
* under the License.
15+
*/
16+
17+
package io.netty.handler.ssl;
18+
19+
import java.io.File;
20+
21+
import javax.net.ssl.SSLException;
22+
23+
import org.junit.Test;
24+
25+
/**
26+
* Tests for JDK SSL Server Context.
27+
*/
28+
public class JdkSslServerContextTest {
29+
30+
@Test
31+
public void testJdkSslServerWithEncryptedPrivateKey() throws SSLException {
32+
File keyFile = new File(getClass().getResource("netty_test").getFile());
33+
File crtFile = new File(getClass().getResource("netty_test.crt").getFile());
34+
35+
new JdkSslServerContext(crtFile, keyFile, "12345");
36+
}
37+
38+
@Test
39+
public void testJdkSslServerWithUnencryptedPrivateKey() throws SSLException {
40+
File keyFile = new File(getClass().getResource("netty_test_unencrypted").getFile());
41+
File crtFile = new File(getClass().getResource("netty_test.crt").getFile());
42+
43+
new JdkSslServerContext(crtFile, keyFile, "");
44+
new JdkSslServerContext(crtFile, keyFile, null);
45+
}
46+
47+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
-----BEGIN ENCRYPTED PRIVATE KEY-----
2+
MIIE9jAoBgoqhkiG9w0BDAEDMBoEFDBlaUwB8TQ9ImbApCmAyVRTTX+kAgIIAASC
3+
BMhC8QFNyn0VbVp7I+R9Yvmr+Ksl0xZshGg3zaUN8/HRblNSS3gPiP673rmnhcU3
4+
PfSNFR9hOrTqdtd5i6Qq4HznECs81KBlqRNB9ihgy++ByFkf6GTzdfBA6zJInhNx
5+
qSWjUwpFtV4or1w/N23bTcpdGmjfdCSFBMQdbkIDgT7GaWxd3mCLxSbfVzF64tev
6+
x+V22nA/TR0VWnG+aj7aVbReK6VpepiCX7ZmQ5KehXAeB0SDrgT89kcz2VIfDxvE
7+
hkCymNTcJY/ETdPfTSiR+DSZvVJMgVmfk7j1toZZSnoMwl4IhlXmIPmDOUE465l3
8+
sNWLygkNKymTmMI5FTT1hChAIdsmeVTfDmVzNPK4HQi5gfEnTCy0uxj9U3HCZWr1
9+
Zlzmw7/430TRqNYSEJ/XkhFaV5V+6LfeZOyuwf2VJAs+CwNo+UYzEQqkW11JM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LbR+/S3ikTDkYj7J
26+
sktK2ap6vK7u50Jnrt9C/wynVACzGx1tlDVxiVerDmwjfQWL08qCXHlouEdjh9dD
27+
L5XyVlT2FxEXXLRgKGHxFaSQw3Fzzug/o4SgizbNjKffJU5xQlC0aq3WX5+/l3Ic
28+
LWTalgdli3edsR/9RGuu8EsZ11dmNh3csGs=
29+
-----END ENCRYPTED PRIVATE KEY-----
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIC/jCCAeagAwIBAgIIIMONxElm0AIwDQYJKoZIhvcNAQELBQAwPjE8MDoGA1UE
3+
AwwzZThhYzAyZmEwZDY1YTg0MjE5MDE2MDQ1ZGI4YjA1YzQ4NWI0ZWNkZi5uZXR0
4+
eS50ZXN0MCAXDTEzMDgwMjA3NTEzNloYDzk5OTkxMjMxMjM1OTU5WjA+MTwwOgYD
5+
VQQDDDNlOGFjMDJmYTBkNjVhODQyMTkwMTYwNDVkYjhiMDVjNDg1YjRlY2RmLm5l
6+
dHR5LnRlc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDb+HBO3C0U
7+
RBKvDUgJHbhIlBye8X/cbNH3lDq3XOOFBz7L4XZKLDIXS+FeQqSAUMo2otmU+Vkj
8+
0KorshMjbUXfE1KkTijTMJlaga2M2xVVt21fRIkJNWbIL0dWFLWyRq7OXdygyFkI
9+
iW9b2/LYaePBgET22kbtHSCAEj+BlSf265+1rNxyAXBGGGccCKzEbcqASBKHOgVp
10+
6pLqlQAfuSy6g/OzGzces3zXRrGu1N3pBIzAIwCW429n52ZlYfYR0nr+REKDnRrP
11+
IIDsWASmEHhBezTD+v0qCJRyLz2usFgWY+7agUJE2yHHI2mTu2RAFngBilJXlMCt
12+
VwT0xGuQxkbHAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAEv8N7Xm8qaY2FgrOc6P
13+
a1GTgA+AOb3aU33TGwAR86f+nLf6BSPaohcQfOeJid7FkFuYInuXl+oqs+RqM/j8
14+
R0E5BuGYY2wOKpL/PbFi1yf/Kyvft7KVh8e1IUUec/i1DdYTDB0lNWvXXxjfMKGL
15+
ct3GMbEHKvLfHx42Iwz/+fva6LUrO4u2TDfv0ycHuR7UZEuC1DJ4xtFhbpq/QRAj
16+
CyfNx3cDc7L2EtJWnCmivTFA9l8MF1ZPMDSVd4ecQ7B0xZIFQ5cSSFt7WGaJCsGM
17+
zYkU4Fp4IykQcWxdlNX7wJZRwQ2TZJFFglpTiFZdeq6I6Ad9An1Encpz5W8UJ4tv
18+
hmw=
19+
-----END CERTIFICATE-----
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDb+HBO3C0URBKvDUgJHbhIlBye
3+
8X/cbNH3lDq3XOOFBz7L4XZKLDIXS+FeQqSAUMo2otmU+Vkj0KorshMjbUXfE1KkTijTMJlaga2M
4+
2xVVt21fRIkJNWbIL0dWFLWyRq7OXdygyFkIiW9b2/LYaePBgET22kbtHSCAEj+BlSf265+1rNxy
5+
AXBGGGccCKzEbcqASBKHOgVp6pLqlQAfuSy6g/OzGzces3zXRrGu1N3pBIzAIwCW429n52ZlYfYR
6+
0nr+REKDnRrPIIDsWASmEHhBezTD+v0qCJRyLz2usFgWY+7agUJE2yHHI2mTu2RAFngBilJXlMCt
7+
VwT0xGuQxkbHAgMBAAECggEBAJJdKaVfXWNptCDkLnVaYB9y5eRgfppVkhQxfiw5023Vl1QjrgjG
8+
hYH4zHli0IBMwXA/RZWZoFVzZ3dxoshk0iQPgGKxWvrDEJcnSCo8MGL7jPvh52jILp6uzsGZQBji
9+
bTgFPmOBS7ShdgZiQKD9PD2psrmqHZ1yTwjIm5cGfzQM8Y6tjm0xLBn676ecJNdS1TL10y9vmSUM
10+
Ofdkmeg9Z9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