use of net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile in project agileway by fangjinuo.
the class SshjConnection method authenticateWithPublicKey.
@Override
public boolean authenticateWithPublicKey(String user, byte[] pemPrivateKey, String passphrase) throws SshException {
Preconditions.checkNotNull(sshClient);
String keyContent = new String(pemPrivateKey);
List<KeyProvider> keyProviders = Collects.emptyArrayList();
PasswordFinder passwordFinder = null;
if (Strings.isNotBlank(passphrase)) {
passwordFinder = PasswordUtils.createOneOff(passphrase.toCharArray());
}
try {
StringReader reader = new StringReader(keyContent);
PuTTYKeyFile puTTYKeyFile = new PuTTYKeyFile();
if (passwordFinder == null) {
puTTYKeyFile.init(reader);
} else {
puTTYKeyFile.init(reader, passwordFinder);
}
puTTYKeyFile.getPrivate();
keyProviders.add(puTTYKeyFile);
} catch (Throwable ex) {
// ignore it
}
try {
StringReader reader = new StringReader(keyContent);
PKCS8KeyFile pkcs8KeyFile = new PKCS8KeyFile();
if (passwordFinder == null) {
pkcs8KeyFile.init(reader);
} else {
pkcs8KeyFile.init(reader, passwordFinder);
}
pkcs8KeyFile.getPrivate();
keyProviders.add(pkcs8KeyFile);
} catch (Throwable ex) {
// ignore it
}
try {
StringReader reader = new StringReader(keyContent);
OpenSSHKeyFile openSSHKeyFile = new OpenSSHKeyFile();
if (passwordFinder == null) {
openSSHKeyFile.init(reader);
} else {
openSSHKeyFile.init(reader, passwordFinder);
}
openSSHKeyFile.getPrivate();
keyProviders.add(openSSHKeyFile);
} catch (Throwable ex) {
// ignore it
}
try {
Preconditions.checkState(!keyProviders.isEmpty(), "the private key is invalid: " + keyContent);
sshClient.authPublickey(user, keyProviders);
} catch (UserAuthException ex) {
logger.error(ex.getMessage(), ex);
return false;
} catch (Throwable ex) {
throw new SshException(ex);
}
return false;
}
Aggregations