Skip to content

Commit e9cb909

Browse files
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.
1 parent 69812e9 commit e9cb909

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

src/main/java/com/hierynomus/sshj/userauth/keyprovider/OpenSSHKeyV1KeyFile.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,9 @@ private boolean checkHeader(final BufferedReader reader) throws IOException {
218218
while (line != null && !line.startsWith(BEGIN)) {
219219
line = reader.readLine();
220220
}
221+
if (line == null) {
222+
return false;
223+
}
221224
line = line.substring(BEGIN.length());
222225
return line.startsWith(OPENSSH_PRIVATE_KEY);
223226
}

src/test/java/net/schmizz/sshj/keyprovider/OpenSSHKeyFileTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import java.io.IOException;
4040
import java.io.InputStreamReader;
4141
import java.io.OutputStreamWriter;
42+
import java.io.StringReader;
4243
import java.math.BigInteger;
4344
import java.security.GeneralSecurityException;
4445
import java.security.PrivateKey;
@@ -443,6 +444,14 @@ public void notTrimmedKeys() throws IOException {
443444
corruptedKeyFile.getPublic());
444445
}
445446

447+
@Test
448+
public void emptyPrivateKey() {
449+
FileKeyProvider keyProvider = new OpenSSHKeyV1KeyFile();
450+
keyProvider.init(new StringReader(""));
451+
452+
assertThrows("This key is not in 'openssh-key-v1' format", IOException.class, keyProvider::getPrivate);
453+
}
454+
446455
@Before
447456
public void checkBCRegistration() {
448457
if (!SecurityUtils.isBouncyCastleRegistered()) {

0 commit comments

Comments
 (0)