Skip to content

Commit

Permalink
Throw IOE instead of NPE if OpenSSHKeyV1KeyFile reads an empty file
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
vladimirlagunov committed Mar 16, 2022
1 parent 69812e9 commit 1980072
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ private boolean checkHeader(final BufferedReader reader) throws IOException {
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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
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;
Expand Down Expand Up @@ -443,6 +444,14 @@ public void notTrimmedKeys() throws IOException {
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()) {
Expand Down

0 comments on commit 1980072

Please sign in to comment.