Skip to content

Commit

Permalink
refactor: Clean up loading of reading of keydata file in LazyKeyManag…
Browse files Browse the repository at this point in the history
…er (#1372)
  • Loading branch information
sehrope authored and davecramer committed Dec 11, 2018
1 parent bac4bc1 commit 9b45e70
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions pgjdbc/src/main/java/org/postgresql/ssl/LazyKeyManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
Expand Down Expand Up @@ -160,9 +159,19 @@ public String[] getClientAliases(String keyType, Principal[] issuers) {
return (alias == null ? new String[]{} : new String[]{alias});
}

private static byte[] readFileFully(String path) throws IOException {
RandomAccessFile raf = new RandomAccessFile(path, "r");
try {
byte[] ret = new byte[(int) raf.length()];
raf.readFully(ret);
return ret;
} finally {
raf.close();
}
}

@Override
public PrivateKey getPrivateKey(String alias) {
RandomAccessFile raf = null;
try {
if (key == null && keyfile != null) {
// If keyfile is null, we do not load the key
Expand All @@ -173,19 +182,16 @@ public PrivateKey getPrivateKey(String alias) {
}
}

byte[] keydata;
try {
raf = new RandomAccessFile(new File(keyfile), "r"); // NOSONAR
keydata = readFileFully(keyfile);
} catch (FileNotFoundException ex) {
if (!defaultfile) {
// It is not an error if there is no file at the default location
throw ex;
}
return null;
}
byte[] keydata = new byte[(int) raf.length()];
raf.readFully(keydata);
raf.close();
raf = null;

KeyFactory kf = KeyFactory.getInstance(cert[0].getPublicKey().getAlgorithm());
try {
Expand Down Expand Up @@ -241,13 +247,6 @@ public PrivateKey getPrivateKey(String alias) {
}
}
} catch (IOException ioex) {
if (raf != null) {
try {
raf.close();
} catch (IOException ex) {
}
}

error = new PSQLException(GT.tr("Could not read SSL key file {0}.", keyfile),
PSQLState.CONNECTION_FAILURE, ioex);
} catch (NoSuchAlgorithmException ex) {
Expand Down

0 comments on commit 9b45e70

Please sign in to comment.