PemPrivateKey.toPem(...) should throw IllegalArgumentException when P… (#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.
This commit is contained in:
Norman Maurer 2018-09-05 20:33:40 +02:00 committed by GitHub
parent 02d559e6a4
commit 5ff6b57940
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 1 deletions

View File

@ -60,7 +60,12 @@ public final class PemPrivateKey extends AbstractReferenceCounted implements Pri
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 {

View File

@ -24,7 +24,10 @@ import static org.junit.Assume.assumeTrue;
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;
@ -69,6 +72,26 @@ public class PemEncodedTest {
}
}
@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());
}