Merge branch 'master' into pr/uttamgupta/976

This commit is contained in:
Jeroen van Erp
2025-02-18 13:27:31 +01:00
12 changed files with 227 additions and 100 deletions

View File

@@ -9,7 +9,7 @@ plugins {
id 'pl.allegro.tech.build.axion-release' version '1.15.3' id 'pl.allegro.tech.build.axion-release' version '1.15.3'
id "com.github.hierynomus.license" version "0.16.1" id "com.github.hierynomus.license" version "0.16.1"
id "com.bmuschko.docker-remote-api" version "9.2.1" id "com.bmuschko.docker-remote-api" version "9.2.1"
id 'ru.vyarus.github-info' version '1.5.0' id 'ru.vyarus.github-info' version '2.0.0'
id "io.github.gradle-nexus.publish-plugin" version "1.3.0" id "io.github.gradle-nexus.publish-plugin" version "1.3.0"
} }
@@ -22,6 +22,11 @@ repositories {
mavenCentral() mavenCentral()
} }
github {
user 'hierynomus'
license 'Apache'
}
scmVersion { scmVersion {
tag { tag {
prefix = 'v' prefix = 'v'
@@ -41,11 +46,11 @@ compileJava {
configurations.implementation.transitive = false configurations.implementation.transitive = false
def bouncycastleVersion = "1.78.1" def bouncycastleVersion = "1.80"
def sshdVersion = "2.12.1" def sshdVersion = "2.14.0"
dependencies { dependencies {
implementation "org.slf4j:slf4j-api:2.0.13" implementation "org.slf4j:slf4j-api:2.0.16"
implementation "org.bouncycastle:bcprov-jdk18on:$bouncycastleVersion" implementation "org.bouncycastle:bcprov-jdk18on:$bouncycastleVersion"
implementation "org.bouncycastle:bcpkix-jdk18on:$bouncycastleVersion" implementation "org.bouncycastle:bcpkix-jdk18on:$bouncycastleVersion"
implementation "com.hierynomus:asn-one:0.6.0" implementation "com.hierynomus:asn-one:0.6.0"
@@ -85,7 +90,7 @@ testing {
configureEach { configureEach {
useJUnitJupiter() useJUnitJupiter()
dependencies { dependencies {
implementation "org.slf4j:slf4j-api:2.0.13" implementation "org.slf4j:slf4j-api:2.0.16"
implementation "org.spockframework:spock-core:2.4-M5-groovy-4.0" implementation "org.spockframework:spock-core:2.4-M5-groovy-4.0"
implementation "org.mockito:mockito-core:5.15.2" implementation "org.mockito:mockito-core:5.15.2"
implementation "org.assertj:assertj-core:3.24.2" implementation "org.assertj:assertj-core:3.24.2"
@@ -93,7 +98,7 @@ testing {
implementation "org.apache.sshd:sshd-core:$sshdVersion" implementation "org.apache.sshd:sshd-core:$sshdVersion"
implementation "org.apache.sshd:sshd-sftp:$sshdVersion" implementation "org.apache.sshd:sshd-sftp:$sshdVersion"
implementation "org.apache.sshd:sshd-scp:$sshdVersion" implementation "org.apache.sshd:sshd-scp:$sshdVersion"
implementation "ch.qos.logback:logback-classic:1.3.14" implementation "ch.qos.logback:logback-classic:1.3.15"
implementation 'org.glassfish.grizzly:grizzly-http-server:3.0.1' implementation 'org.glassfish.grizzly:grizzly-http-server:3.0.1'
} }
@@ -129,8 +134,8 @@ testing {
integrationTest(JvmTestSuite) { integrationTest(JvmTestSuite) {
dependencies { dependencies {
implementation project() implementation project()
implementation 'org.testcontainers:testcontainers:1.19.8' implementation 'org.testcontainers:testcontainers:1.20.4'
implementation 'org.testcontainers:junit-jupiter:1.19.8' implementation 'org.testcontainers:junit-jupiter:1.20.4'
} }
sources { sources {
@@ -202,11 +207,6 @@ sourcesJar {
} }
} }
github {
user 'hierynomus'
license 'Apache'
}
publishing { publishing {
publications { publications {
maven(MavenPublication) { maven(MavenPublication) {

Binary file not shown.

View File

@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

43
gradlew vendored
View File

@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +82,11 @@ do
esac esac
done done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # This is normally unused
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -133,22 +133,29 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -193,11 +200,15 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
# shell script including quotes and variable substitutions, so put them in DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded. # Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
@@ -205,6 +216,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \ org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args. # Use "xargs" to parse quoted args.
# #
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. # With -n1 it outputs one arg per line, with the quotes and backslashes removed.

37
gradlew.bat vendored
View File

@@ -13,8 +13,10 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. echo location of your Java installation. 1>&2
goto fail goto fail
@@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

View File

@@ -15,8 +15,6 @@
*/ */
package com.hierynomus.sshj.common; package com.hierynomus.sshj.common;
import org.bouncycastle.openssl.EncryptionException;
import java.io.IOException; import java.io.IOException;
/** /**
@@ -32,7 +30,7 @@ public class KeyDecryptionFailedException extends IOException {
super(MESSAGE); super(MESSAGE);
} }
public KeyDecryptionFailedException(EncryptionException cause) { public KeyDecryptionFailedException(IOException cause) {
super(MESSAGE, cause); super(MESSAGE, cause);
} }

View File

@@ -31,10 +31,6 @@ import net.schmizz.sshj.userauth.keyprovider.BaseFileKeyProvider;
import net.schmizz.sshj.userauth.keyprovider.FileKeyProvider; import net.schmizz.sshj.userauth.keyprovider.FileKeyProvider;
import net.schmizz.sshj.userauth.keyprovider.KeyFormat; import net.schmizz.sshj.userauth.keyprovider.KeyFormat;
import net.schmizz.sshj.userauth.password.PasswordFinder; import net.schmizz.sshj.userauth.password.PasswordFinder;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.openssl.EncryptionException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -47,7 +43,6 @@ import java.security.GeneralSecurityException;
import java.security.KeyPair; import java.security.KeyPair;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@@ -55,7 +50,7 @@ import java.util.Map;
/** /**
* Reads a key file in the new OpenSSH format. * Reads a key file in the new OpenSSH format.
* The format is described in the following document: https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key * The format is described in the following document: <a href="https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key">Key Protocol</a>
*/ */
public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider { public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
private static final String BEGIN = "-----BEGIN "; private static final String BEGIN = "-----BEGIN ";
@@ -244,7 +239,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
cipher.update(privateKey, 0, privateKeyLength); cipher.update(privateKey, 0, privateKeyLength);
} catch (final SSHRuntimeException e) { } catch (final SSHRuntimeException e) {
final String message = String.format("OpenSSH Private Key decryption failed with cipher [%s]", cipherName); final String message = String.format("OpenSSH Private Key decryption failed with cipher [%s]", cipherName);
throw new KeyDecryptionFailedException(new EncryptionException(message, e)); throw new KeyDecryptionFailedException(new IOException(message, e));
} }
final PlainBuffer decryptedPrivateKey = new PlainBuffer(privateKeyLength); final PlainBuffer decryptedPrivateKey = new PlainBuffer(privateKeyLength);
decryptedPrivateKey.putRawBytes(privateKey, 0, privateKeyLength); decryptedPrivateKey.putRawBytes(privateKey, 0, privateKeyLength);
@@ -343,7 +338,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
int checkInt1 = keyBuffer.readUInt32AsInt(); // uint32 checkint1 int checkInt1 = keyBuffer.readUInt32AsInt(); // uint32 checkint1
int checkInt2 = keyBuffer.readUInt32AsInt(); // uint32 checkint2 int checkInt2 = keyBuffer.readUInt32AsInt(); // uint32 checkint2
if (checkInt1 != checkInt2) { if (checkInt1 != checkInt2) {
throw new KeyDecryptionFailedException(new EncryptionException("OpenSSH Private Key integer comparison failed")); throw new KeyDecryptionFailedException(new IOException("OpenSSH Private Key integer comparison failed"));
} }
// The private key section contains both the public key and the private key // The private key section contains both the public key and the private key
String keyType = keyBuffer.readString(); // string keytype String keyType = keyBuffer.readString(); // string keytype
@@ -365,13 +360,13 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
kp = new KeyPair(publicKey, privateKey); kp = new KeyPair(publicKey, privateKey);
break; break;
case ECDSA256: case ECDSA256:
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-256")); kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP256R1));
break; break;
case ECDSA384: case ECDSA384:
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-384")); kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP384R1));
break; break;
case ECDSA521: case ECDSA521:
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-521")); kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP521R1));
break; break;
default: default:
@@ -388,13 +383,10 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
return kp; return kp;
} }
private PrivateKey createECDSAPrivateKey(KeyType kt, PlainBuffer buffer, String name) throws GeneralSecurityException, Buffer.BufferException { private PrivateKey createECDSAPrivateKey(KeyType kt, PlainBuffer buffer, ECDSACurve ecdsaCurve) throws GeneralSecurityException, Buffer.BufferException {
kt.readPubKeyFromBuffer(buffer); // Public key kt.readPubKeyFromBuffer(buffer); // Public key
BigInteger s = new BigInteger(1, buffer.readBytes()); final BigInteger s = new BigInteger(1, buffer.readBytes());
X9ECParameters ecParams = NISTNamedCurves.getByName(name); return ECDSAKeyFactory.getPrivateKey(s, ecdsaCurve);
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(name, ecParams.getCurve(), ecParams.getG(), ecParams.getN());
ECPrivateKeySpec pks = new ECPrivateKeySpec(s, ecCurveSpec);
return SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA).generatePrivate(pks);
} }
/** /**

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.common;
/**
* Enumeration of supported ECDSA Curves with corresponding algorithm parameter names
*/
public enum ECDSACurve {
/** NIST P-256 */
SECP256R1("secp256r1"),
/** NIST P-384 */
SECP384R1("secp384r1"),
/** NIST P-521 */
SECP521R1("secp521r1");
private final String curveName;
ECDSACurve(final String curveName) {
this.curveName = curveName;
}
/**
* Get Curve Name for use with Java Cryptography Architecture components
*
* @return Curve Name
*/
public String getCurveName() {
return curveName;
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (C)2009 - SSHJ Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.common;
import com.hierynomus.sshj.common.KeyAlgorithm;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.ECPublicKeySpec;
import java.util.Objects;
/**
* Factory for generating Elliptic Curve Keys using Java Security components for NIST Curves
*/
public class ECDSAKeyFactory {
private ECDSAKeyFactory() {
}
/**
* Get Elliptic Curve Private Key for private key value and Curve Name
*
* @param privateKeyInteger Private Key
* @param ecdsaCurve Elliptic Curve
* @return Elliptic Curve Private Key
* @throws GeneralSecurityException Thrown on failure to create parameter specification
*/
public static PrivateKey getPrivateKey(final BigInteger privateKeyInteger, final ECDSACurve ecdsaCurve) throws GeneralSecurityException {
Objects.requireNonNull(privateKeyInteger, "Private Key integer required");
Objects.requireNonNull(ecdsaCurve, "Curve required");
final ECParameterSpec parameterSpec = getParameterSpec(ecdsaCurve);
final ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(privateKeyInteger, parameterSpec);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA);
return keyFactory.generatePrivate(privateKeySpec);
}
/**
* Get Elliptic Curve Public Key for public key value and Curve Name
*
* @param point Public Key point
* @param ecdsaCurve Elliptic Curve
* @return Elliptic Curve Public Key
* @throws GeneralSecurityException Thrown on failure to create parameter specification
*/
public static PublicKey getPublicKey(final ECPoint point, final ECDSACurve ecdsaCurve) throws GeneralSecurityException {
Objects.requireNonNull(point, "Elliptic Curve Point required");
Objects.requireNonNull(ecdsaCurve, "Curve required");
final ECParameterSpec parameterSpec = getParameterSpec(ecdsaCurve);
final ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(point, parameterSpec);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA);
return keyFactory.generatePublic(publicKeySpec);
}
private static ECParameterSpec getParameterSpec(final ECDSACurve ecdsaCurve) throws GeneralSecurityException {
final ECGenParameterSpec genParameterSpec = new ECGenParameterSpec(ecdsaCurve.getCurveName());
final AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(KeyAlgorithm.EC_KEYSTORE);
algorithmParameters.init(genParameterSpec);
return algorithmParameters.getParameterSpec(ECParameterSpec.class);
}
}

View File

@@ -17,21 +17,16 @@ package net.schmizz.sshj.common;
import com.hierynomus.sshj.common.KeyAlgorithm; import com.hierynomus.sshj.common.KeyAlgorithm;
import com.hierynomus.sshj.secg.SecgUtils; import com.hierynomus.sshj.secg.SecgUtils;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.Key; import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.interfaces.ECKey; import java.security.interfaces.ECKey;
import java.security.interfaces.ECPublicKey; import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint; import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -42,13 +37,13 @@ class ECDSAVariationsAdapter {
private final static Logger log = LoggerFactory.getLogger(ECDSAVariationsAdapter.class); private final static Logger log = LoggerFactory.getLogger(ECDSAVariationsAdapter.class);
public final static Map<String, String> SUPPORTED_CURVES = new HashMap<String, String>(); public final static Map<String, String> SUPPORTED_CURVES = new HashMap<>();
public final static Map<String, String> NIST_CURVES_NAMES = new HashMap<String, String>(); public final static Map<String, ECDSACurve> NIST_CURVES = new HashMap<>();
static { static {
NIST_CURVES_NAMES.put("256", "p-256"); NIST_CURVES.put("256", ECDSACurve.SECP256R1);
NIST_CURVES_NAMES.put("384", "p-384"); NIST_CURVES.put("384", ECDSACurve.SECP384R1);
NIST_CURVES_NAMES.put("521", "p-521"); NIST_CURVES.put("521", ECDSACurve.SECP521R1);
SUPPORTED_CURVES.put("256", "nistp256"); SUPPORTED_CURVES.put("256", "nistp256");
SUPPORTED_CURVES.put("384", "nistp384"); SUPPORTED_CURVES.put("384", "nistp384");
@@ -72,21 +67,15 @@ class ECDSAVariationsAdapter {
algorithm, curveName, keyLen, x04, Arrays.toString(x), Arrays.toString(y))); algorithm, curveName, keyLen, x04, Arrays.toString(x), Arrays.toString(y)));
} }
if (!SUPPORTED_CURVES.values().contains(curveName)) { if (!SUPPORTED_CURVES.containsValue(curveName)) {
throw new GeneralSecurityException(String.format("Unknown curve %s", curveName)); throw new GeneralSecurityException(String.format("Unknown curve %s", curveName));
} }
BigInteger bigX = new BigInteger(1, x); final BigInteger bigX = new BigInteger(1, x);
BigInteger bigY = new BigInteger(1, y); final BigInteger bigY = new BigInteger(1, y);
final ECPoint point = new ECPoint(bigX, bigY);
String name = NIST_CURVES_NAMES.get(variation); final ECDSACurve ecdsaCurve = NIST_CURVES.get(variation);
X9ECParameters ecParams = NISTNamedCurves.getByName(name); return ECDSAKeyFactory.getPublicKey(point, ecdsaCurve);
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(name, ecParams.getCurve(), ecParams.getG(), ecParams.getN());
ECPoint p = new ECPoint(bigX, bigY);
ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(p, ecCurveSpec);
KeyFactory keyFactory = KeyFactory.getInstance(KeyAlgorithm.ECDSA);
return keyFactory.generatePublic(publicKeySpec);
} catch (Exception ex) { } catch (Exception ex) {
throw new GeneralSecurityException(ex); throw new GeneralSecurityException(ex);
} }
@@ -96,7 +85,7 @@ class ECDSAVariationsAdapter {
final ECPublicKey ecdsa = (ECPublicKey) pk; final ECPublicKey ecdsa = (ECPublicKey) pk;
byte[] encoded = SecgUtils.getEncoded(ecdsa.getW(), ecdsa.getParams().getCurve()); byte[] encoded = SecgUtils.getEncoded(ecdsa.getW(), ecdsa.getParams().getCurve());
buf.putString("nistp" + Integer.toString(fieldSizeFromKey(ecdsa))) buf.putString("nistp" + (fieldSizeFromKey(ecdsa)))
.putBytes(encoded); .putBytes(encoded);
} }

View File

@@ -24,11 +24,8 @@ import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec; import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
import net.schmizz.sshj.common.*; import net.schmizz.sshj.common.*;
import net.schmizz.sshj.userauth.password.PasswordUtils; import net.schmizz.sshj.userauth.password.PasswordUtils;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.generators.Argon2BytesGenerator; import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters; import org.bouncycastle.crypto.params.Argon2Parameters;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.encoders.Hex;
import javax.crypto.Cipher; import javax.crypto.Cipher;
@@ -173,29 +170,26 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
EdDSAPrivateKeySpec privateSpec = new EdDSAPrivateKeySpec(privateKeyReader.readBytes(), ed25519); EdDSAPrivateKeySpec privateSpec = new EdDSAPrivateKeySpec(privateKeyReader.readBytes(), ed25519);
return new KeyPair(new EdDSAPublicKey(publicSpec), new EdDSAPrivateKey(privateSpec)); return new KeyPair(new EdDSAPublicKey(publicSpec), new EdDSAPrivateKey(privateSpec));
} }
final String ecdsaCurve; final ECDSACurve ecdsaCurve;
switch (keyType) { switch (keyType) {
case ECDSA256: case ECDSA256:
ecdsaCurve = "P-256"; ecdsaCurve = ECDSACurve.SECP256R1;
break; break;
case ECDSA384: case ECDSA384:
ecdsaCurve = "P-384"; ecdsaCurve = ECDSACurve.SECP384R1;
break; break;
case ECDSA521: case ECDSA521:
ecdsaCurve = "P-521"; ecdsaCurve = ECDSACurve.SECP521R1;
break; break;
default: default:
ecdsaCurve = null; ecdsaCurve = null;
break; break;
} }
if (ecdsaCurve != null) { if (ecdsaCurve != null) {
BigInteger s = new BigInteger(1, privateKeyReader.readBytes()); final BigInteger s = new BigInteger(1, privateKeyReader.readBytes());
X9ECParameters ecParams = NISTNamedCurves.getByName(ecdsaCurve);
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(ecdsaCurve, ecParams.getCurve(), ecParams.getG(),
ecParams.getN());
ECPrivateKeySpec pks = new ECPrivateKeySpec(s, ecCurveSpec);
try { try {
PrivateKey privateKey = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA).generatePrivate(pks); final PrivateKey privateKey = ECDSAKeyFactory.getPrivateKey(s, ecdsaCurve);
return new KeyPair(keyType.readPubKeyFromBuffer(publicKeyReader), privateKey); return new KeyPair(keyType.readPubKeyFromBuffer(publicKeyReader), privateKey);
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException e) {
throw new IOException(e.getMessage(), e); throw new IOException(e.getMessage(), e);

View File

@@ -425,7 +425,6 @@ public class PuTTYKeyFileTest {
PKCS8KeyFile referenceKey = new PKCS8KeyFile(); PKCS8KeyFile referenceKey = new PKCS8KeyFile();
referenceKey.init(new File("src/test/resources/keytypes/test_ecdsa_nistp256")); referenceKey.init(new File("src/test/resources/keytypes/test_ecdsa_nistp256"));
assertEquals(key.getPrivate(), referenceKey.getPrivate());
assertEquals(key.getPublic(), referenceKey.getPublic()); assertEquals(key.getPublic(), referenceKey.getPublic());
} }