Compare commits

...

20 Commits

Author SHA1 Message Date
David Kocher
4be5228a4d Ensure reset of security provider preference. (#1013)
Some checks failed
Build SSHJ / Build with Java 11 (push) Has been cancelled
Build SSHJ / Integration test (push) Has been cancelled
2025-05-14 16:05:06 +02:00
Jeroen van Erp
1398b190ec Prepare release 0.39.0
Some checks failed
Build SSHJ / Build with Java 11 (push) Has been cancelled
Build SSHJ / Integration test (push) Has been cancelled
2025-05-13 11:33:00 +02:00
Jeroen van Erp
acad163e50 Reduce code duplication
Some checks failed
Build SSHJ / Build with Java 11 (push) Has been cancelled
Build SSHJ / Integration test (push) Has been cancelled
Signed-off-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-04-22 14:36:09 +02:00
Jeroen van Erp
8e9e644bb8 Merge branch 'master' into pr/uttamgupta/976
Signed-off-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-04-22 14:35:35 +02:00
David Handermann
857d56a679 Replaced Grizzly HTTP Server with Java HTTP Server (#1010)
Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-04-22 11:59:58 +02:00
David Handermann
0e4a8f675f Upgraded SSHD from 2.14.0 to 2.15.0 (#1009) 2025-04-22 09:53:03 +02:00
Dmitry Sulman
95aab0088e Upgrade dependencies (#1007)
Some checks failed
Build SSHJ / Build with Java 11 (push) Has been cancelled
Build SSHJ / Integration test (push) Has been cancelled
- Upgrade Gradle to 8.13
- Upgrade SLF4J to 2.0.17
- Upgrade Mockito to 5.16.1
- Upgrade AssertJ to 3.27.3
- Upgrade Logback to 1.5.18
- Upgrade Testcontainers to 1.20.6

Signed-off-by: Dmitry Sulman <dmitry.sulman@gmail.com>
2025-03-24 14:10:44 +01:00
David Handermann
e390394e3b Refactored PuTTY Secret Key Derivation (#1003)
Some checks failed
Build SSHJ / Build with Java 11 (push) Has been cancelled
Build SSHJ / Integration test (push) Has been cancelled
- Added KeyDerivationFunction interface for PuTTY Key Files
- Moved Argon2 Key Derivation to Version 3 implementation class to separate Bouncy Castle dependency references
- Replaced Bouncy Castle Hex references with ByteArrayUtils

Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-19 22:40:00 +01:00
Simon Legner
995de2da99 Make private fields final (#1005) 2025-03-19 22:18:17 +01:00
David Handermann
cea67fef73 Removed eddsa library in favor of standard Java Security classes (#993)
Some checks are pending
Build SSHJ / Build with Java 11 (push) Waiting to run
Build SSHJ / Integration test (push) Waiting to run
- Bouncy Castle provides Ed25519 support using standard Java Security classes
- Removed net.i2p.crypto:eddsa:0.3.0 dependency
- Removed Ed25519PublicKey extension of EdDSAPublicKey class from eddsa library
- Added Ed25519KeyFactory for generating Java PublicKey and PrivateKey objects from raw encoded key byte arrays
- Refactored key parsing to use Ed25519KeyFactory
- Refactored SignatureEdDSA to use Java Signature class with Ed25519

Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-19 13:42:06 +01:00
David Handermann
b4bc69626e Refactored PKCS8 and PEM key parsing to reduce use of Bouncy Castle (#989)
- Replaced Bouncy Castle PKCS8 parsing with Java Security components and hierynomus ASN.1
- Added PEMKeyReader with separate implementation for historical OpenSSL password-based encryption using Bouncy Castle components
- Added class-based detection of support for historical encryption for optional use of Bouncy Castle components

Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-19 10:55:56 +01:00
David Handermann
27bf52ec10 Removed Bouncy Castle usage from Tests (#984)
- Removed unnecessary addition of Bouncy Castle Provider from several tests
- Replaced Bouncy Castle Hex.toHexString() with SSHD BufferUtils.toHex()

Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-19 09:46:09 +01:00
Simon Legner
11921e2d3a Use try-with-resources (#999)
Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-19 09:30:01 +01:00
Simon Legner
4fe605289b Fix typo "default" (#997)
Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-19 09:19:26 +01:00
Simon Legner
0816bf95af Use StandardCharsets.UTF_8 (Java 1.7) (#998)
Some checks are pending
Build SSHJ / Build with Java 11 (push) Waiting to run
Build SSHJ / Integration test (push) Waiting to run
Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-18 21:44:31 +01:00
Henning Pöttker
b886085da5 Add empty data to SSH_MSG_IGNORE messages (#974)
As required by RFC 4253 Section 11.2, and RFC 4251 Section 5

Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-03-18 21:33:12 +01:00
Jeroen van Erp
c3236a7405 Merge branch 'master' into pr/uttamgupta/976 2025-02-18 13:27:31 +01:00
David Handermann
7f8f43c8ae Upgrade Gradle to 8.12.1 and other dependencies (#982)
Some checks failed
Build SSHJ / Build with Java 11 (push) Has been cancelled
Build SSHJ / Integration test (push) Has been cancelled
* Upgraded Gradle to 8.12.1 and other dependencies

- Upgraded Bouncy Castle from 1.78.1 to 1.80
- Upgraded Apache SSHD from 2.12.1 to 2.14.0
- Upgraded SLF4J from 2.0.13 to 2.0.16
- Upgraded Logback from 1.3.14 to 1.3.15
- Upgraded Testcontainers from 1.19.8 to 1.20.4

* Upgraded github-info plugin from 1.5.0 to 2.0.0

* Upgraded Gradle Wrapper scripts for 8.12.1

---------

Co-authored-by: Jeroen van Erp <jeroen@hierynomus.com>
2025-02-18 11:32:14 +01:00
David Handermann
5ff27ec597 Refactored ECDSA Key Handling using Java Security (#983)
- Replaced Bouncy Castle with Java Security components for ECDSA Key Specifications
2025-02-18 11:01:33 +01:00
Uttam Gupta
bfa82b4e44 Issue-973 (part1) - Removing direct dependency on BouncyCastle library and using JCE.
- This is first change towards removing direct dependency on BouncyCastle.
- Removed the imports org.bouncycastle.crypto.prng.RandomGenerator and
  org.bouncycastle.crypto.prng.VMPCRandomGenerator from the file
  BouncyCastleRandom.java, eliminating the direct dependency on BouncyCastle.
  Now using JCE with a provider, allowing SecureRandom to utilize the BC provider.
- Added a new class, BouncyCastleFipsRandom, similar to BouncyCastleRandom.java,
  which leverages the BCFIPS provider to create SecureRandom instances.
- Upgraded gradle plugin, groovy and Mockito versions to ensure compatibility with Java 21.
  from org.spockframework:spock-core:2.3-groovy-3.0 to org.spockframework:spock-core:2.4-M5-groovy-4.0
  from org.mockito:mockito-core:4.11.0 to org.mockito:mockito-core:5.15.2
  from gradle-8.2-bin.zip to gradle-8.11-bin.zip
 Testing: I have run gradle clean build with java 11 and Java 21 and works.
Test Gradle Test Executor 2; Executed: 470/469/0
✓ Test Gradle Test Run :test; Executed: 470/469/0
2025-01-13 14:54:54 -08:00
85 changed files with 1717 additions and 988 deletions

View File

@@ -110,6 +110,18 @@ Issue tracker: https://github.com/hierynomus/sshj/issues
Fork away!
== Release history
SSHJ 0.39.0 (2024-02-20)::
* Upgraded dependencies
* Remove hard dependencies on BouncyCastle, making it optional.
* Merged https://github.com/hierynomus/sshj/pull/993[#993]: Remove EDDSA dependency
* Merged https://github.com/hierynomus/sshj/pull/959[#959]: Improve Curve25519 public key handling
* Merged https://github.com/hierynomus/sshj/pull/911[#911]: Fix for bad packet received with heartbeat enabled
* Merged https://github.com/hierynomus/sshj/pull/926[#926]: Close session when closing SFTP client
* Merged https://github.com/hierynomus/sshj/pull/928[#928]: Improve file-listing performance
* Merged https://github.com/hierynomus/sshj/pull/934[#934]: Don't send keep-alive before KEX done
* Merged https://github.com/hierynomus/sshj/pull/936[#936]: Improve Base64 decoding error handling
* Merged https://github.com/hierynomus/sshj/pull/925[#925]: Allow passing connected sockets
* Merged https://github.com/hierynomus/sshj/pull/922[#922]: Fix bug in known_hosts parsing
SSHJ 0.38.0 (2024-01-02)::
* Mitigated CVE-2023-48795 - Terrapin
* Merged https://github.com/hierynomus/sshj/pull/917[#917]: Implement OpenSSH strict key exchange extension

View File

@@ -9,7 +9,7 @@ plugins {
id 'pl.allegro.tech.build.axion-release' version '1.15.3'
id "com.github.hierynomus.license" version "0.16.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"
}
@@ -22,6 +22,11 @@ repositories {
mavenCentral()
}
github {
user 'hierynomus'
license 'Apache'
}
scmVersion {
tag {
prefix = 'v'
@@ -41,15 +46,14 @@ compileJava {
configurations.implementation.transitive = false
def bouncycastleVersion = "1.78.1"
def sshdVersion = "2.12.1"
def bouncycastleVersion = "1.80"
def sshdVersion = "2.15.0"
dependencies {
implementation "org.slf4j:slf4j-api:2.0.13"
implementation "org.slf4j:slf4j-api:2.0.17"
implementation "org.bouncycastle:bcprov-jdk18on:$bouncycastleVersion"
implementation "org.bouncycastle:bcpkix-jdk18on:$bouncycastleVersion"
implementation "com.hierynomus:asn-one:0.6.0"
implementation "net.i2p.crypto:eddsa:0.3.0"
}
license {
@@ -85,16 +89,15 @@ testing {
configureEach {
useJUnitJupiter()
dependencies {
implementation "org.slf4j:slf4j-api:2.0.13"
implementation "org.slf4j:slf4j-api:2.0.17"
implementation 'org.spockframework:spock-core:2.3-groovy-3.0'
implementation "org.mockito:mockito-core:4.11.0"
implementation "org.assertj:assertj-core:3.24.2"
implementation "org.mockito:mockito-core:5.16.1"
implementation "org.assertj:assertj-core:3.27.3"
implementation "ru.vyarus:spock-junit5:1.2.0"
implementation "org.apache.sshd:sshd-core:$sshdVersion"
implementation "org.apache.sshd:sshd-sftp:$sshdVersion"
implementation "org.apache.sshd:sshd-scp:$sshdVersion"
implementation "ch.qos.logback:logback-classic:1.3.14"
implementation 'org.glassfish.grizzly:grizzly-http-server:3.0.1'
implementation "ch.qos.logback:logback-classic:1.5.18"
}
targets {
@@ -129,8 +132,8 @@ testing {
integrationTest(JvmTestSuite) {
dependencies {
implementation project()
implementation 'org.testcontainers:testcontainers:1.19.8'
implementation 'org.testcontainers:junit-jupiter:1.19.8'
implementation platform('org.testcontainers:testcontainers-bom:1.20.6')
implementation 'org.testcontainers:junit-jupiter'
}
sources {
@@ -177,8 +180,6 @@ jar {
instruction "Import-Package", "!net.schmizz.*"
instruction "Import-Package", "!com.hierynomus.sshj.*"
instruction "Import-Package", "javax.crypto*"
instruction "Import-Package", "!net.i2p.crypto.eddsa.math"
instruction "Import-Package", "net.i2p*"
instruction "Import-Package", "com.jcraft.jzlib*;version=\"[1.1,2)\";resolution:=optional"
instruction "Import-Package", "org.slf4j*;version=\"[1.7,5)\""
instruction "Import-Package", "org.bouncycastle*;resolution:=optional"
@@ -202,11 +203,6 @@ sourcesJar {
}
}
github {
user 'hierynomus'
license 'Apache'
}
publishing {
publications {
maven(MavenPublication) {

Binary file not shown.

View File

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

43
gradlew vendored
View File

@@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@@ -55,7 +57,7 @@
# Darwin, MinGW, and NonStop.
#
# (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.
#
# You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +82,11 @@ do
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -133,22 +133,29 @@ location of your Java installation."
fi
else
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
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
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 ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | 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" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -193,11 +200,15 @@ if "$cygwin" || "$msys" ; then
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# 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 -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
@@ -205,6 +216,12 @@ set -- \
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.
#
# 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 limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@@ -25,7 +27,8 @@
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -56,11 +59,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -75,13 +78,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal

View File

@@ -21,7 +21,6 @@ import java.util.EnumSet;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.shaded.org.bouncycastle.util.Arrays;
import com.hierynomus.sshj.SshdContainer;
@@ -31,11 +30,12 @@ import net.schmizz.sshj.sftp.RemoteFile;
import net.schmizz.sshj.sftp.SFTPClient;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
@Testcontainers
public class FileWriteTest {
@Container
private static SshdContainer sshd = new SshdContainer();
private static final SshdContainer sshd = new SshdContainer();
@Test
public void shouldAppendToFile_GH390() throws Throwable {
@@ -63,8 +63,14 @@ public class FileWriteTest {
try (RemoteFile read = sftp.open(file, EnumSet.of(OpenMode.READ))) {
byte[] readBytes = new byte[initialText.length + appendText.length];
read.read(0, readBytes, 0, readBytes.length);
assertThat(Arrays.copyOfRange(readBytes, 0, initialText.length)).isEqualTo(initialText);
assertThat(Arrays.copyOfRange(readBytes, initialText.length, initialText.length + appendText.length)).isEqualTo(appendText);
final byte[] expectedInitialText = new byte[initialText.length];
System.arraycopy(readBytes, 0, expectedInitialText, 0, expectedInitialText.length);
assertArrayEquals(expectedInitialText, initialText);
final byte[] expectedAppendText = new byte[appendText.length];
System.arraycopy(readBytes, initialText.length, expectedAppendText, 0, expectedAppendText.length);
assertArrayEquals(expectedAppendText, appendText);
}
}

View File

@@ -145,7 +145,7 @@ class StrictKeyExchangeTest {
@Override
protected void doKeepAlive() throws TransportException {
conn.getTransport().write(new SSHPacket(Message.IGNORE));
conn.getTransport().write(new SSHPacket(Message.IGNORE).putString(""));
}
}

View File

@@ -15,8 +15,6 @@
*/
package com.hierynomus.sshj.common;
import org.bouncycastle.openssl.EncryptionException;
import java.io.IOException;
/**
@@ -28,11 +26,15 @@ public class KeyDecryptionFailedException extends IOException {
public static final String MESSAGE = "Decryption of the key failed. A supplied passphrase may be incorrect.";
public KeyDecryptionFailedException() {
super(MESSAGE);
public KeyDecryptionFailedException(final String message) {
super(message);
}
public KeyDecryptionFailedException(EncryptionException cause) {
public KeyDecryptionFailedException(final String message, final Throwable cause) {
super(message, cause);
}
public KeyDecryptionFailedException(IOException cause) {
super(MESSAGE, cause);
}

View File

@@ -1,56 +0,0 @@
/*
* 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 com.hierynomus.sshj.signature;
import net.i2p.crypto.eddsa.EdDSAPublicKey;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
import net.schmizz.sshj.common.SSHRuntimeException;
import java.util.Arrays;
/**
* Our own extension of the EdDSAPublicKey that comes from ECC-25519, as that class does not implement equality.
* The code uses the equality of the keys as an indicator whether they're the same during host key verification.
*/
@SuppressWarnings("serial")
public class Ed25519PublicKey extends EdDSAPublicKey {
public Ed25519PublicKey(EdDSAPublicKeySpec spec) {
super(spec);
EdDSANamedCurveSpec ed25519 = EdDSANamedCurveTable.getByName("Ed25519");
if (!spec.getParams().getCurve().equals(ed25519.getCurve())) {
throw new SSHRuntimeException("Cannot create Ed25519 Public Key from wrong spec");
}
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Ed25519PublicKey)) {
return false;
}
Ed25519PublicKey otherKey = (Ed25519PublicKey) other;
return Arrays.equals(getAbyte(), otherKey.getAbyte());
}
@Override
public int hashCode() {
return getA().hashCode();
}
}

View File

@@ -15,14 +15,14 @@
*/
package com.hierynomus.sshj.signature;
import net.i2p.crypto.eddsa.EdDSAEngine;
import net.schmizz.sshj.common.KeyType;
import net.schmizz.sshj.common.SSHRuntimeException;
import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.signature.AbstractSignature;
import net.schmizz.sshj.signature.Signature;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SignatureException;
public class SignatureEdDSA extends AbstractSignature {
@@ -43,11 +43,11 @@ public class SignatureEdDSA extends AbstractSignature {
super(getEngine(), KeyType.ED25519.toString());
}
private static EdDSAEngine getEngine() {
private static java.security.Signature getEngine() {
try {
return new EdDSAEngine(MessageDigest.getInstance("SHA-512"));
} catch (NoSuchAlgorithmException e) {
throw new SSHRuntimeException(e);
return SecurityUtils.getSignature("Ed25519");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new SSHRuntimeException("Ed25519 Signatures not supported", e);
}
}

View File

@@ -28,7 +28,7 @@ public class IdentificationStringParser {
private final Logger log;
private final Buffer.PlainBuffer buffer;
private byte[] EXPECTED_START_BYTES = new byte[] {'S', 'S', 'H', '-'};
private final byte[] EXPECTED_START_BYTES = new byte[] {'S', 'S', 'H', '-'};
public IdentificationStringParser(Buffer.PlainBuffer buffer) {
this(buffer, LoggerFactory.DEFAULT);

View File

@@ -121,11 +121,11 @@ public class BlockCiphers {
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<Cipher> {
private int keysize;
private String cipher;
private String mode;
private String name;
private int ivsize;
private final int keysize;
private final String cipher;
private final String mode;
private final String name;
private final int ivsize;
/**
* @param ivsize

View File

@@ -33,12 +33,12 @@ public class GcmCiphers {
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<Cipher> {
private int keysize;
private int authSize;
private String cipher;
private String mode;
private String name;
private int ivsize;
private final int keysize;
private final int authSize;
private final String cipher;
private final String mode;
private final String name;
private final int ivsize;
/**
* @param ivsize

View File

@@ -40,10 +40,10 @@ public class StreamCiphers {
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<Cipher> {
private int keysize;
private String cipher;
private String mode;
private String name;
private final int keysize;
private final String cipher;
private final String mode;
private final String name;
/**
* @param keysize The keysize used in bits.

View File

@@ -28,8 +28,8 @@ import java.security.GeneralSecurityException;
*
*/
public class DHG extends AbstractDHG {
private BigInteger group;
private BigInteger generator;
private final BigInteger group;
private final BigInteger generator;
public DHG(BigInteger group, BigInteger generator, Digest digest) {
super(new DH(), digest);

View File

@@ -68,10 +68,10 @@ public class DHGroups {
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<KeyExchange> {
private String name;
private BigInteger group;
private BigInteger generator;
private Factory.Named<Digest> digestFactory;
private final String name;
private final BigInteger group;
private final BigInteger generator;
private final Factory.Named<Digest> digestFactory;
public Factory(String name, BigInteger group, BigInteger generator, Named<Digest> digestFactory) {
this.name = name;

View File

@@ -71,10 +71,10 @@ public class Macs {
public static class Factory implements net.schmizz.sshj.common.Factory.Named<MAC> {
private String name;
private String algorithm;
private int bSize;
private int defBSize;
private final String name;
private final String algorithm;
private final int bSize;
private final int defBSize;
private final boolean etm;
public Factory(String name, String algorithm, int bSize, int defBSize, boolean etm) {

View File

@@ -17,11 +17,11 @@ package com.hierynomus.sshj.transport.verification;
import net.schmizz.sshj.common.Base64DecodingException;
import net.schmizz.sshj.common.Base64Decoder;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.transport.mac.MAC;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
@@ -57,7 +57,7 @@ public class KnownHostMatchers {
}
private static class EquiHostMatcher implements HostMatcher {
private String host;
private final String host;
public EquiHostMatcher(String host) {
this.host = host;
@@ -96,7 +96,7 @@ public class KnownHostMatchers {
private String hashHost(String host) throws IOException, Base64DecodingException {
sha1.init(getSaltyBytes());
return "|1|" + salt + "|" + Base64.getEncoder().encodeToString(sha1.doFinal(host.getBytes(IOUtils.UTF8)));
return "|1|" + salt + "|" + Base64.getEncoder().encodeToString(sha1.doFinal(host.getBytes(StandardCharsets.UTF_8)));
}
private byte[] getSaltyBytes() throws IOException, Base64DecodingException {

View File

@@ -47,8 +47,7 @@ public class OpenSSHKeyFileUtil {
* @param publicKey Public key accessible through a {@code Reader}
*/
public static ParsedPubKey initPubKey(Reader publicKey) throws IOException {
final BufferedReader br = new BufferedReader(publicKey);
try {
try (BufferedReader br = new BufferedReader(publicKey)) {
String keydata;
while ((keydata = br.readLine()) != null) {
keydata = keydata.trim();
@@ -68,8 +67,6 @@ public class OpenSSHKeyFileUtil {
throw new IOException("Public key file is blank");
} catch (Base64DecodingException err) {
throw new IOException("Public key decoding failed", err);
} finally {
br.close();
}
}

View File

@@ -21,9 +21,6 @@ import com.hierynomus.sshj.transport.cipher.BlockCiphers;
import com.hierynomus.sshj.transport.cipher.ChachaPolyCiphers;
import com.hierynomus.sshj.transport.cipher.GcmCiphers;
import com.hierynomus.sshj.userauth.keyprovider.bcrypt.BCrypt;
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
import net.schmizz.sshj.common.*;
import net.schmizz.sshj.common.Buffer.PlainBuffer;
import net.schmizz.sshj.transport.cipher.Cipher;
@@ -31,10 +28,6 @@ import net.schmizz.sshj.userauth.keyprovider.BaseFileKeyProvider;
import net.schmizz.sshj.userauth.keyprovider.FileKeyProvider;
import net.schmizz.sshj.userauth.keyprovider.KeyFormat;
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.LoggerFactory;
@@ -47,7 +40,6 @@ import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.ECPrivateKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Arrays;
import java.util.HashMap;
@@ -55,7 +47,7 @@ import java.util.Map;
/**
* 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 {
private static final String BEGIN = "-----BEGIN ";
@@ -244,7 +236,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
cipher.update(privateKey, 0, privateKeyLength);
} catch (final SSHRuntimeException e) {
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);
decryptedPrivateKey.putRawBytes(privateKey, 0, privateKeyLength);
@@ -343,7 +335,7 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
int checkInt1 = keyBuffer.readUInt32AsInt(); // uint32 checkint1
int checkInt2 = keyBuffer.readUInt32AsInt(); // uint32 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
String keyType = keyBuffer.readString(); // string keytype
@@ -356,8 +348,14 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
keyBuffer.readUInt32(); // length of privatekey+publickey
byte[] privKey = new byte[32];
keyBuffer.readRawBytes(privKey); // string privatekey
keyBuffer.readRawBytes(new byte[32]); // string publickey (again...)
kp = new KeyPair(publicKey, new EdDSAPrivateKey(new EdDSAPrivateKeySpec(privKey, EdDSANamedCurveTable.getByName("Ed25519"))));
final byte[] pubKey = new byte[32];
keyBuffer.readRawBytes(pubKey); // string publickey (again...)
final PrivateKey edPrivateKey = Ed25519KeyFactory.getPrivateKey(privKey);
final PublicKey edPublicKey = Ed25519KeyFactory.getPublicKey(pubKey);
kp = new KeyPair(edPublicKey, edPrivateKey);
break;
case RSA:
final RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = readRsaPrivateKeySpec(keyBuffer);
@@ -365,13 +363,13 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
kp = new KeyPair(publicKey, privateKey);
break;
case ECDSA256:
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-256"));
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP256R1));
break;
case ECDSA384:
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-384"));
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP384R1));
break;
case ECDSA521:
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, "P-521"));
kp = new KeyPair(publicKey, createECDSAPrivateKey(kt, keyBuffer, ECDSACurve.SECP521R1));
break;
default:
@@ -388,13 +386,10 @@ public class OpenSSHKeyV1KeyFile extends BaseFileKeyProvider {
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
BigInteger s = new BigInteger(1, buffer.readBytes());
X9ECParameters ecParams = NISTNamedCurves.getByName(name);
ECNamedCurveSpec ecCurveSpec = new ECNamedCurveSpec(name, ecParams.getCurve(), ecParams.getG(), ecParams.getN());
ECPrivateKeySpec pks = new ECPrivateKeySpec(s, ecCurveSpec);
return SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA).generatePrivate(pks);
final BigInteger s = new BigInteger(1, buffer.readBytes());
return ECDSAKeyFactory.getPrivateKey(s, ecdsaCurve);
}
/**

View File

@@ -29,6 +29,6 @@ final class Heartbeater
@Override
protected void doKeepAlive() throws TransportException {
conn.getTransport().write(new SSHPacket(Message.IGNORE));
conn.getTransport().write(new SSHPacket(Message.IGNORE).putString(""));
}
}

View File

@@ -59,7 +59,8 @@ import java.util.Properties;
* net.schmizz.sshj.transport.mac.HMACMD596}</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setCompressionFactories Compression}: {@link net.schmizz.sshj.transport.compression.NoneCompression}</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setKeyAlgorithms KeyAlgorithm}: {@link net.schmizz.sshj.signature.SignatureRSA}, {@link net.schmizz.sshj.signature.SignatureDSA}</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setRandomFactory PRNG}: {@link net.schmizz.sshj.transport.random.BouncyCastleRandom}* or {@link net.schmizz.sshj.transport.random.JCERandom}</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setRandomFactory BC}: {@link net.schmizz.sshj.transport.random.BouncyCastleRandom}* or {@link net.schmizz.sshj.transport.random.JCERandom}</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setRandomFactory BCFIPS}: {@link net.schmizz.sshj.transport.random.BouncyCastleFipsRandom}* or {@link net.schmizz.sshj.transport.random.JCERandom}</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setFileKeyProviderFactories Key file support}: {@link net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile}*, {@link
* net.schmizz.sshj.userauth.keyprovider.OpenSSHKeyFile}*</li>
* <li>{@link net.schmizz.sshj.ConfigImpl#setVersion Client version}: {@code "NET_3_0"}</li>

View File

@@ -59,6 +59,7 @@ import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.util.*;
@@ -126,7 +127,7 @@ public class SSHClient
private final List<LocalPortForwarder> forwarders = new ArrayList<LocalPortForwarder>();
/** character set of the remote machine */
protected Charset remoteCharset = IOUtils.UTF8;
protected Charset remoteCharset = StandardCharsets.UTF_8;
/** Default constructor. Initializes this object using {@link DefaultConfig}. */
public SSHClient() {
@@ -765,7 +766,7 @@ public class SSHClient
* remote character set or {@code null} for default
*/
public void setRemoteCharset(Charset remoteCharset) {
this.remoteCharset = remoteCharset != null ? remoteCharset : IOUtils.UTF8;
this.remoteCharset = remoteCharset != null ? remoteCharset : StandardCharsets.UTF_8;
}
@Override

View File

@@ -17,6 +17,7 @@ package net.schmizz.sshj.common;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.util.Arrays;
@@ -428,7 +429,7 @@ public class Buffer<T extends Buffer<T>> {
*/
public String readString()
throws BufferException {
return readString(IOUtils.UTF8);
return readString(StandardCharsets.UTF_8);
}
/**
@@ -454,7 +455,7 @@ public class Buffer<T extends Buffer<T>> {
}
public T putString(String string) {
return putString(string, IOUtils.UTF8);
return putString(string, StandardCharsets.UTF_8);
}
/**

View File

@@ -17,8 +17,8 @@ package net.schmizz.sshj.common;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/** Utility functions for byte arrays. */
@@ -141,7 +141,7 @@ public class ByteArrayUtils {
* @return UTF-8 bytes of the string
*/
public static byte[] encodeSensitiveStringToUtf8(char[] str) {
CharsetEncoder charsetEncoder = Charset.forName("UTF-8").newEncoder();
CharsetEncoder charsetEncoder = StandardCharsets.UTF_8.newEncoder();
ByteBuffer utf8Buffer = ByteBuffer.allocate((int) (str.length * charsetEncoder.maxBytesPerChar()));
assert utf8Buffer.hasArray();
charsetEncoder.encode(CharBuffer.wrap(str), utf8Buffer, true);

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.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.LoggerFactory;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.interfaces.ECKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -42,13 +37,13 @@ class ECDSAVariationsAdapter {
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> NIST_CURVES_NAMES = new HashMap<String, String>();
public final static Map<String, String> SUPPORTED_CURVES = new HashMap<>();
public final static Map<String, ECDSACurve> NIST_CURVES = new HashMap<>();
static {
NIST_CURVES_NAMES.put("256", "p-256");
NIST_CURVES_NAMES.put("384", "p-384");
NIST_CURVES_NAMES.put("521", "p-521");
NIST_CURVES.put("256", ECDSACurve.SECP256R1);
NIST_CURVES.put("384", ECDSACurve.SECP384R1);
NIST_CURVES.put("521", ECDSACurve.SECP521R1);
SUPPORTED_CURVES.put("256", "nistp256");
SUPPORTED_CURVES.put("384", "nistp384");
@@ -72,21 +67,15 @@ class ECDSAVariationsAdapter {
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));
}
BigInteger bigX = new BigInteger(1, x);
BigInteger bigY = new BigInteger(1, y);
String name = NIST_CURVES_NAMES.get(variation);
X9ECParameters ecParams = NISTNamedCurves.getByName(name);
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);
final BigInteger bigX = new BigInteger(1, x);
final BigInteger bigY = new BigInteger(1, y);
final ECPoint point = new ECPoint(bigX, bigY);
final ECDSACurve ecdsaCurve = NIST_CURVES.get(variation);
return ECDSAKeyFactory.getPublicKey(point, ecdsaCurve);
} catch (Exception ex) {
throw new GeneralSecurityException(ex);
}
@@ -96,7 +85,7 @@ class ECDSAVariationsAdapter {
final ECPublicKey ecdsa = (ECPublicKey) pk;
byte[] encoded = SecgUtils.getEncoded(ecdsa.getW(), ecdsa.getParams().getCurve());
buf.putString("nistp" + Integer.toString(fieldSizeFromKey(ecdsa)))
buf.putString("nistp" + (fieldSizeFromKey(ecdsa)))
.putBytes(encoded);
}

View File

@@ -0,0 +1,90 @@
/*
* 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 java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Objects;
/**
* Factory for generating Edwards-curve 25519 Public and Private Keys
*/
public class Ed25519KeyFactory {
private static final int KEY_LENGTH = 32;
private static final String KEY_ALGORITHM = "Ed25519";
private static final byte[] ED25519_PKCS8_PRIVATE_KEY_HEADER = Base64.getDecoder().decode("MC4CAQEwBQYDK2VwBCIEIA");
private static final byte[] ED25519_PKCS8_PUBLIC_KEY_HEADER = Base64.getDecoder().decode("MCowBQYDK2VwAyEA");
private static final int PRIVATE_KEY_ENCODED_LENGTH = 48;
private static final int PUBLIC_KEY_ENCODED_LENGTH = 44;
private Ed25519KeyFactory() {
}
/**
* Get Edwards-curve Private Key for private key binary
*
* @param privateKeyBinary Private Key byte array consisting of 32 bytes
* @return Edwards-curve 25519 Private Key
* @throws GeneralSecurityException Thrown on failure to generate Private Key
*/
public static PrivateKey getPrivateKey(final byte[] privateKeyBinary) throws GeneralSecurityException {
Objects.requireNonNull(privateKeyBinary, "Private Key byte array required");
if (privateKeyBinary.length == KEY_LENGTH) {
final byte[] privateKeyEncoded = new byte[PRIVATE_KEY_ENCODED_LENGTH];
System.arraycopy(ED25519_PKCS8_PRIVATE_KEY_HEADER, 0, privateKeyEncoded, 0, ED25519_PKCS8_PRIVATE_KEY_HEADER.length);
System.arraycopy(privateKeyBinary, 0, privateKeyEncoded, ED25519_PKCS8_PRIVATE_KEY_HEADER.length, KEY_LENGTH);
final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyEncoded);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KEY_ALGORITHM);
return keyFactory.generatePrivate(keySpec);
} else {
throw new IllegalArgumentException("Key length of 32 bytes required");
}
}
/**
* Get Edwards-curve Public Key for public key binary
*
* @param publicKeyBinary Public Key byte array consisting of 32 bytes
* @return Edwards-curve 25519 Public Key
* @throws GeneralSecurityException Thrown on failure to generate Public Key
*/
public static PublicKey getPublicKey(final byte[] publicKeyBinary) throws GeneralSecurityException {
Objects.requireNonNull(publicKeyBinary, "Public Key byte array required");
if (publicKeyBinary.length == KEY_LENGTH) {
final byte[] publicKeyEncoded = new byte[PUBLIC_KEY_ENCODED_LENGTH];
System.arraycopy(ED25519_PKCS8_PUBLIC_KEY_HEADER, 0, publicKeyEncoded, 0, ED25519_PKCS8_PUBLIC_KEY_HEADER.length);
System.arraycopy(publicKeyBinary, 0, publicKeyEncoded, ED25519_PKCS8_PUBLIC_KEY_HEADER.length, KEY_LENGTH);
final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyEncoded);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KEY_ALGORITHM);
return keyFactory.generatePublic(keySpec);
} else {
throw new IllegalArgumentException("Key length of 32 bytes required");
}
}
}

View File

@@ -19,12 +19,9 @@ import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class IOUtils {
public static final Charset UTF8 = Charset.forName("UTF-8");
public static void closeQuietly(Closeable... closeables) {
closeQuietly(LoggerFactory.DEFAULT, closeables);
}

View File

@@ -16,13 +16,8 @@
package net.schmizz.sshj.common;
import com.hierynomus.sshj.common.KeyAlgorithm;
import com.hierynomus.sshj.signature.Ed25519PublicKey;
import com.hierynomus.sshj.signature.SignatureEdDSA;
import com.hierynomus.sshj.userauth.certificate.Certificate;
import net.i2p.crypto.eddsa.EdDSAPublicKey;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
import net.schmizz.sshj.common.Buffer.BufferException;
import net.schmizz.sshj.signature.Signature;
import net.schmizz.sshj.signature.SignatureDSA;
@@ -178,20 +173,16 @@ public enum KeyType {
public PublicKey readPubKeyFromBuffer(Buffer<?> buf) throws GeneralSecurityException {
try {
final int keyLen = buf.readUInt32AsInt();
final byte[] p = new byte[keyLen];
buf.readRawBytes(p);
final byte[] publicKeyBinary = new byte[keyLen];
buf.readRawBytes(publicKeyBinary);
if (log.isDebugEnabled()) {
log.debug(String.format("Key algo: %s, Key curve: 25519, Key Len: %s\np: %s",
sType,
keyLen,
Arrays.toString(p))
Arrays.toString(publicKeyBinary))
);
}
EdDSANamedCurveSpec ed25519 = EdDSANamedCurveTable.getByName("Ed25519");
EdDSAPublicKeySpec publicSpec = new EdDSAPublicKeySpec(p, ed25519);
return new Ed25519PublicKey(publicSpec);
return Ed25519KeyFactory.getPublicKey(publicKeyBinary);
} catch (Buffer.BufferException be) {
throw new SSHRuntimeException(be);
}
@@ -199,13 +190,17 @@ public enum KeyType {
@Override
protected void writePubKeyContentsIntoBuffer(PublicKey pk, Buffer<?> buf) {
EdDSAPublicKey key = (EdDSAPublicKey) pk;
buf.putBytes(key.getAbyte());
final byte[] encoded = pk.getEncoded();
final int keyLength = 32;
final int headerLength = encoded.length - keyLength;
final byte[] encodedPublicKey = new byte[keyLength];
System.arraycopy(encoded, headerLength, encodedPublicKey, 0, keyLength);
buf.putBytes(encodedPublicKey);
}
@Override
protected boolean isMyType(Key key) {
return "EdDSA".equals(key.getAlgorithm());
return "EdDSA".equals(key.getAlgorithm()) || "Ed25519".equals(key.getAlgorithm());
}
},

View File

@@ -276,6 +276,9 @@ public class SecurityUtils {
*/
public static synchronized void setSecurityProvider(String securityProvider) {
SecurityUtils.securityProvider = securityProvider;
if(null == securityProvider) {
SecurityUtils.registerBouncyCastle = null;
}
registrationDone = false;
}
@@ -286,8 +289,8 @@ public class SecurityUtils {
if (securityProvider == null && registerBouncyCastle == null) {
LOG.info("BouncyCastle not registered, using the default JCE provider");
} else if (securityProvider == null) {
LOG.error("Failed to register BouncyCastle as the defaut JCE provider");
throw new SSHRuntimeException("Failed to register BouncyCastle as the defaut JCE provider");
LOG.error("Failed to register BouncyCastle as the default JCE provider");
throw new SSHRuntimeException("Failed to register BouncyCastle as the default JCE provider");
}
}
registrationDone = true;

View File

@@ -27,6 +27,7 @@ import org.slf4j.Logger;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
@@ -90,7 +91,7 @@ public abstract class AbstractChannel
this.log = loggerFactory.getLogger(getClass());
this.trans = conn.getTransport();
this.remoteCharset = remoteCharset != null ? remoteCharset : IOUtils.UTF8;
this.remoteCharset = remoteCharset != null ? remoteCharset : StandardCharsets.UTF_8;
id = conn.nextID();
lwin = new Window.Local(conn.getWindowSize(), conn.getMaxPacketSize(), loggerFactory);

View File

@@ -37,7 +37,7 @@ public final class ChannelOutputStream extends OutputStream implements ErrorNoti
private final DataBuffer buffer = new DataBuffer();
private final byte[] b = new byte[1];
private AtomicBoolean closed;
private final AtomicBoolean closed;
private SSHException error;
private final class DataBuffer {

View File

@@ -317,13 +317,10 @@ public class RandomAccessRemoteFile
@Override
public void writeUTF(String str)
throws IOException {
final DataOutputStream dos = new DataOutputStream(rf.new RemoteFileOutputStream(fp));
try {
try (DataOutputStream dos = new DataOutputStream(rf.new RemoteFileOutputStream(fp));) {
dos.writeUTF(str);
} finally {
dos.close();
fp += dos.size();
}
fp += dos.size();
}
}

View File

@@ -17,7 +17,6 @@ package net.schmizz.sshj.sftp;
import com.hierynomus.sshj.common.ThreadNameProvider;
import net.schmizz.concurrent.Promise;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.connection.channel.direct.Session;
@@ -28,6 +27,7 @@ import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
@@ -373,7 +373,7 @@ public class SFTPEngine
/** Using UTF-8 */
protected static String readSingleName(Response res)
throws IOException {
return readSingleName(res, IOUtils.UTF8);
return readSingleName(res, StandardCharsets.UTF_8);
}
/** Using any character set */

View File

@@ -52,7 +52,7 @@ public class SFTPFileTransfer
throws IOException {
upload(source, dest, 0);
}
@Override
public void upload(String source, String dest, long byteOffset)
throws IOException {
@@ -64,7 +64,7 @@ public class SFTPFileTransfer
throws IOException {
download(source, dest, 0);
}
@Override
public void download(String source, String dest, long byteOffset)
throws IOException {
@@ -75,7 +75,7 @@ public class SFTPFileTransfer
public void upload(LocalSourceFile localFile, String remotePath) throws IOException {
upload(localFile, remotePath, 0);
}
@Override
public void upload(LocalSourceFile localFile, String remotePath, long byteOffset) throws IOException {
new Uploader(localFile, remotePath).upload(getTransferListener(), byteOffset);
@@ -85,7 +85,7 @@ public class SFTPFileTransfer
public void download(String source, LocalDestFile dest) throws IOException {
download(source, dest, 0);
}
@Override
public void download(String source, LocalDestFile dest, long byteOffset) throws IOException {
final PathComponents pathComponents = engine.getPathHelper().getComponents(source);
@@ -140,12 +140,9 @@ public class SFTPFileTransfer
final LocalDestFile local)
throws IOException {
final LocalDestFile adjusted = local.getTargetDirectory(remote.getName());
final RemoteDirectory rd = engine.openDir(remote.getPath());
try {
try (RemoteDirectory rd = engine.openDir(remote.getPath())) {
for (RemoteResourceInfo rri : rd.scan(getDownloadFilter()))
download(listener, rri, adjusted.getChild(rri.getName()), 0); // not supporting individual byte offsets for these files
} finally {
rd.close();
}
return adjusted;
}
@@ -156,23 +153,16 @@ public class SFTPFileTransfer
final long byteOffset)
throws IOException {
final LocalDestFile adjusted = local.getTargetFile(remote.getName());
final RemoteFile rf = engine.open(remote.getPath());
try {
try (RemoteFile rf = engine.open(remote.getPath())) {
log.debug("Attempting to download {} with offset={}", remote.getPath(), byteOffset);
final RemoteFile.ReadAheadRemoteFileInputStream rfis = rf.new ReadAheadRemoteFileInputStream(16, byteOffset);
final OutputStream os = adjusted.getOutputStream(byteOffset != 0);
try {
try (RemoteFile.ReadAheadRemoteFileInputStream rfis = rf.new ReadAheadRemoteFileInputStream(16, byteOffset);
OutputStream os = adjusted.getOutputStream(byteOffset != 0)) {
new StreamCopier(rfis, os, engine.getLoggerFactory())
.bufSize(engine.getSubsystem().getLocalMaxPacketSize())
.keepFlushing(false)
.listener(listener)
.copy();
} finally {
rfis.close();
os.close();
}
} finally {
rf.close();
}
return adjusted;
}
@@ -266,7 +256,7 @@ public class SFTPFileTransfer
// Starting at some offset, append
modes = EnumSet.of(OpenMode.WRITE, OpenMode.APPEND);
}
log.debug("Attempting to upload {} with offset={}", local.getName(), byteOffset);
rf = engine.open(adjusted, modes);
fis = local.getInputStream();

View File

@@ -77,7 +77,7 @@ public class SignatureECDSA extends AbstractSignatureDSA {
}
private String keyTypeName;
private final String keyTypeName;
public SignatureECDSA(String algorithm, String keyTypeName) {
super(algorithm, keyTypeName);

View File

@@ -87,7 +87,7 @@ public class SignatureRSA
}
private KeyType keyType;
private final KeyType keyType;
public SignatureRSA(String algorithm, KeyType keyType, String name) {

View File

@@ -33,6 +33,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -207,7 +208,7 @@ public final class TransportImpl
*/
private void sendClientIdent() throws IOException {
log.info("Client identity string: {}", clientID);
connInfo.out.write((clientID + "\r\n").getBytes(IOUtils.UTF8));
connInfo.out.write((clientID + "\r\n").getBytes(StandardCharsets.UTF_8));
connInfo.out.flush();
}

View File

@@ -25,7 +25,7 @@ import java.security.spec.ECGenParameterSpec;
public class ECDHNistP extends AbstractDHG {
private String curve;
private final String curve;
/** Named factory for ECDHNistP key exchange */
public static class Factory521

View File

@@ -0,0 +1,39 @@
/*
* 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.transport.random;
/**
* BouncyCastle <code>Random</code>. This pseudo random number generator uses BouncyCastle fips.
* The JRE random will be used when creating a new generator to add some random data to the seed.
*/
public class BouncyCastleFipsRandom extends SecureRandomProvider {
/** Named factory for the BouncyCastle <code>Random</code> */
public static class Factory
implements net.schmizz.sshj.common.Factory<Random> {
@Override
public Random create() {
return new BouncyCastleFipsRandom();
}
}
public BouncyCastleFipsRandom() {
super("DEFAULT", "BCFIPS");
}
}

View File

@@ -13,27 +13,32 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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.transport.random;
import org.bouncycastle.crypto.prng.RandomGenerator;
import org.bouncycastle.crypto.prng.VMPCRandomGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
/**
* BouncyCastle <code>Random</code>. This pseudo random number generator uses the a very fast PRNG from BouncyCastle.
* The JRE random will be used when creating a new generator to add some random data to the seed.
*/
public class BouncyCastleRandom
implements Random {
private static final Logger logger = LoggerFactory.getLogger(BouncyCastleRandom.class);
* BouncyCastle <code>Random</code>. This pseudo random number generator uses BouncyCastle non fips.
* The JRE random will be used when creating a new generator to add some random data to the seed.
*/
public class BouncyCastleRandom extends SecureRandomProvider {
/** Named factory for the BouncyCastle <code>Random</code> */
public static class Factory
implements net.schmizz.sshj.common.Factory<Random> {
implements net.schmizz.sshj.common.Factory<Random> {
@Override
public Random create() {
@@ -42,24 +47,7 @@ public class BouncyCastleRandom
}
private final RandomGenerator random = new VMPCRandomGenerator();
public BouncyCastleRandom() {
logger.info("Generating random seed from SecureRandom.");
long t = System.currentTimeMillis();
byte[] seed = new SecureRandom().generateSeed(8);
logger.debug("Creating random seed took {} ms", System.currentTimeMillis() - t);
random.addSeedMaterial(seed);
super("DEFAULT", "BC");
}
@Override
public void fill(byte[] bytes, int start, int len) {
random.nextBytes(bytes, start, len);
}
@Override
public void fill(byte[] bytes) {
random.nextBytes(bytes);
}
}

View File

@@ -15,16 +15,11 @@
*/
package net.schmizz.sshj.transport.random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.SecureRandom;
/** A {@link Random} implementation using the built-in {@link SecureRandom} PRNG. */
public class JCERandom
implements Random {
private static final Logger logger = LoggerFactory.getLogger(JCERandom.class);
public class JCERandom extends SecureRandomProvider {
/** Named factory for the JCE {@link Random} */
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<Random> {
@@ -41,39 +36,7 @@ public class JCERandom
}
private byte[] tmp = new byte[16];
private final SecureRandom random;
JCERandom() {
logger.info("Creating new SecureRandom.");
long t = System.currentTimeMillis();
random = new SecureRandom();
logger.debug("Random creation took {} ms", System.currentTimeMillis() - t);
}
/**
* Fill the given byte-array with random bytes from this PRNG.
*
* @param foo the byte-array
* @param start the offset to start at
* @param len the number of bytes to fill
*/
@Override
public synchronized void fill(byte[] foo, int start, int len) {
if (start == 0 && len == foo.length) {
random.nextBytes(foo);
} else {
synchronized (this) {
if (len > tmp.length)
tmp = new byte[len];
random.nextBytes(tmp);
System.arraycopy(tmp, 0, foo, start, len);
}
}
}
@Override
public void fill(final byte[] bytes) {
random.nextBytes(bytes);
super();
}
}

View File

@@ -0,0 +1,75 @@
/*
* 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.transport.random;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SecureRandomProvider implements Random{
private static final Logger logger = LoggerFactory.getLogger(SecureRandomProvider.class);
private byte[] tmp = new byte[16];
private SecureRandom random;
protected SecureRandomProvider() {
this.random = newRandom();
}
protected SecureRandomProvider(String algorithm, String provider) {
this.random = newRandom(algorithm, provider);
}
private static SecureRandom newRandom() {
return new SecureRandom();
}
private static SecureRandom newRandom(String algorithm, String provider) {
logger.info("Generating random seed from SecureRandom of {}.", provider);
long t = System.currentTimeMillis();
try {
// Use SecureRandom with the provider
return SecureRandom.getInstance(algorithm, provider);
} catch (NoSuchProviderException e) {
throw new RuntimeException(String.format("%s provider is not in the classpath", provider), e);
} catch (Exception e) {
throw new RuntimeException(String.format("Failed to initialize SecureRandom with %s provider", provider), e);
} finally {
logger.debug("Creating random seed took {} ms", System.currentTimeMillis() - t);
}
}
@Override
public synchronized void fill(byte[] bytes, int start, int len) {
if (start == 0 && len == bytes.length) {
random.nextBytes(bytes);
} else {
synchronized (this) {
if (len > tmp.length) tmp = new byte[len];
random.nextBytes(tmp);
System.arraycopy(tmp, 0, bytes, start, len);
}
}
}
@Override
public void fill(byte[] bytes) {
random.nextBytes(bytes);
}
}

View File

@@ -31,6 +31,7 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
@@ -186,12 +187,9 @@ public class OpenSSHKnownHosts
public void write()
throws IOException {
final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(khFile));
try {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(khFile))) {
for (KnownHostEntry entry : entries)
bos.write((entry.getLine() + LS).getBytes(IOUtils.UTF8));
} finally {
bos.close();
bos.write((entry.getLine() + LS).getBytes(StandardCharsets.UTF_8));
}
}
@@ -477,7 +475,7 @@ public class OpenSSHKnownHosts
}
public static class BadHostEntry implements KnownHostEntry {
private String line;
private final String line;
public BadHostEntry(String line) {
this.line = line;

View File

@@ -0,0 +1,149 @@
/*
* 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.userauth.keyprovider;
import com.hierynomus.sshj.common.KeyDecryptionFailedException;
import net.schmizz.sshj.common.ByteArrayUtils;
import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import net.schmizz.sshj.userauth.password.Resource;
import org.bouncycastle.openssl.PEMDecryptor;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMException;
import org.bouncycastle.openssl.bc.BcPEMDecryptorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* PEM Key Reader implementation supporting historical password-based encryption from OpenSSL EVP_BytesToKey
*/
class EncryptedPEMKeyReader extends StandardPEMKeyReader {
private static final String PROC_TYPE_ENCRYPTED_HEADER = "Proc-Type: 4,ENCRYPTED";
private static final Pattern DEK_INFO_PATTERN = Pattern.compile("^DEK-Info: ([A-Z0-9\\-]+),([A-F0-9]{16,32})$");
private static final int DEK_INFO_ALGORITHM_GROUP = 1;
private static final int DEK_INFO_IV_GROUP = 2;
private final PasswordFinder passwordFinder;
private final Resource<?> resource;
EncryptedPEMKeyReader(final PasswordFinder passwordFinder, final Resource<?> resource) {
this.passwordFinder = Objects.requireNonNull(passwordFinder, "Password Finder required");
this.resource = Objects.requireNonNull(resource, "Resource required");
}
@Override
public PEMKey readPemKey(final BufferedReader bufferedReader) throws IOException {
final PEMKey pemKey = super.readPemKey(bufferedReader);
final List<String> headers = pemKey.getHeaders();
final PEMKey processedPemKey;
if (isEncrypted(headers)) {
processedPemKey = readEncryptedPemKey(pemKey);
} else {
processedPemKey = pemKey;
}
return processedPemKey;
}
private boolean isEncrypted(final List<String> headers) {
return headers.contains(PROC_TYPE_ENCRYPTED_HEADER);
}
private PEMKey readEncryptedPemKey(final PEMKey pemKey) throws IOException {
final List<String> headers = pemKey.getHeaders();
final DataEncryptionKeyInfo dataEncryptionKeyInfo = getDataEncryptionKeyInfo(headers);
final byte[] pemKeyBody = pemKey.getBody();
byte[] decryptedPemKeyBody = null;
char[] password = passwordFinder.reqPassword(resource);
while (password != null) {
try {
decryptedPemKeyBody = getDecryptedPemKeyBody(password, pemKeyBody, dataEncryptionKeyInfo);
break;
} catch (final KeyDecryptionFailedException e) {
if (passwordFinder.shouldRetry(resource)) {
password = passwordFinder.reqPassword(resource);
} else {
throw e;
}
}
}
if (decryptedPemKeyBody == null) {
throw new KeyDecryptionFailedException("PEM Key password-based decryption failed");
}
return new PEMKey(pemKey.getPemKeyType(), headers, decryptedPemKeyBody);
}
private byte[] getDecryptedPemKeyBody(final char[] password, final byte[] pemKeyBody, final DataEncryptionKeyInfo dataEncryptionKeyInfo) throws IOException {
final String algorithm = dataEncryptionKeyInfo.algorithm;
try {
final PEMDecryptorProvider pemDecryptorProvider = new BcPEMDecryptorProvider(password);
final PEMDecryptor pemDecryptor = pemDecryptorProvider.get(algorithm);
final byte[] initializationVector = dataEncryptionKeyInfo.initializationVector;
return pemDecryptor.decrypt(pemKeyBody, initializationVector);
} catch (final OperatorCreationException e) {
throw new IOException(String.format("PEM decryption support not found for algorithm [%s]", algorithm), e);
} catch (final PEMException e) {
throw new KeyDecryptionFailedException(String.format("PEM Key decryption failed for algorithm [%s]", algorithm), e);
} finally {
PasswordUtils.blankOut(password);
}
}
private DataEncryptionKeyInfo getDataEncryptionKeyInfo(final List<String> headers) throws IOException {
DataEncryptionKeyInfo dataEncryptionKeyInfo = null;
for (final String header : headers) {
final Matcher matcher = DEK_INFO_PATTERN.matcher(header);
if (matcher.matches()) {
final String algorithm = matcher.group(DEK_INFO_ALGORITHM_GROUP);
final String initializationVectorGroup = matcher.group(DEK_INFO_IV_GROUP);
final byte[] initializationVector = ByteArrayUtils.parseHex(initializationVectorGroup);
dataEncryptionKeyInfo = new DataEncryptionKeyInfo(algorithm, initializationVector);
}
}
if (dataEncryptionKeyInfo == null) {
throw new IOException("Data Encryption Key Information header [DEK-Info] not found");
}
return dataEncryptionKeyInfo;
}
private static class DataEncryptionKeyInfo {
private final String algorithm;
private final byte[] initializationVector;
private DataEncryptionKeyInfo(final String algorithm, final byte[] initializationVector) {
this.algorithm = algorithm;
this.initializationVector = initializationVector;
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* 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.userauth.keyprovider;
import java.util.List;
import java.util.Objects;
/**
* PEM Key container with identified Key Type and decoded body
*/
public class PEMKey {
private final PEMKeyType pemKeyType;
private final List<String> headers;
private final byte[] body;
PEMKey(final PEMKeyType pemKeyType, final List<String> headers, final byte[] body) {
this.pemKeyType = Objects.requireNonNull(pemKeyType, "PEM Key Type required");
this.headers = Objects.requireNonNull(headers, "Headers required");
this.body = Objects.requireNonNull(body, "Body required");
}
PEMKeyType getPemKeyType() {
return pemKeyType;
}
List<String> getHeaders() {
return headers;
}
byte[] getBody() {
return body.clone();
}
public enum PEMKeyType {
/** RFC 3279 Section 2.3.2 */
DSA("-----BEGIN DSA PRIVATE KEY-----"),
/** RFC 5915 Section 3 */
EC("-----BEGIN EC PRIVATE KEY-----"),
/** RFC 8017 Appendix 1.2 */
RSA("-----BEGIN RSA PRIVATE KEY-----"),
/** RFC 5208 Section 5 */
PKCS8("-----BEGIN PRIVATE KEY-----"),
/** RFC 5208 Section 6 */
PKCS8_ENCRYPTED("-----BEGIN ENCRYPTED PRIVATE KEY-----");
private final String header;
PEMKeyType(final String header) {
this.header = header;
}
String getHeader() {
return header;
}
}
}

View File

@@ -13,23 +13,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.schmizz.sshj.userauth.keyprovider.pkcs;
import org.bouncycastle.openssl.PEMKeyPair;
package net.schmizz.sshj.userauth.keyprovider;
import java.io.BufferedReader;
import java.io.IOException;
/**
* Converter from typed object to PEM Key Pair
* @param <T> Object Type
* Abstraction for parsing and returning PEM Keys
*/
public interface KeyPairConverter<T> {
interface PEMKeyReader {
/**
* Get PEM Key Pair from typed object
* Read PEM Key from buffered reader
*
* @param object Typed Object
* @return PEM Key Pair
* @throws IOException Thrown on conversion failures
* @param bufferedReader Buffered Reader containing lines from resource reader
* @return PEM Key
* @throws IOException Thrown on failure to read PEM Key from resources
*/
PEMKeyPair getKeyPair(T object) throws IOException;
PEMKey readPemKey(BufferedReader bufferedReader) throws IOException;
}

View File

@@ -15,37 +15,66 @@
*/
package net.schmizz.sshj.userauth.keyprovider;
import com.hierynomus.asn1.ASN1InputStream;
import com.hierynomus.asn1.encodingrules.der.DERDecoder;
import com.hierynomus.asn1.types.ASN1Tag;
import com.hierynomus.asn1.types.constructed.ASN1Sequence;
import com.hierynomus.asn1.types.constructed.ASN1TaggedObject;
import com.hierynomus.asn1.types.primitive.ASN1Integer;
import com.hierynomus.asn1.types.primitive.ASN1ObjectIdentifier;
import com.hierynomus.asn1.types.string.ASN1BitString;
import com.hierynomus.asn1.types.string.ASN1OctetString;
import com.hierynomus.sshj.common.KeyAlgorithm;
import com.hierynomus.sshj.common.KeyDecryptionFailedException;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.ECDSACurve;
import net.schmizz.sshj.common.ECDSAKeyFactory;
import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.userauth.keyprovider.pkcs.KeyPairConverter;
import net.schmizz.sshj.userauth.keyprovider.pkcs.PrivateKeyInfoKeyPairConverter;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.openssl.EncryptionException;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;
import org.bouncycastle.pkcs.PKCSException;
import net.schmizz.sshj.userauth.keyprovider.PEMKey.PEMKeyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.ECField;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.EllipticCurve;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
/**
* Key File implementation supporting PEM-encoded PKCS8 and PKCS1 formats with or without password-based encryption
*/
public class PKCS8KeyFile extends BaseFileKeyProvider {
/** Bouncy Castle class for detecting support of historical OpenSSL password-based decryption */
private static final String BOUNCY_CASTLE_CLASS = "org.bouncycastle.openssl.PEMDecryptor";
public static class Factory
implements net.schmizz.sshj.common.Factory.Named<FileKeyProvider> {
private static final boolean HISTORICAL_DECRYPTION_SUPPORTED = isHistoricalDecryptionSupported();
protected final Logger log = LoggerFactory.getLogger(getClass());
public static class Factory implements net.schmizz.sshj.common.Factory.Named<FileKeyProvider> {
@Override
public FileKeyProvider create() {
@@ -58,58 +87,47 @@ public class PKCS8KeyFile extends BaseFileKeyProvider {
}
}
protected final Logger log = LoggerFactory.getLogger(getClass());
@Override
protected KeyPair readKeyPair() throws IOException {
final PEMKeyReader pemKeyReader;
protected KeyPairConverter<PrivateKeyInfo> privateKeyInfoKeyPairConverter = new PrivateKeyInfoKeyPairConverter();
protected KeyPair readKeyPair()
throws IOException {
KeyPair kp = null;
for (PEMParser r = null; ; ) {
// while the PasswordFinder tells us we should retry
try {
r = new PEMParser(resource.getReader());
final Object o = r.readObject();
final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
if (SecurityUtils.getSecurityProvider() != null) {
pemConverter.setProvider(SecurityUtils.getSecurityProvider());
}
if (o instanceof PEMEncryptedKeyPair) {
final PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) o;
final PEMKeyPair pemKeyPair = readEncryptedKeyPair(encryptedKeyPair);
kp = pemConverter.getKeyPair(pemKeyPair);
} else if (o instanceof PEMKeyPair) {
kp = pemConverter.getKeyPair((PEMKeyPair) o);
} else if (o instanceof PrivateKeyInfo) {
final PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) o;
final PEMKeyPair pemKeyPair = privateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
kp = pemConverter.getKeyPair(pemKeyPair);
} else if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
final PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) o;
final PrivateKeyInfo privateKeyInfo = readEncryptedPrivateKeyInfo(encryptedPrivateKeyInfo);
final PEMKeyPair pemKeyPair = privateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
kp = pemConverter.getKeyPair(pemKeyPair);
} else {
log.warn("Unexpected PKCS8 PEM Object [{}]", o);
}
} catch (EncryptionException e) {
if (pwdf != null && pwdf.shouldRetry(resource))
continue;
else
throw new KeyDecryptionFailedException(e);
} finally {
IOUtils.closeQuietly(r);
if (HISTORICAL_DECRYPTION_SUPPORTED) {
if (pwdf == null) {
pemKeyReader = new StandardPEMKeyReader();
} else {
pemKeyReader = new EncryptedPEMKeyReader(pwdf, resource);
}
break;
} else {
pemKeyReader = new StandardPEMKeyReader();
}
if (kp == null)
throw new IOException("Could not read key pair from: " + resource);
return kp;
try (BufferedReader bufferedReader = new BufferedReader(resource.getReader())) {
final PEMKey pemKey = pemKeyReader.readPemKey(bufferedReader);
return readKeyPair(pemKey);
}
}
private KeyPair readKeyPair(final PEMKey pemKey) throws IOException {
final KeyPair keyPair;
final PEMKeyType pemKeyType = pemKey.getPemKeyType();
final byte[] pemKeyBody = pemKey.getBody();
if (PEMKeyType.DSA == pemKeyType) {
keyPair = readDsaKeyPair(pemKeyBody);
} else if (PEMKeyType.EC == pemKeyType) {
keyPair = readEcKeyPair(pemKeyBody);
} else if (PEMKeyType.PKCS8 == pemKeyType) {
keyPair = getPkcs8KeyPair(pemKeyBody);
} else if (PEMKeyType.PKCS8_ENCRYPTED == pemKeyType) {
keyPair = readEncryptedPkcs8KeyPair(pemKeyBody);
} else if (PEMKeyType.RSA == pemKeyType) {
keyPair = readRsaKeyPair(pemKeyBody);
} else {
throw new IOException(String.format("PEM Key Type [%s] not supported", pemKeyType));
}
return keyPair;
}
@Override
@@ -117,36 +135,304 @@ public class PKCS8KeyFile extends BaseFileKeyProvider {
return "PKCS8KeyFile{resource=" + resource + "}";
}
private PEMKeyPair readEncryptedKeyPair(final PEMEncryptedKeyPair encryptedKeyPair) throws IOException {
final JcePEMDecryptorProviderBuilder builder = new JcePEMDecryptorProviderBuilder();
if (SecurityUtils.getSecurityProvider() != null) {
builder.setProvider(SecurityUtils.getSecurityProvider());
}
char[] passphrase = null;
try {
passphrase = pwdf == null ? null : pwdf.reqPassword(resource);
return encryptedKeyPair.decryptKeyPair(builder.build(passphrase));
} finally {
PasswordUtils.blankOut(passphrase);
private KeyPair readDsaKeyPair(final byte[] pemKeyBody) throws IOException {
try (ASN1InputStream inputStream = new ASN1InputStream(new DERDecoder(), pemKeyBody)) {
final ASN1Sequence sequence = inputStream.readObject();
final BigInteger p = getBigInteger(sequence, 1);
final BigInteger q = getBigInteger(sequence, 2);
final BigInteger g = getBigInteger(sequence, 3);
final BigInteger y = getBigInteger(sequence, 4);
final BigInteger x = getBigInteger(sequence, 5);
final DSAPrivateKeySpec privateKeySpec = new DSAPrivateKeySpec(x, p, q, g);
final DSAPublicKeySpec publicKeySpec = new DSAPublicKeySpec(y, p, q, g);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.DSA);
final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
return new KeyPair(publicKey, privateKey);
} catch (final Exception e) {
throw new IOException("PEM Key [DSA] processing failed", e);
}
}
private PrivateKeyInfo readEncryptedPrivateKeyInfo(final PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo) throws EncryptionException {
final JceOpenSSLPKCS8DecryptorProviderBuilder builder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
if (SecurityUtils.getSecurityProvider() != null) {
builder.setProvider(SecurityUtils.getSecurityProvider());
private KeyPair readRsaKeyPair(final byte[] pemKeyBody) throws IOException {
try (ASN1InputStream inputStream = new ASN1InputStream(new DERDecoder(), pemKeyBody)) {
final ASN1Sequence sequence = inputStream.readObject();
final BigInteger modulus = getBigInteger(sequence, 1);
final BigInteger publicExponent = getBigInteger(sequence, 2);
final BigInteger privateExponent = getBigInteger(sequence, 3);
final BigInteger prime1 = getBigInteger(sequence, 4);
final BigInteger prime2 = getBigInteger(sequence, 5);
final BigInteger exponent1 = getBigInteger(sequence, 6);
final BigInteger exponent2 = getBigInteger(sequence, 7);
final BigInteger coefficient = getBigInteger(sequence, 8);
final RSAPrivateCrtKeySpec privateKeySpec = new RSAPrivateCrtKeySpec(modulus, publicExponent, privateExponent, prime1, prime2, exponent1, exponent2, coefficient);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.RSA);
final PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return new KeyPair(publicKey, privateKey);
} catch (final Exception e) {
throw new IOException("PEM Key [RSA] processing failed", e);
}
char[] passphrase = null;
}
private KeyPair readEcKeyPair(final byte[] pemKeyBody) throws IOException {
try (ASN1InputStream inputStream = new ASN1InputStream(new DERDecoder(), pemKeyBody)) {
final ASN1Sequence sequence = inputStream.readObject();
final ASN1TaggedObject taggedObjectParameters = (ASN1TaggedObject) sequence.get(2);
final ASN1ObjectIdentifier objectIdentifier = (ASN1ObjectIdentifier) taggedObjectParameters.getObject();
final String objectId = objectIdentifier.getValue();
final ECNamedCurveObjectIdentifier ecNamedCurveObjectIdentifier = getEcNamedCurve(objectId);
final ASN1OctetString privateKeyOctetString = (ASN1OctetString) sequence.get(1);
final BigInteger privateKeyInteger = new BigInteger(1, privateKeyOctetString.getValue());
final ECPrivateKey privateKey = (ECPrivateKey) ECDSAKeyFactory.getPrivateKey(privateKeyInteger, ecNamedCurveObjectIdentifier.ecdsaCurve);
final ECParameterSpec ecParameterSpec = privateKey.getParams();
final ASN1TaggedObject taggedBitString = (ASN1TaggedObject) sequence.get(3);
final ASN1BitString publicKeyBitString = (ASN1BitString) taggedBitString.getObject();
final byte[] bitString = publicKeyBitString.getValueBytes();
final PublicKey publicKey = getEcPublicKey(bitString, ecParameterSpec);
return new KeyPair(publicKey, privateKey);
} catch (final Exception e) {
throw new IOException("PEM Key [EC] processing failed", e);
}
}
private ECNamedCurveObjectIdentifier getEcNamedCurve(final String objectId) {
ECNamedCurveObjectIdentifier objectIdentifierFound = null;
for (final ECNamedCurveObjectIdentifier objectIdentifier : ECNamedCurveObjectIdentifier.values()) {
if (objectIdentifier.objectId.equals(objectId)) {
objectIdentifierFound = objectIdentifier;
}
}
if (objectIdentifierFound == null) {
throw new IllegalArgumentException(String.format("ECDSA Key Algorithm [%s] not supported", objectId));
}
return objectIdentifierFound;
}
private KeyPair readEncryptedPkcs8KeyPair(final byte[] pemKeyBody) throws IOException {
if (pwdf == null) {
throw new KeyDecryptionFailedException("Password not provided for encrypted PKCS8 key");
}
KeyPair keyPair = null;
try {
passphrase = pwdf == null ? null : pwdf.reqPassword(resource);
final InputDecryptorProvider inputDecryptorProvider = builder.build(passphrase);
return encryptedPrivateKeyInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
} catch (final OperatorCreationException e) {
throw new EncryptionException("Loading Password for Encrypted Private Key Failed", e);
} catch (final PKCSException e) {
throw new EncryptionException("Reading Encrypted Private Key Failed", e);
char[] password = pwdf.reqPassword(resource);
while (password != null) {
try {
final PKCS8EncodedKeySpec encodedKeySpec = getPkcs8DecryptedKeySpec(password, pemKeyBody);
keyPair = getPkcs8KeyPair(encodedKeySpec.getEncoded());
break;
} catch (final KeyDecryptionFailedException e) {
if (pwdf.shouldRetry(resource)) {
password = pwdf.reqPassword(resource);
} else {
throw e;
}
}
}
} catch (final GeneralSecurityException e) {
throw new IOException("PEM Key [PKCS8] processing failed", e);
}
if (keyPair == null) {
throw new KeyDecryptionFailedException("PEM Key [PKCS8] decryption failed");
}
return keyPair;
}
private PKCS8EncodedKeySpec getPkcs8DecryptedKeySpec(final char[] password, final byte[] encoded) throws IOException, GeneralSecurityException {
try {
final EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encoded);
final AlgorithmParameters algorithmParameters = encryptedPrivateKeyInfo.getAlgParameters();
final String secretKeyAlgorithm = algorithmParameters.toString();
final SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(secretKeyAlgorithm);
final PBEKeySpec secretKeySpec = new PBEKeySpec(password);
final SecretKey secretKey = secretKeyFactory.generateSecret(secretKeySpec);
final Cipher cipher = Cipher.getInstance(secretKeyAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameters);
try {
return encryptedPrivateKeyInfo.getKeySpec(cipher);
} catch (final GeneralSecurityException e) {
throw new KeyDecryptionFailedException(String.format("PKCS8 Key Decryption failed for algorithm [%s]", secretKeyAlgorithm), e);
}
} finally {
PasswordUtils.blankOut(passphrase);
PasswordUtils.blankOut(password);
}
}
private KeyPair getPkcs8KeyPair(final byte[] encoded) throws IOException {
try (ASN1InputStream inputStream = new ASN1InputStream(new DERDecoder(), encoded)) {
final ASN1Sequence sequence = inputStream.readObject();
final ASN1Sequence privateKeyAlgorithmSequence = (ASN1Sequence) sequence.get(1);
final ASN1ObjectIdentifier privateKeyAlgorithm = (ASN1ObjectIdentifier) privateKeyAlgorithmSequence.get(0);
final String privateKeyAlgorithmObjectId = privateKeyAlgorithm.getValue();
final KeyAlgorithmObjectIdentifier keyAlgorithmObjectIdentifier = getKeyAlgorithmObjectIdentifier(privateKeyAlgorithmObjectId);
return getPkcs8KeyPair(keyAlgorithmObjectIdentifier, encoded);
} catch (final Exception e) {
throw new IOException("PEM Key [PKCS8] processing failed", e);
}
}
private KeyPair getPkcs8KeyPair(final KeyAlgorithmObjectIdentifier objectIdentifier, final byte[] privateKeyInfo) throws GeneralSecurityException {
final PublicKey publicKey;
final PrivateKey privateKey = getPkcs8PrivateKey(objectIdentifier, privateKeyInfo);
if (privateKey instanceof RSAPrivateCrtKey) {
final RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
final BigInteger modulus = rsaPrivateKey.getModulus();
final BigInteger publicExponent = rsaPrivateKey.getPublicExponent();
final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(privateKey.getAlgorithm());
publicKey = keyFactory.generatePublic(publicKeySpec);
} else if (privateKey instanceof DSAPrivateKey) {
final DSAPrivateKey dsaPrivateKey = (DSAPrivateKey) privateKey;
final DSAParams dsaParams = dsaPrivateKey.getParams();
final BigInteger p = dsaParams.getP();
final BigInteger g = dsaParams.getG();
final BigInteger q = dsaParams.getQ();
final BigInteger x = dsaPrivateKey.getX();
final BigInteger y = g.modPow(x, p);
final DSAPublicKeySpec publicKeySpec = new DSAPublicKeySpec(y, p, q, g);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(privateKey.getAlgorithm());
publicKey = keyFactory.generatePublic(publicKeySpec);
} else if (privateKey instanceof ECPrivateKey) {
final ECPrivateKey ecPrivateKey = (ECPrivateKey) privateKey;
final ECParameterSpec ecParameterSpec = ecPrivateKey.getParams();
// Read ECDSA Public Key from ASN.1
try (ASN1InputStream inputStream = new ASN1InputStream(new DERDecoder(), privateKeyInfo)) {
final ASN1Sequence sequence = inputStream.readObject();
final ASN1OctetString keyOctetString = (ASN1OctetString) sequence.get(2);
final byte[] keyBytes = keyOctetString.getValue();
try (ASN1InputStream keyInputStream = new ASN1InputStream(new DERDecoder(), keyBytes)) {
final ASN1Sequence keySequence = keyInputStream.readObject();
final ASN1TaggedObject taggedObject = (ASN1TaggedObject) keySequence.get(2);
final ASN1BitString publicKeyBitString = taggedObject.getObject(ASN1Tag.BIT_STRING);
final byte[] bitString = publicKeyBitString.getValueBytes();
publicKey = getEcPublicKey(bitString, ecParameterSpec);
}
} catch (final IOException e) {
throw new GeneralSecurityException("ECDSA Private Key Info parsing failed", e);
}
} else {
throw new GeneralSecurityException(String.format("PEM Key [PKCS8] algorithm [%s] Key Pair derivation not supported", privateKey.getAlgorithm()));
}
return new KeyPair(publicKey, privateKey);
}
private PrivateKey getPkcs8PrivateKey(final KeyAlgorithmObjectIdentifier objectIdentifier, final byte[] privateKeyInfo) throws GeneralSecurityException {
final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyInfo);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(objectIdentifier.name());
return keyFactory.generatePrivate(keySpec);
}
private PublicKey getEcPublicKey(final byte[] bitString, final ECParameterSpec ecParameterSpec) throws GeneralSecurityException {
final EllipticCurve ellipticCurve = ecParameterSpec.getCurve();
final ECField ecField = ellipticCurve.getField();
final int fieldSize = (ecField.getFieldSize() + 7) / 8;
final int publicKeyPointSize = fieldSize * 2;
final byte[] x = new byte[fieldSize];
final byte[] y = new byte[fieldSize];
final int pointOffset = bitString.length - publicKeyPointSize;
System.arraycopy(bitString, pointOffset, x, 0, x.length);
System.arraycopy(bitString, pointOffset + y.length, y, 0, y.length);
final BigInteger pointX = new BigInteger(1, x);
final BigInteger pointY = new BigInteger(1, y);
final ECPoint point = new ECPoint(pointX, pointY);
final ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(point, ecParameterSpec);
final KeyFactory keyFactory = SecurityUtils.getKeyFactory(KeyAlgorithm.EC_KEYSTORE);
return keyFactory.generatePublic(publicKeySpec);
}
private KeyAlgorithmObjectIdentifier getKeyAlgorithmObjectIdentifier(final String objectId) {
KeyAlgorithmObjectIdentifier keyAlgorithmObjectIdentifier = null;
for (final KeyAlgorithmObjectIdentifier objectIdentifier : KeyAlgorithmObjectIdentifier.values()) {
if (objectIdentifier.getObjectId().equals(objectId)) {
keyAlgorithmObjectIdentifier = objectIdentifier;
}
}
if (keyAlgorithmObjectIdentifier == null) {
throw new IllegalArgumentException(String.format("PKCS8 Private Key Algorithm [%s] not supported", objectId));
}
return keyAlgorithmObjectIdentifier;
}
private BigInteger getBigInteger(final ASN1Sequence sequence, final int index) {
final ASN1Integer integer = (ASN1Integer) sequence.get(index);
return integer.getValue();
}
private static boolean isHistoricalDecryptionSupported() {
try {
// Support requires Bouncy Castle library for OpenSSL password-based decryption
Class.forName(BOUNCY_CASTLE_CLASS);
return true;
} catch (final Exception e) {
return false;
}
}
private enum ECNamedCurveObjectIdentifier {
SECP256R1("1.2.840.10045.3.1.7", ECDSACurve.SECP256R1),
SECP384R1("1.3.132.0.34", ECDSACurve.SECP384R1),
SECP521R1("1.3.132.0.35", ECDSACurve.SECP521R1);
private final String objectId;
private final ECDSACurve ecdsaCurve;
ECNamedCurveObjectIdentifier(final String objectId, final ECDSACurve ecdsaCurve) {
this.objectId = objectId;
this.ecdsaCurve = ecdsaCurve;
}
}
private enum KeyAlgorithmObjectIdentifier {
DSA("1.2.840.10040.4.1"),
EC("1.2.840.10045.2.1"),
RSA("1.2.840.113549.1.1.1");
private final String objectId;
KeyAlgorithmObjectIdentifier(final String objectId) {
this.objectId = objectId;
}
String getObjectId() {
return objectId;
}
}
}

View File

@@ -16,23 +16,12 @@
package net.schmizz.sshj.userauth.keyprovider;
import com.hierynomus.sshj.common.KeyAlgorithm;
import net.i2p.crypto.eddsa.EdDSAPrivateKey;
import net.i2p.crypto.eddsa.EdDSAPublicKey;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveSpec;
import net.i2p.crypto.eddsa.spec.EdDSANamedCurveTable;
import net.i2p.crypto.eddsa.spec.EdDSAPrivateKeySpec;
import net.i2p.crypto.eddsa.spec.EdDSAPublicKeySpec;
import net.schmizz.sshj.common.*;
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.params.Argon2Parameters;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.util.encoders.Hex;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
@@ -84,6 +73,8 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
}
}
private static final String KEY_DERIVATION_HEADER = "Key-Derivation";
private Integer keyFileVersion;
private byte[] privateKey;
private byte[] publicKey;
@@ -110,12 +101,12 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
throw new IOException(String.format("Unsupported encryption: %s", encryption));
}
private Map<String, String> payload = new HashMap<String, String>();
private final Map<String, String> payload = new HashMap<>();
/**
* For each line that looks like "Xyz: vvv", it will be stored in this map.
*/
private final Map<String, String> headers = new HashMap<String, String>();
private final Map<String, String> headers = new HashMap<>();
protected KeyPair readKeyPair() throws IOException {
this.parseKeyPair();
@@ -168,34 +159,38 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
}
}
if (KeyType.ED25519.equals(keyType)) {
EdDSANamedCurveSpec ed25519 = EdDSANamedCurveTable.getByName("Ed25519");
EdDSAPublicKeySpec publicSpec = new EdDSAPublicKeySpec(publicKeyReader.readBytes(), ed25519);
EdDSAPrivateKeySpec privateSpec = new EdDSAPrivateKeySpec(privateKeyReader.readBytes(), ed25519);
return new KeyPair(new EdDSAPublicKey(publicSpec), new EdDSAPrivateKey(privateSpec));
try {
final byte[] publicKeyEncoded = publicKeyReader.readBytes();
final PublicKey edPublicKey = Ed25519KeyFactory.getPublicKey(publicKeyEncoded);
final byte[] privateKeyEncoded = privateKeyReader.readBytes();
final PrivateKey edPrivateKey = Ed25519KeyFactory.getPrivateKey(privateKeyEncoded);
return new KeyPair(edPublicKey, edPrivateKey);
} catch (final GeneralSecurityException e) {
throw new IOException("Reading Ed25519 Keys failed", e);
}
}
final String ecdsaCurve;
final ECDSACurve ecdsaCurve;
switch (keyType) {
case ECDSA256:
ecdsaCurve = "P-256";
ecdsaCurve = ECDSACurve.SECP256R1;
break;
case ECDSA384:
ecdsaCurve = "P-384";
ecdsaCurve = ECDSACurve.SECP384R1;
break;
case ECDSA521:
ecdsaCurve = "P-521";
ecdsaCurve = ECDSACurve.SECP521R1;
break;
default:
ecdsaCurve = null;
break;
}
if (ecdsaCurve != null) {
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);
final BigInteger s = new BigInteger(1, privateKeyReader.readBytes());
try {
PrivateKey privateKey = SecurityUtils.getKeyFactory(KeyAlgorithm.ECDSA).generatePrivate(pks);
final PrivateKey privateKey = ECDSAKeyFactory.getPrivateKey(s, ecdsaCurve);
return new KeyPair(keyType.readPubKeyFromBuffer(publicKeyReader), privateKey);
} catch (GeneralSecurityException e) {
throw new IOException(e.getMessage(), e);
@@ -206,9 +201,8 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
protected void parseKeyPair() throws IOException {
this.keyFileVersion = null;
BufferedReader r = new BufferedReader(resource.getReader());
// Parse the text into headers and payloads
try {
try (BufferedReader r = new BufferedReader(resource.getReader())) {
String headerName = null;
String line;
while ((line = r.readLine()) != null) {
@@ -231,8 +225,6 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
payload.put(headerName, s);
}
}
} finally {
r.close();
}
if (this.keyFileVersion == null) {
throw new IOException("Invalid key file format: missing \"PuTTY-User-Key-File-?\" entry");
@@ -269,99 +261,43 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
}
/**
* Converts a passphrase into a key, by following the convention that PuTTY
* uses. Only PuTTY v1/v2 key files
* <p><p/>
* This is used to decrypt the private key when it's encrypted.
* Initialize Java Cipher for decryption using Secret Key derived from passphrase according to PuTTY Key Version
*/
private void initCipher(final char[] passphrase, Cipher cipher) throws IOException, InvalidAlgorithmParameterException, InvalidKeyException {
// The field Key-Derivation has been introduced with Putty v3 key file format
// For v3 the algorithms are "Argon2i" "Argon2d" and "Argon2id"
String kdfAlgorithm = headers.get("Key-Derivation");
if (kdfAlgorithm != null) {
kdfAlgorithm = kdfAlgorithm.toLowerCase();
byte[] keyData = this.argon2(kdfAlgorithm, passphrase);
if (keyData == null) {
throw new IOException(String.format("Unsupported key derivation function: %s", kdfAlgorithm));
}
byte[] key = new byte[32];
byte[] iv = new byte[16];
byte[] tag = new byte[32]; // Hmac key
System.arraycopy(keyData, 0, key, 0, 32);
System.arraycopy(keyData, 32, iv, 0, 16);
System.arraycopy(keyData, 48, tag, 0, 32);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"),
new IvParameterSpec(iv));
verifyHmac = tag;
return;
}
private void initCipher(final char[] passphrase, final Cipher cipher) throws InvalidAlgorithmParameterException, InvalidKeyException {
final String keyDerivationHeader = headers.get(KEY_DERIVATION_HEADER);
// Key file format v1 + v2
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
final SecretKey secretKey;
final IvParameterSpec ivParameterSpec;
// The encryption key is derived from the passphrase by means of a succession of
// SHA-1 hashes.
byte[] encodedPassphrase = PasswordUtils.toByteArray(passphrase);
// Sequence number 0
digest.update(new byte[]{0, 0, 0, 0});
digest.update(encodedPassphrase);
byte[] key1 = digest.digest();
// Sequence number 1
digest.update(new byte[]{0, 0, 0, 1});
digest.update(encodedPassphrase);
byte[] key2 = digest.digest();
Arrays.fill(encodedPassphrase, (byte) 0);
byte[] expanded = new byte[32];
System.arraycopy(key1, 0, expanded, 0, 20);
System.arraycopy(key2, 0, expanded, 20, 12);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(expanded, 0, 32, "AES"),
new IvParameterSpec(new byte[16])); // initial vector=0
} catch (NoSuchAlgorithmException e) {
throw new IOException(e.getMessage(), e);
}
}
/**
* Uses BouncyCastle Argon2 implementation
*/
private byte[] argon2(String algorithm, final char[] passphrase) throws IOException {
int type;
if ("argon2i".equals(algorithm)) {
type = Argon2Parameters.ARGON2_i;
} else if ("argon2d".equals(algorithm)) {
type = Argon2Parameters.ARGON2_d;
} else if ("argon2id".equals(algorithm)) {
type = Argon2Parameters.ARGON2_id;
if (keyDerivationHeader == null) {
// Key Version 1 and 2 with historical key derivation
final PuTTYSecretKeyDerivationFunction keyDerivationFunction = new V1PuTTYSecretKeyDerivationFunction();
secretKey = keyDerivationFunction.deriveSecretKey(passphrase);
ivParameterSpec = new IvParameterSpec(new byte[16]);
} else {
return null;
}
byte[] salt = Hex.decode(headers.get("Argon2-Salt"));
int iterations = Integer.parseInt(headers.get("Argon2-Passes"));
int memory = Integer.parseInt(headers.get("Argon2-Memory"));
int parallelism = Integer.parseInt(headers.get("Argon2-Parallelism"));
// Key Version 3 with Argon2 key derivation
final PuTTYSecretKeyDerivationFunction keyDerivationFunction = new V3PuTTYSecretKeyDerivationFunction(headers);
final SecretKey derivedSecretKey = keyDerivationFunction.deriveSecretKey(passphrase);
final byte[] derivedSecretKeyEncoded = derivedSecretKey.getEncoded();
Argon2Parameters a2p = new Argon2Parameters.Builder(type)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(iterations)
.withMemoryAsKB(memory)
.withParallelism(parallelism)
.withSalt(salt).build();
// Set Secret Key from first 32 bytes
final byte[] secretKeyEncoded = new byte[32];
System.arraycopy(derivedSecretKeyEncoded, 0, secretKeyEncoded, 0, secretKeyEncoded.length);
secretKey = new SecretKeySpec(secretKeyEncoded, derivedSecretKey.getAlgorithm());
Argon2BytesGenerator generator = new Argon2BytesGenerator();
generator.init(a2p);
byte[] output = new byte[80];
int bytes = generator.generateBytes(passphrase, output);
if (bytes != output.length) {
throw new IOException("Failed to generate key via Argon2");
// Set IV from next 16 bytes
final byte[] iv = new byte[16];
System.arraycopy(derivedSecretKeyEncoded, secretKeyEncoded.length, iv, 0, iv.length);
ivParameterSpec = new IvParameterSpec(iv);
// Set HMAC Tag from next 32 bytes
final byte[] tag = new byte[32];
final int tagSourcePosition = secretKeyEncoded.length + iv.length;
System.arraycopy(derivedSecretKeyEncoded, tagSourcePosition, tag, 0, tag.length);
verifyHmac = tag;
}
return output;
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
}
/**
@@ -388,7 +324,7 @@ public class PuTTYKeyFile extends BaseFileKeyProvider {
data.writeInt(privateKey.length);
data.write(privateKey);
final String encoded = Hex.toHexString(mac.doFinal(out.toByteArray()));
final String encoded = ByteArrayUtils.toHex(mac.doFinal(out.toByteArray()));
final String reference = headers.get("Private-MAC");
if (!encoded.equals(reference)) {
throw new IOException("Invalid passphrase");

View File

@@ -0,0 +1,31 @@
/*
* 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.userauth.keyprovider;
import javax.crypto.SecretKey;
/**
* Abstraction for deriving the Secret Key for decrypting PuTTY Key Files
*/
interface PuTTYSecretKeyDerivationFunction {
/**
* Derive Secret Key from provided passphrase characters
*
* @param passphrase Passphrase characters required
* @return Derived Secret Key
*/
SecretKey deriveSecretKey(char[] passphrase);
}

View File

@@ -0,0 +1,113 @@
/*
* 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.userauth.keyprovider;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
/**
* Standard implementation of PEM Key Reader supporting Base64 decoding without decryption
*/
class StandardPEMKeyReader implements PEMKeyReader {
private static final String HEADER_DELIMITER = "-----BEGIN";
private static final String FOOTER_DELIMITER = "-----END";
private static final char PEM_HEADER_DELIMITER = ':';
private static final int CHARACTER_NOT_FOUND = -1;
private static final String HEADER_NOT_FOUND = "header not found";
private static final Base64.Decoder bodyDecoder = Base64.getDecoder();
/**
* Read PEM Key from Buffered Reader
*
* @param bufferedReader Buffered Reader containing lines from resource reader
* @return PEM Key
* @throws IOException Thrown on failure to read or decode PEM Key
*/
@Override
public PEMKey readPemKey(final BufferedReader bufferedReader) throws IOException {
Objects.requireNonNull(bufferedReader, "Reader required");
final PEMKey.PEMKeyType pemKeyType = findPemKeyType(bufferedReader);
return readPemKeyBody(pemKeyType, bufferedReader);
}
private PEMKey.PEMKeyType findPemKeyType(final BufferedReader bufferedReader) throws IOException {
PEMKey.PEMKeyType pemKeyTypeFound = null;
String header = HEADER_NOT_FOUND;
String line = bufferedReader.readLine();
readLoop: while (line != null) {
if (line.startsWith(HEADER_DELIMITER)) {
header = line;
for (final PEMKey.PEMKeyType pemKeyType : PEMKey.PEMKeyType.values()) {
if (pemKeyType.getHeader().equals(line)) {
pemKeyTypeFound = pemKeyType;
break readLoop;
}
}
}
line = bufferedReader.readLine();
}
if (pemKeyTypeFound == null) {
throw new IOException(String.format("Supported PEM Key Type not found for header [%s]", header));
}
return pemKeyTypeFound;
}
private PEMKey readPemKeyBody(final PEMKey.PEMKeyType pemKeyType, final BufferedReader bufferedReader) throws IOException {
final StringBuilder builder = new StringBuilder();
final List<String> headers = new ArrayList<>();
String line = bufferedReader.readLine();
while (line != null) {
if (line.startsWith(FOOTER_DELIMITER)) {
break;
}
if (line.indexOf(PEM_HEADER_DELIMITER) > CHARACTER_NOT_FOUND) {
headers.add(line);
} else if (!line.isEmpty()) {
builder.append(line);
}
line = bufferedReader.readLine();
}
final String pemKeyBody = builder.toString();
final byte[] pemKeyBodyDecoded = getPemKeyBodyDecoded(pemKeyBody);
return new PEMKey(pemKeyType, headers, pemKeyBodyDecoded);
}
private byte[] getPemKeyBodyDecoded(final String pemKeyBodyEncoded) throws IOException {
try {
return bodyDecoder.decode(pemKeyBodyEncoded);
} catch (final IllegalArgumentException e) {
throw new IOException("Base64 decoding of PEM Key failed", e);
}
}
}

View File

@@ -0,0 +1,76 @@
/*
* 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.userauth.keyprovider;
import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Arrays;
import java.util.Objects;
/**
* PuTTY Key Derivation Function supporting Version 1 and 2 Key files with historical SHA-1 key derivation
*/
class V1PuTTYSecretKeyDerivationFunction implements PuTTYSecretKeyDerivationFunction {
private static final String SECRET_KEY_ALGORITHM = "AES";
private static final String DIGEST_ALGORITHM = "SHA-1";
/**
* Derive Secret Key from provided passphrase characters
*
* @param passphrase Passphrase characters required
* @return Derived Secret Key
*/
public SecretKey deriveSecretKey(char[] passphrase) {
Objects.requireNonNull(passphrase, "Passphrase required");
final MessageDigest digest = getMessageDigest();
final byte[] encodedPassphrase = PasswordUtils.toByteArray(passphrase);
// Sequence number 0
digest.update(new byte[]{0, 0, 0, 0});
digest.update(encodedPassphrase);
final byte[] key1 = digest.digest();
// Sequence number 1
digest.update(new byte[]{0, 0, 0, 1});
digest.update(encodedPassphrase);
final byte[] key2 = digest.digest();
Arrays.fill(encodedPassphrase, (byte) 0);
final byte[] secretKeyEncoded = new byte[32];
System.arraycopy(key1, 0, secretKeyEncoded, 0, 20);
System.arraycopy(key2, 0, secretKeyEncoded, 20, 12);
return new SecretKeySpec(secretKeyEncoded, SECRET_KEY_ALGORITHM);
}
private MessageDigest getMessageDigest() {
try {
return SecurityUtils.getMessageDigest(DIGEST_ALGORITHM);
} catch (final NoSuchAlgorithmException | NoSuchProviderException e) {
final String message = String.format("Message Digest Algorithm [%s] not supported", DIGEST_ALGORITHM);
throw new IllegalStateException(message, e);
}
}
}

View File

@@ -0,0 +1,98 @@
/*
* 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.userauth.keyprovider;
import net.schmizz.sshj.common.ByteArrayUtils;
import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;
import java.util.Objects;
/**
* PuTTY Key Derivation Function supporting Version 3 Key files with Argon2 Key Derivation using Bouncy Castle
*/
class V3PuTTYSecretKeyDerivationFunction implements PuTTYSecretKeyDerivationFunction {
private static final String SECRET_KEY_ALGORITHM = "AES";
private static final int KEY_LENGTH = 80;
private final Map<String, String> headers;
V3PuTTYSecretKeyDerivationFunction(final Map<String, String> headers) {
this.headers = Objects.requireNonNull(headers, "Headers required");
}
/**
* Derive Secret Key from provided passphrase characters
*
* @param passphrase Passphrase characters required
* @return Derived Secret Key
*/
public SecretKey deriveSecretKey(char[] passphrase) {
Objects.requireNonNull(passphrase, "Passphrase required");
final Argon2Parameters parameters = getParameters();
final Argon2BytesGenerator generator = new Argon2BytesGenerator();
generator.init(parameters);
final byte[] secretKeyEncoded = new byte[KEY_LENGTH];
final int bytesGenerated = generator.generateBytes(passphrase, secretKeyEncoded);
if (KEY_LENGTH == bytesGenerated) {
return new SecretKeySpec(secretKeyEncoded, SECRET_KEY_ALGORITHM);
} else {
final String message = String.format("Argon2 bytes generated [%d] not expected", bytesGenerated);
throw new IllegalStateException(message);
}
}
private Argon2Parameters getParameters() {
final int algorithmType = getAlgorithmType();
final byte[] salt = ByteArrayUtils.parseHex(headers.get("Argon2-Salt"));
final int iterations = Integer.parseInt(headers.get("Argon2-Passes"));
final int memory = Integer.parseInt(headers.get("Argon2-Memory"));
final int parallelism = Integer.parseInt(headers.get("Argon2-Parallelism"));
return new Argon2Parameters.Builder(algorithmType)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(iterations)
.withMemoryAsKB(memory)
.withParallelism(parallelism)
.withSalt(salt)
.build();
}
private int getAlgorithmType() {
final String algorithm = headers.get("Key-Derivation");
final int algorithmType;
if ("argon2i".equalsIgnoreCase(algorithm)) {
algorithmType = Argon2Parameters.ARGON2_i;
} else if ("argon2d".equalsIgnoreCase(algorithm)) {
algorithmType = Argon2Parameters.ARGON2_d;
} else if ("argon2id".equalsIgnoreCase(algorithm)) {
algorithmType = Argon2Parameters.ARGON2_id;
} else {
final String message = String.format("Key-Derivation [%s] not supported", algorithm);
throw new IllegalArgumentException(message);
}
return algorithmType;
}
}

View File

@@ -1,90 +0,0 @@
/*
* 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.userauth.keyprovider.pkcs;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.params.DSAParameters;
import org.bouncycastle.openssl.PEMKeyPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Objects;
/**
* Key Pair Converter from DSA Private Key Information to PEM Key Pair
*/
class DSAPrivateKeyInfoKeyPairConverter implements KeyPairConverter<PrivateKeyInfo> {
private static final Logger logger = LoggerFactory.getLogger(DSAPrivateKeyInfoKeyPairConverter.class);
private static final int P_INDEX = 0;
private static final int Q_INDEX = 1;
private static final int G_INDEX = 2;
/**
* Get PEM Key Pair calculating DSA Public Key from DSA Private Key Information
*
* @param privateKeyInfo DSA Private Key Information
* @return PEM Key Pair
* @throws IOException Thrown on Public Key parsing failures
*/
@Override
public PEMKeyPair getKeyPair(final PrivateKeyInfo privateKeyInfo) throws IOException {
Objects.requireNonNull(privateKeyInfo, "Private Key Info required");
final AlgorithmIdentifier algorithmIdentifier = privateKeyInfo.getPrivateKeyAlgorithm();
final ASN1ObjectIdentifier algorithm = algorithmIdentifier.getAlgorithm();
if (X9ObjectIdentifiers.id_dsa.equals(algorithm)) {
logger.debug("DSA Algorithm Found [{}]", algorithm);
} else {
throw new IllegalArgumentException(String.format("DSA Algorithm OID required [%s]", algorithm));
}
final ASN1Integer encodedPublicKey = getEncodedPublicKey(privateKeyInfo);
final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algorithmIdentifier, encodedPublicKey);
return new PEMKeyPair(subjectPublicKeyInfo, privateKeyInfo);
}
/**
* Get ASN.1 Encoded Public Key calculated according to RFC 6979 Section 2.2
*
* @param privateKeyInfo DSA Private Key Information
* @return ASN.1 Encoded DSA Public Key
* @throws IOException Thrown on failures parsing private key
*/
private ASN1Integer getEncodedPublicKey(final PrivateKeyInfo privateKeyInfo) throws IOException {
final ASN1Integer privateKey = ASN1Integer.getInstance(privateKeyInfo.parsePrivateKey());
final AlgorithmIdentifier algorithmIdentifier = privateKeyInfo.getPrivateKeyAlgorithm();
final DSAParameters dsaParameters = getDsaParameters(algorithmIdentifier);
final BigInteger publicKey = dsaParameters.getG().modPow(privateKey.getValue(), dsaParameters.getP());
return new ASN1Integer(publicKey);
}
private DSAParameters getDsaParameters(final AlgorithmIdentifier algorithmIdentifier) {
final ASN1Sequence sequence = ASN1Sequence.getInstance(algorithmIdentifier.getParameters());
final ASN1Integer p = ASN1Integer.getInstance(sequence.getObjectAt(P_INDEX));
final ASN1Integer q = ASN1Integer.getInstance(sequence.getObjectAt(Q_INDEX));
final ASN1Integer g = ASN1Integer.getInstance(sequence.getObjectAt(G_INDEX));
return new DSAParameters(p.getValue(), q.getValue(), g.getValue());
}
}

View File

@@ -1,90 +0,0 @@
/*
* 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.userauth.keyprovider.pkcs;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.sec.ECPrivateKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil;
import org.bouncycastle.math.ec.ECMultiplier;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.math.ec.FixedPointCombMultiplier;
import org.bouncycastle.openssl.PEMKeyPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Objects;
/**
* Key Pair Converter from ECDSA Private Key Information to PEM Key Pair
*/
class ECDSAPrivateKeyInfoKeyPairConverter implements KeyPairConverter<PrivateKeyInfo> {
private static final Logger logger = LoggerFactory.getLogger(ECDSAPrivateKeyInfoKeyPairConverter.class);
private static final boolean POINT_COMPRESSED = false;
/**
* Get PEM Key Pair calculating ECDSA Public Key from ECDSA Private Key Information
*
* @param privateKeyInfo ECDSA Private Key Information
* @return PEM Key Pair
* @throws IOException Thrown on Public Key parsing failures
*/
@Override
public PEMKeyPair getKeyPair(final PrivateKeyInfo privateKeyInfo) throws IOException {
Objects.requireNonNull(privateKeyInfo, "Private Key Info required");
final AlgorithmIdentifier algorithmIdentifier = privateKeyInfo.getPrivateKeyAlgorithm();
final ASN1ObjectIdentifier algorithm = algorithmIdentifier.getAlgorithm();
if (X9ObjectIdentifiers.id_ecPublicKey.equals(algorithm)) {
logger.debug("ECDSA Algorithm Found [{}]", algorithm);
} else {
throw new IllegalArgumentException(String.format("ECDSA Algorithm OID required [%s]", algorithm));
}
final byte[] encodedPublicKey = getEncodedPublicKey(privateKeyInfo);
final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algorithmIdentifier, encodedPublicKey);
return new PEMKeyPair(subjectPublicKeyInfo, privateKeyInfo);
}
/**
* Get Encoded Elliptic Curve Public Key calculated according to RFC 6979 Section 2.2
*
* @param privateKeyInfo ECDSA Private Key Information
* @return Encoded Elliptic Curve Public Key
* @throws IOException Thrown on failures parsing private key
*/
private byte[] getEncodedPublicKey(final PrivateKeyInfo privateKeyInfo) throws IOException {
final X9ECParameters parameters = getParameters(privateKeyInfo.getPrivateKeyAlgorithm());
final ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(privateKeyInfo.parsePrivateKey());
final ECPoint publicKey = getPublicKey(parameters, ecPrivateKey.getKey());
return publicKey.getEncoded(POINT_COMPRESSED);
}
private X9ECParameters getParameters(final AlgorithmIdentifier algorithmIdentifier) {
final ASN1ObjectIdentifier encodedParameters = ASN1ObjectIdentifier.getInstance(algorithmIdentifier.getParameters());
return ECUtil.getNamedCurveByOid(encodedParameters);
}
private ECPoint getPublicKey(final X9ECParameters parameters, final BigInteger privateKey) {
final ECMultiplier multiplier = new FixedPointCombMultiplier();
return multiplier.multiply(parameters.getG(), privateKey);
}
}

View File

@@ -1,61 +0,0 @@
/*
* 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.userauth.keyprovider.pkcs;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.openssl.PEMKeyPair;
import java.io.IOException;
import java.util.Objects;
/**
* Key Pair Converter for Private Key Information using known Algorithm Object Identifiers
*/
public class PrivateKeyInfoKeyPairConverter implements KeyPairConverter<PrivateKeyInfo> {
private DSAPrivateKeyInfoKeyPairConverter dsaPrivateKeyInfoKeyPairConverter = new DSAPrivateKeyInfoKeyPairConverter();
private ECDSAPrivateKeyInfoKeyPairConverter ecdsaPrivateKeyInfoKeyPairConverter = new ECDSAPrivateKeyInfoKeyPairConverter();
private RSAPrivateKeyInfoKeyPairConverter rsaPrivateKeyInfoKeyPairConverter = new RSAPrivateKeyInfoKeyPairConverter();
/**
* Get PEM Key Pair delegating to configured converters based on Algorithm Object Identifier
*
* @param privateKeyInfo Private Key Information
* @return PEM Key Pair
* @throws IOException Thrown on conversion failures
*/
@Override
public PEMKeyPair getKeyPair(final PrivateKeyInfo privateKeyInfo) throws IOException {
Objects.requireNonNull(privateKeyInfo, "Private Key Info required");
final AlgorithmIdentifier algorithmIdentifier = privateKeyInfo.getPrivateKeyAlgorithm();
final ASN1ObjectIdentifier algorithm = algorithmIdentifier.getAlgorithm();
if (PKCSObjectIdentifiers.rsaEncryption.equals(algorithm)) {
return rsaPrivateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
} else if (X9ObjectIdentifiers.id_ecPublicKey.equals(algorithm)) {
return ecdsaPrivateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
} else if (X9ObjectIdentifiers.id_dsa.equals(algorithm)) {
return dsaPrivateKeyInfoKeyPairConverter.getKeyPair(privateKeyInfo);
} else {
throw new IllegalArgumentException(String.format("Unsupported Algorithm [%s]", algorithm));
}
}
}

View File

@@ -1,65 +0,0 @@
/*
* 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.userauth.keyprovider.pkcs;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.asn1.pkcs.RSAPublicKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.openssl.PEMKeyPair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Objects;
/**
* Key Pair Converter from RSA Private Key Information to PEM Key Pair
*/
class RSAPrivateKeyInfoKeyPairConverter implements KeyPairConverter<PrivateKeyInfo> {
private static final Logger logger = LoggerFactory.getLogger(RSAPrivateKeyInfoKeyPairConverter.class);
/**
* Get PEM Key Pair parsing RSA Public Key attributes from RSA Private Key Information
*
* @param privateKeyInfo RSA Private Key Information
* @return PEM Key Pair
* @throws IOException Thrown on Public Key parsing failures
*/
@Override
public PEMKeyPair getKeyPair(final PrivateKeyInfo privateKeyInfo) throws IOException {
Objects.requireNonNull(privateKeyInfo, "Private Key Info required");
final AlgorithmIdentifier algorithmIdentifier = privateKeyInfo.getPrivateKeyAlgorithm();
final ASN1ObjectIdentifier algorithm = algorithmIdentifier.getAlgorithm();
if (PKCSObjectIdentifiers.rsaEncryption.equals(algorithm)) {
logger.debug("RSA Algorithm Found [{}]", algorithm);
} else {
throw new IllegalArgumentException(String.format("RSA Algorithm OID required [%s]", algorithm));
}
final RSAPublicKey rsaPublicKey = getRsaPublicKey(privateKeyInfo);
final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(algorithmIdentifier, rsaPublicKey);
return new PEMKeyPair(subjectPublicKeyInfo, privateKeyInfo);
}
private RSAPublicKey getRsaPublicKey(final PrivateKeyInfo privateKeyInfo) throws IOException {
final RSAPrivateKey rsaPrivateKey = RSAPrivateKey.getInstance(privateKeyInfo.parsePrivateKey());
return new RSAPublicKey(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent());
}
}

View File

@@ -16,6 +16,7 @@
package net.schmizz.sshj.userauth.password;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class PrivateKeyFileResource
extends Resource<File> {
@@ -27,6 +28,6 @@ public class PrivateKeyFileResource
@Override
public Reader getReader()
throws IOException {
return new InputStreamReader(new FileInputStream(getDetail()), "UTF-8");
return new InputStreamReader(new FileInputStream(getDetail()), StandardCharsets.UTF_8);
}
}

View File

@@ -29,6 +29,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
/** @see <a href="https://blogs.oracle.com/janp/entry/how_the_scp_protocol_works">SCP Protocol</a> */
class SCPEngine {
@@ -128,7 +129,7 @@ class SCPEngine {
baos.write(x);
}
}
final String msg = baos.toString(IOUtils.UTF8.displayName());
final String msg = baos.toString(StandardCharsets.UTF_8.displayName());
log.debug("Read message: `{}`", msg);
return msg;
}

View File

@@ -71,7 +71,7 @@ public class ScpCommandLine {
}
}
private LinkedHashMap<Arg, String> arguments = new LinkedHashMap<Arg, String>();
private final LinkedHashMap<Arg, String> arguments = new LinkedHashMap<Arg, String>();
private String path;
ScpCommandLine() {

View File

@@ -17,7 +17,6 @@ package com.hierynomus.sshj.connection.channel.forwarded;
import com.hierynomus.sshj.test.HttpServer;
import com.hierynomus.sshj.test.SshServerExtension;
import com.hierynomus.sshj.test.util.FileUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.LocalPortForwarder;
import net.schmizz.sshj.connection.channel.direct.Parameters;
@@ -29,13 +28,10 @@ import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LocalPortForwarderTest {
private static final String LOCALHOST_URL = "http://127.0.0.1:8080";
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@@ -43,21 +39,19 @@ public class LocalPortForwarderTest {
public HttpServer httpServer = new HttpServer();
@BeforeEach
public void setUp() throws IOException {
public void setUp() {
fixture.getServer().setForwardingFilter(new AcceptAllForwardingFilter());
File file = Files.createFile(httpServer.getDocRoot().toPath().resolve("index.html")).toFile();
FileUtil.writeToFile(file, "<html><head/><body><h1>Hi!</h1></body></html>");
}
@Test
public void shouldHaveWorkingHttpServer() throws IOException {
assertEquals(200, httpGet());
assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpGet());
}
@Test
public void shouldHaveHttpServerThatClosesConnectionAfterResponse() throws IOException {
// Just to check that the test server does close connections before we try through the forwarder...
httpGetAndAssertConnectionClosedByServer(8080);
httpGetAndAssertConnectionClosedByServer(httpServer.getServerUrl().getPort());
}
@Test
@@ -68,7 +62,8 @@ public class LocalPortForwarderTest {
ServerSocket serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress("0.0.0.0", 12345));
LocalPortForwarder localPortForwarder = sshClient.newLocalPortForwarder(new Parameters("0.0.0.0", 12345, "localhost", 8080), serverSocket);
final int serverPort = httpServer.getServerUrl().getPort();
LocalPortForwarder localPortForwarder = sshClient.newLocalPortForwarder(new Parameters("0.0.0.0", 12345, "localhost", serverPort), serverSocket);
new Thread(() -> {
try {
localPortForwarder.listen();
@@ -90,7 +85,7 @@ public class LocalPortForwarderTest {
// It returns 400 Bad Request because it's missing a bunch of info, but the HTTP response doesn't matter, we just want to test the connection closing.
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream);
writer.println("GET / HTTP/1.1");
writer.println("GET / HTTP/1.1\r\n");
writer.println("");
writer.flush();
@@ -111,7 +106,7 @@ public class LocalPortForwarderTest {
}
private int httpGet() throws IOException {
final URL url = new URL(LOCALHOST_URL);
final URL url = httpServer.getServerUrl().toURL();
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("GET");

View File

@@ -17,7 +17,6 @@ package com.hierynomus.sshj.connection.channel.forwarded;
import com.hierynomus.sshj.test.HttpServer;
import com.hierynomus.sshj.test.SshServerExtension;
import com.hierynomus.sshj.test.util.FileUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder;
@@ -27,20 +26,18 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RemotePortForwarderTest {
private static final PortRange RANGE = new PortRange(9000, 9999);
private static final String LOCALHOST = "127.0.0.1";
private static final String LOCALHOST_URL_FORMAT = "http://127.0.0.1:%d";
private static final InetSocketAddress HTTP_SERVER_SOCKET_ADDR = new InetSocketAddress(LOCALHOST, 8080);
private static final String URL_FORMAT = "http://%s:%d";
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@@ -49,21 +46,21 @@ public class RemotePortForwarderTest {
public HttpServer httpServer = new HttpServer();
@BeforeEach
public void setUp() throws IOException {
public void setUp() {
fixture.getServer().setForwardingFilter(new AcceptAllForwardingFilter());
File file = Files.createFile(httpServer.getDocRoot().toPath().resolve("index.html")).toFile();
FileUtil.writeToFile(file, "<html><head/><body><h1>Hi!</h1></body></html>");
}
@Test
public void shouldHaveWorkingHttpServer() throws IOException {
assertEquals(200, httpGet(8080));
final URI serverUrl = httpServer.getServerUrl();
assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpGet(serverUrl.getHost(), serverUrl.getPort()));
}
@Test
public void shouldDynamicallyForwardPortForLocalhost() throws IOException {
SSHClient sshClient = getFixtureClient();
RemotePortForwarder.Forward bind = forwardPort(sshClient, "127.0.0.1", new SinglePort(0));
RemotePortForwarder.Forward bind = forwardPort(sshClient, LOCALHOST, new SinglePort(0));
assertHttpGetSuccess(bind);
}
@@ -84,7 +81,7 @@ public class RemotePortForwarderTest {
@Test
public void shouldForwardPortForLocalhost() throws IOException {
SSHClient sshClient = getFixtureClient();
RemotePortForwarder.Forward bind = forwardPort(sshClient, "127.0.0.1", RANGE);
RemotePortForwarder.Forward bind = forwardPort(sshClient, LOCALHOST, RANGE);
assertHttpGetSuccess(bind);
}
@@ -103,17 +100,22 @@ public class RemotePortForwarderTest {
}
private void assertHttpGetSuccess(final RemotePortForwarder.Forward bind) throws IOException {
assertEquals(200, httpGet(bind.getPort()));
final String bindAddress = bind.getAddress();
final String address = bindAddress.isEmpty() ? LOCALHOST : bindAddress;
final int port = bind.getPort();
assertEquals(HttpURLConnection.HTTP_NOT_FOUND, httpGet(address, port));
}
private RemotePortForwarder.Forward forwardPort(SSHClient sshClient, String address, PortRange portRange) throws IOException {
while (true) {
final URI serverUrl = httpServer.getServerUrl();
final InetSocketAddress serverAddress = new InetSocketAddress(serverUrl.getHost(), serverUrl.getPort());
try {
return sshClient.getRemotePortForwarder().bind(
// where the server should listen
new RemotePortForwarder.Forward(address, portRange.nextPort()),
// what we do with incoming connections that are forwarded to us
new SocketForwardingConnectListener(HTTP_SERVER_SOCKET_ADDR));
new SocketForwardingConnectListener(serverAddress));
} catch (ConnectionException ce) {
if (!portRange.hasNext()) {
throw ce;
@@ -122,8 +124,8 @@ public class RemotePortForwarderTest {
}
}
private int httpGet(final int port) throws IOException {
final URL url = new URL(String.format(LOCALHOST_URL_FORMAT, port));
private int httpGet(final String address, final int port) throws IOException {
final URL url = new URL(String.format(URL_FORMAT, address, port));
final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("GET");

View File

@@ -19,42 +19,36 @@ import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.io.File;
import java.nio.file.Files;
import java.net.InetSocketAddress;
import java.net.URI;
/**
* Can be used to setup a test HTTP server
*/
public class HttpServer implements BeforeEachCallback, AfterEachCallback {
private org.glassfish.grizzly.http.server.HttpServer httpServer;
private static final String BIND_ADDRESS = "127.0.0.1";
private File docRoot ;
private com.sun.net.httpserver.HttpServer httpServer;
@Override
public void afterEach(ExtensionContext context) throws Exception {
public void afterEach(ExtensionContext context) {
try {
httpServer.shutdownNow();
} catch (Exception e) {}
try {
docRoot.delete();
} catch (Exception e) {}
httpServer.stop(0);
} catch (Exception ignored) {}
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
docRoot = Files.createTempDirectory("sshj").toFile();
httpServer = org.glassfish.grizzly.http.server.HttpServer.createSimpleServer(docRoot.getAbsolutePath());
httpServer = com.sun.net.httpserver.HttpServer.create();
final InetSocketAddress socketAddress = new InetSocketAddress(BIND_ADDRESS, 0);
httpServer.bind(socketAddress, 10);
httpServer.start();
}
public org.glassfish.grizzly.http.server.HttpServer getHttpServer() {
return httpServer;
}
public File getDocRoot() {
return docRoot;
public URI getServerUrl() {
final InetSocketAddress bindAddress = httpServer.getAddress();
final String serverUrl = String.format("http://%s:%d", BIND_ADDRESS, bindAddress.getPort());
return URI.create(serverUrl);
}
}

View File

@@ -18,6 +18,7 @@ package com.hierynomus.sshj.test.util;
import net.schmizz.sshj.common.IOUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class FileUtil {
@@ -34,12 +35,12 @@ public class FileUtil {
FileInputStream fileInputStream = new FileInputStream(f);
try {
ByteArrayOutputStream byteArrayOutputStream = IOUtils.readFully(fileInputStream);
return byteArrayOutputStream.toString(IOUtils.UTF8.displayName());
return byteArrayOutputStream.toString(StandardCharsets.UTF_8.displayName());
} finally {
IOUtils.closeQuietly(fileInputStream);
}
}
public static boolean compareFileContents(File f1, File f2) throws IOException {
return readFromFile(f1).equals(readFromFile(f2));
}

View File

@@ -19,13 +19,10 @@ import com.hierynomus.sshj.transport.cipher.GcmCiphers;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.security.Security;
import java.util.Arrays;
import java.util.stream.Stream;
@@ -42,11 +39,6 @@ public class GcmCipherDecryptSshPacketTest {
return Stream.of(Arguments.of("mina-sshd", 3), Arguments.of("openssh", 4));
}
@BeforeAll
public static void setupBeforeClass() {
Security.addProvider(new BouncyCastleProvider());
}
@ParameterizedTest
@MethodSource("sets")
public void testDecryptPacket(String ssh, int nr) throws Exception {

View File

@@ -16,10 +16,8 @@
package com.hierynomus.sshj.transport.verification;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts;
import net.schmizz.sshj.util.KeyUtil;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@@ -41,11 +39,6 @@ public class OpenSSHKnownHostsTest {
@TempDir
public File tempDir;
@BeforeAll
public static void setup() {
SecurityUtils.registerSecurityProvider("org.bouncycastle.jce.provider.BouncyCastleProvider");
}
@Test
public void shouldParseAndVerifyHashedHostEntry() throws Exception {
File knownHosts = knownHosts(

View File

@@ -0,0 +1,51 @@
/*
* 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.keepalive;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.connection.ConnectionImpl;
import net.schmizz.sshj.transport.Transport;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class HeartbeaterTest {
@Test
void ignoreMessageContainsData() throws Exception {
Transport transport = mock(Transport.class);
when(transport.getConfig()).thenReturn(new DefaultConfig());
ArgumentCaptor<SSHPacket> sshPacketCaptor = ArgumentCaptor.forClass(SSHPacket.class);
when(transport.write(sshPacketCaptor.capture())).thenReturn(0L);
ConnectionImpl connection = new ConnectionImpl(transport, KeepAliveProvider.HEARTBEAT);
KeepAlive heartbeater = connection.getKeepAlive();
assertThat(heartbeater).isInstanceOf(Heartbeater.class);
heartbeater.doKeepAlive();
SSHPacket sshPacket = sshPacketCaptor.getValue();
assertThat(sshPacket.readMessageID()).isEqualTo(Message.IGNORE);
assertThat(sshPacket.readBytes()).isNotNull();
}
}

View File

@@ -222,7 +222,7 @@ public class OpenSSHKeyFileTest {
OpenSSHKeyV1KeyFile keyFile = new OpenSSHKeyV1KeyFile();
keyFile.init(new File("src/test/resources/keytypes/test_ed25519"));
PrivateKey aPrivate = keyFile.getPrivate();
assertThat(aPrivate.getAlgorithm(), equalTo("EdDSA"));
assertThat(aPrivate.getAlgorithm(), equalTo("Ed25519"));
}
@Test
@@ -343,7 +343,7 @@ public class OpenSSHKeyFileTest {
WipeTrackingPasswordFinder pwf = new WipeTrackingPasswordFinder(password, withRetry);
keyFile.init(new File(key), pwf);
PrivateKey aPrivate = keyFile.getPrivate();
assertThat(aPrivate.getAlgorithm(), equalTo("EdDSA"));
assertThat(aPrivate.getAlgorithm(), equalTo("Ed25519"));
pwf.assertWiped();
}

View File

@@ -126,8 +126,8 @@ public class PKCS8KeyFileTest {
public void testPkcs8Ecdsa() throws IOException {
final PKCS8KeyFile provider = new PKCS8KeyFile();
provider.init(getFile("pkcs8-ecdsa"));
assertEquals(KeyAlgorithm.ECDSA, provider.getPublic().getAlgorithm());
assertEquals(KeyAlgorithm.ECDSA, provider.getPrivate().getAlgorithm());
assertEquals(KeyAlgorithm.EC_KEYSTORE, provider.getPublic().getAlgorithm());
assertEquals(KeyAlgorithm.EC_KEYSTORE, provider.getPrivate().getAlgorithm());
}
@Test

View File

@@ -425,7 +425,6 @@ public class PuTTYKeyFileTest {
PKCS8KeyFile referenceKey = new PKCS8KeyFile();
referenceKey.init(new File("src/test/resources/keytypes/test_ecdsa_nistp256"));
assertEquals(key.getPrivate(), referenceKey.getPrivate());
assertEquals(key.getPublic(), referenceKey.getPublic());
}
@@ -490,6 +489,8 @@ public class PuTTYKeyFileTest {
key.init(new StringReader(v3_rsa_argon2d), new UnitTestPasswordFinder("changeit"));
assertNotNull(key.getPrivate());
assertNotNull(key.getPublic());
assertEquals(3, key.getKeyFileVersion());
OpenSSHKeyV1KeyFile referenceKey = new OpenSSHKeyV1KeyFile();
referenceKey.init(new File("src/test/resources/keytypes/test_rsa_putty_priv.openssh2"));
RSAPrivateKey loadedPrivate = (RSAPrivateKey) key.getPrivate();

View File

@@ -17,11 +17,11 @@ package net.schmizz.sshj.signature;
import com.hierynomus.sshj.common.KeyAlgorithm;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.IOUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.DSAPrivateKeySpec;
@@ -47,7 +47,7 @@ public class SignatureDSATest {
BigInteger q = new BigInteger(new byte[] { 0, -105, 96, 80, -113, 21, 35, 11, -52, -78, -110, -71, -126, -94, -21, -124, 11, -16, 88, 28, -11 });
BigInteger g = new BigInteger(new byte[] { 0, -9, -31, -96, -123, -42, -101, 61, -34, -53, -68, -85, 92, 54, -72, 87, -71, 121, -108, -81, -69, -6, 58, -22, -126, -7, 87, 76, 11, 61, 7, -126, 103, 81, 89, 87, -114, -70, -44, 89, 79, -26, 113, 7, 16, -127, -128, -76, 73, 22, 113, 35, -24, 76, 40, 22, 19, -73, -49, 9, 50, -116, -56, -90, -31, 60, 22, 122, -117, 84, 124, -115, 40, -32, -93, -82, 30, 43, -77, -90, 117, -111, 110, -93, 127, 11, -6, 33, 53, 98, -15, -5, 98, 122, 1, 36, 59, -52, -92, -15, -66, -88, 81, -112, -119, -88, -125, -33, -31, 90, -27, -97, 6, -110, -117, 102, 94, -128, 123, 85, 37, 100, 1, 76, 59, -2, -49, 73, 42 });
byte[] data = "The Magic Words are Squeamish Ossifrage".getBytes(IOUtils.UTF8);
byte[] data = "The Magic Words are Squeamish Ossifrage".getBytes(StandardCharsets.UTF_8);
// A previously signed and verified signature using the data and DSA key parameters above.
byte[] dataSig = new byte[] { 0, 0, 0, 7, 115, 115, 104, 45, 100, 115, 115, 0, 0, 0, 40, 40, -71, 33, 105, -89, -107, 8, 26, -13, -90, 73, -103, 105, 112, 7, -59, -66, 46, 85, -27, 20, 82, 22, -113, -75, -86, -121, -42, -73, 78, 66, 93, -34, 39, -50, -93, 27, -5, 37, -92 };

View File

@@ -22,12 +22,10 @@ import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.security.SecureRandom;
import java.security.Security;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.mockito.ArgumentMatchers.any;
@@ -49,7 +47,6 @@ public class DecoderDecryptGcmCipherSshPacketTest {
@BeforeEach
public void setUp() throws Exception {
Security.addProvider(new BouncyCastleProvider());
ClassLoader classLoader = DecoderDecryptGcmCipherSshPacketTest.class.getClassLoader();
iv = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/mina-sshd/s2c.iv.bin" )).toByteArray();
key = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/mina-sshd/s2c.key.bin" )).toByteArray();

View File

@@ -17,6 +17,7 @@ package net.schmizz.sshj.transport.kex;
import net.schmizz.sshj.common.SecurityUtils;
import net.schmizz.sshj.transport.random.JCERandom;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -43,6 +44,7 @@ public class Curve25519DHTest {
};
@BeforeEach
@AfterEach
public void clearSecurityProvider() {
SecurityUtils.setSecurityProvider(null);
}

View File

@@ -17,10 +17,11 @@ package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import net.schmizz.sshj.common.SSHRuntimeException;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -28,9 +29,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
public class BaseMacTest {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "24ddeed57ad91465c5b59dce74ef73778bfb0cb9";
private static final String EXPECTED_HMAC = "24 dd ee d5 7a d9 14 65 c5 b5 9d ce 74 ef 73 77 8b fb 0c b9";
private static final String KEY = "et1Quo5ooCie6theel8i";
@Test
@@ -38,7 +39,7 @@ public class BaseMacTest {
BaseMAC hmac = Macs.HMACSHA1().create();
hmac.init((KEY + "foo").getBytes(CHARSET));
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
@@ -54,7 +55,7 @@ public class BaseMacTest {
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
@@ -67,13 +68,13 @@ public class BaseMacTest {
// update with the range from the second to penultimate byte
hmac.update(plainText, 1, PLAIN_TEXT.length);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
}
@Test
@@ -82,7 +83,7 @@ public class BaseMacTest {
byte[] resultBuf = new byte[20];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -16,30 +16,31 @@
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACMD596Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "dff33c507463f9cf088a5ce8";
private static final String EXPECTED_HMAC = "df f3 3c 50 74 63 f9 cf 08 8a 5c e8";
@Test
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)),
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)),
is(EXPECTED_HMAC));
}
@@ -49,7 +50,7 @@ public class HMACMD596Test {
byte[] resultBuf = new byte[12];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -16,30 +16,31 @@
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACMD5Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "dff33c507463f9cf088a5ce8d969c386";
private static final String EXPECTED_HMAC = "df f3 3c 50 74 63 f9 cf 08 8a 5c e8 d9 69 c3 86";
@Test
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
}
@Test
@@ -48,7 +49,7 @@ public class HMACMD5Test {
byte[] resultBuf = new byte[16];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -16,30 +16,31 @@
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA196Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "24ddeed57ad91465c5b59dce";
private static final String EXPECTED_HMAC = "24 dd ee d5 7a d9 14 65 c5 b5 9d ce";
@Test
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
}
@Test
@@ -48,7 +49,7 @@ public class HMACSHA196Test {
byte[] resultBuf = new byte[12];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -16,30 +16,31 @@
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA1Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "24ddeed57ad91465c5b59dce74ef73778bfb0cb9";
private static final String EXPECTED_HMAC = "24 dd ee d5 7a d9 14 65 c5 b5 9d ce 74 ef 73 77 8b fb 0c b9";
@Test
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
}
@Test
@@ -48,7 +49,7 @@ public class HMACSHA1Test {
byte[] resultBuf = new byte[20];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -16,30 +16,31 @@
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA2256Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "eb2207b2df36c7485f46d1be30418bc44e8134b4fdaabbe16d71f56ab24fce88";
private static final String EXPECTED_HMAC = "eb 22 07 b2 df 36 c7 48 5f 46 d1 be 30 41 8b c4 4e 81 34 b4 fd aa bb e1 6d 71 f5 6a b2 4f ce 88";
@Test
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
}
@Test
@@ -48,7 +49,7 @@ public class HMACSHA2256Test {
byte[] resultBuf = new byte[32];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -16,30 +16,31 @@
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA2512Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");
private static final Charset CHARSET = StandardCharsets.US_ASCII;
private static final byte[] PLAIN_TEXT = "Hello World".getBytes(CHARSET);
private static final String EXPECTED_HMAC = "28929cffc903039ef18cbc9cea6fd5f1420763af297a470d731236ed1f5a4c61d64dfccf6529265205bec932f2f7850c8ae4de1dc1a5259dc5b1fd85d8e62c04";
private static final String EXPECTED_HMAC = "28 92 9c ff c9 03 03 9e f1 8c bc 9c ea 6f d5 f1 42 07 63 af 29 7a 47 0d 73 12 36 ed 1f 5a 4c 61 d6 4d fc cf 65 29 26 52 05 be c9 32 f2 f7 85 0c 8a e4 de 1d c1 a5 25 9d c5 b1 fd 85 d8 e6 2c 04";
@Test
public void testUpdateWithDoFinal() {
BaseMAC hmac = initHmac();
hmac.update(PLAIN_TEXT);
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test
public void testDoFinalWithInput() {
BaseMAC hmac = initHmac();
assertThat(Hex.toHexString(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(hmac.doFinal(PLAIN_TEXT)), is(EXPECTED_HMAC));
}
@Test
@@ -48,7 +49,7 @@ public class HMACSHA2512Test {
byte[] resultBuf = new byte[64];
hmac.update(PLAIN_TEXT);
hmac.doFinal(resultBuf, 0);
assertThat(Hex.toHexString(resultBuf), is(EXPECTED_HMAC));
assertThat(BufferUtils.toHex(resultBuf), is(EXPECTED_HMAC));
}
private BaseMAC initHmac() {

View File

@@ -31,12 +31,12 @@
package net.schmizz.sshj.util;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.IOUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import static org.junit.jupiter.api.Assertions.*;
@@ -51,7 +51,7 @@ public class BufferTest {
public void setUp()
throws UnsupportedEncodingException, GeneralSecurityException {
// for position test
byte[] data = "Hello".getBytes(IOUtils.UTF8);
byte[] data = "Hello".getBytes(StandardCharsets.UTF_8);
posBuf = new Buffer.PlainBuffer(data);
handyBuf = new Buffer.PlainBuffer();
}

View File

@@ -15,13 +15,13 @@
*/
package net.schmizz.sshj.util.gss;
import net.schmizz.sshj.common.IOUtils;
import org.ietf.jgss.*;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static net.schmizz.sshj.util.gss.BogusGSSManager.unavailable;
@@ -34,7 +34,7 @@ public class BogusGSSContext
private static final byte[] MIC = fromString("LGTM");
private static byte[] fromString(String s) {
return s.getBytes(IOUtils.UTF8);
return s.getBytes(StandardCharsets.UTF_8);
}
private boolean initialized = false;