Skip to content

Instantly share code, notes, and snippets.

@markscottwright
Last active September 30, 2022 14:13
Show Gist options
  • Save markscottwright/dfb640e27789ab1fc186818766f43e67 to your computer and use it in GitHub Desktop.
Save markscottwright/dfb640e27789ab1fc186818766f43e67 to your computer and use it in GitHub Desktop.
How to parse a ssh public key file. Only supports RSA keys right now.
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class SshKeyReader {
public static Map<String, PublicKey> read(File publicKeyFile)
throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
HashMap<String, PublicKey> out = new HashMap<>();
for (String line : Files.readAllLines(publicKeyFile.toPath())) {
String[] fields = line.split(" +");
if (fields.length != 3)
continue;
byte[] decoded = Base64.getDecoder().decode(fields[1]);
DataInputStream keyParser = new DataInputStream(new ByteArrayInputStream(decoded));
byte[] typeStringBytes = new byte[keyParser.readInt()];
keyParser.read(typeStringBytes);
String typeString = new String(typeStringBytes);
if (typeString.equals("ssh-rsa")) {
byte[] exponentBytes = new byte[keyParser.readInt()];
keyParser.read(exponentBytes);
byte[] modulusBytes = new byte[keyParser.readInt()];
keyParser.read(modulusBytes);
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(modulusBytes),
new BigInteger(exponentBytes));
out.put(fields[2], KeyFactory.getInstance("RSA").generatePublic(spec));
}
}
return out;
}
public static void main(String[] args)
throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
System.out.println(read(new File("test-rsa.pub")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment