Skip to content

Commit

Permalink
PemPrivateKey.toPem(...) should throw IllegalArgumentException when P… (
Browse files Browse the repository at this point in the history
netty#8253)

* PemPrivateKey.toPem(...) should throw IllegalArgumentException when PrivateKey which does not support encoding is used.

Motivation:

At the moment when a PrivateKey is used that does not support encoding we throw a NPE when trying to convert the key. We should better throw an IllegalArgumentException with the details about what key we tried to encode.

Modifications:

- Check if PrivateKey.getEncoded() returns null and if so throw an IllegalArgumentException
- Add unit test.

Result:

Better handling of non-supported PrivateKey implementations.
  • Loading branch information
normanmaurer authored Sep 5, 2018
1 parent 02d559e commit 5ff6b57
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,12 @@ static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect, PrivateKe
return ((PemEncoded) key).retain();
}

ByteBuf encoded = Unpooled.wrappedBuffer(key.getEncoded());
byte[] bytes = key.getEncoded();
if (bytes == null) {
throw new IllegalArgumentException(key.getClass().getName() + " does not support encoding");
}

ByteBuf encoded = Unpooled.wrappedBuffer(bytes);
try {
ByteBuf base64 = SslUtils.toBase64(allocator, encoded);
try {
Expand Down
23 changes: 23 additions & 0 deletions handler/src/test/java/io/netty/handler/ssl/PemEncodedTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.PrivateKey;

import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import org.junit.Test;

import io.netty.handler.ssl.util.SelfSignedCertificate;
Expand Down Expand Up @@ -69,6 +72,26 @@ private static void testPemEncoded(SslProvider provider) throws Exception {
}
}

@Test(expected = IllegalArgumentException.class)
public void testEncodedReturnsNull() throws Exception {
PemPrivateKey.toPEM(UnpooledByteBufAllocator.DEFAULT, true, new PrivateKey() {
@Override
public String getAlgorithm() {
return null;
}

@Override
public String getFormat() {
return null;
}

@Override
public byte[] getEncoded() {
return null;
}
});
}

private static void assertRelease(PemEncoded encoded) {
assertTrue(encoded.release());
}
Expand Down

0 comments on commit 5ff6b57

Please sign in to comment.