Throw IOE instead of NPE if OpenSSHKeyV1KeyFile reads an empty file (#773)

There is a contract that FileKeyProvider.readKey throws an IOException if something goes wrong. Throwing an NPE is not expected by API users. Also, it is much more difficult to find out if the NPE is thrown due to a broken key file, or due to an internal bug.
This commit is contained in:
Vladimir Lagunov
2022-04-01 14:41:48 +07:00
committed by GitHub
parent 69812e9a81
commit e9cb90901c
2 changed files with 12 additions and 0 deletions

View File

@@ -218,6 +218,9 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
while (line != null && !line.startsWith(BEGIN)) {
line = reader.readLine();
}
if (line == null) {
return false;
}
line = line.substring(BEGIN.length());
return line.startsWith(OPENSSH_PRIVATE_KEY);
}

View File

@@ -39,6 +39,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
@@ -443,6 +444,14 @@ public class OpenSSHKeyFileTest {
corruptedKeyFile.getPublic());
}
@Test
public void emptyPrivateKey() {
FileKeyProvider keyProvider = new OpenSSHKeyV1KeyFile();
keyProvider.init(new StringReader(""));
assertThrows("This key is not in 'openssh-key-v1' format", IOException.class, keyProvider::getPrivate);
}
@Before
public void checkBCRegistration() {
if (!SecurityUtils.isBouncyCastleRegistered()) {