Compare commits

..

1 Commits

16 changed files with 338 additions and 19983 deletions

View File

@ -1,24 +0,0 @@
name: Build/test
on: [push]
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-22.04]
java: [8, 11, 17, 21]
fail-fast: false
name: JDK ${{ matrix.java }}
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Set up JDK
uses: actions/setup-java@9704b39bf258b59bc04b50fa2dd55e9ed76b47a8 # v4.1.0
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
cache: maven
- name: Test with Maven
run: mvn verify -B --file pom.xml

2
.gitignore vendored
View File

@ -4,5 +4,3 @@ target
.project
doc
*.class
*.iml
.idea/

View File

@ -1,15 +1,3 @@
This project is a fork of https://github.com/rweather/noise-java. The goal of
this fork is to make Noise-Java available via common artifact repositories like
[Maven Central](https://search.maven.org/). Substantive changes will be offered
as pull requests upstream wherever possible.
To avoid namespace collisions, the group identifier in this project's POM has
been changed to `org.signal.forks`, though package names within the artifact
have not changed.
The original README continues below.
----
Noise-Java Library
==================
@ -40,7 +28,7 @@ If you have better implementations of the cryptographic primitives
available, you can modify the createDH(), createCipher(), and
createHash() functions in the "Noise" class to integrate your versions.
The [package documentation](https://rweather.github.io/noise-java/index.html)
The [package documentation](http://rweather.github.io/noise-java/index.html)
contains more information on the classes in the Noise-Java library.
For more information on this library, to report bugs, to contribute,

8
makedoc.sh Executable file
View File

@ -0,0 +1,8 @@
#!/bin/sh
rm -rf doc/html
mkdir -p doc/html
exec javadoc -sourcepath NoiseJava/src \
-subpackages com.southernstorm.noise.protocol \
-d doc/html \
-windowtitle "Noise-Java" \
com.southernstorm.noise.protocol

135
pom.xml
View File

@ -1,43 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.signal.forks</groupId>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<artifactId>noise-java</artifactId>
<version>0.1.2-SNAPSHOT</version>
<name>Noise-Java</name>
<description>Plain Java implementation of the Noise protocol</description>
<inceptionYear>2016</inceptionYear>
<url>https://github.com/signalapp/noise-java</url>
<scm>
<connection>scm:git:https://github.com/signalapp/noise-java.git</connection>
<developerConnection>scm:git:git@github.com:signalapp/noise-java.git</developerConnection>
<url>https://github.com/signalapp/noise-java</url>
<tag>HEAD</tag>
</scm>
<developers>
<developer>
<id>rweather</id>
<name>Rhys Weatherley</name>
<email>rhys.weatherley@gmail.com</email>
<url>https://github.com/rweather/</url>
<roles>
<role>developer</role>
</roles>
</developer>
</developers>
<licenses>
<license>
<name>The MIT License (MIT)</name>
<url>http://opensource.org/licenses/MIT</url>
<distribution>repo</distribution>
</license>
</licenses>
<groupId>com.southerstorm</groupId>
<version>1.0-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -45,9 +13,9 @@
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
@ -57,16 +25,9 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@ -74,7 +35,6 @@
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
@ -84,83 +44,6 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<source>8</source>
<excludePackageNames>com.southernstorm.noise.crypto</excludePackageNames>
<windowtitle>Noise-Java</windowtitle>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.13</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>false</autoReleaseAfterClose>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>release-sign-artifacts</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -30,7 +30,7 @@ import java.io.Reader;
*
* Intentionally compatible with android.util.JsonReader.
*/
public class JsonReader implements AutoCloseable {
public class JsonReader {
private Reader in;
private JsonToken token;
@ -54,7 +54,6 @@ public class JsonReader implements AutoCloseable {
expectNext(JsonToken.BEGIN_OBJECT, "JSON begin object expected");
}
@Override
public void close() throws IOException {
in.close();
}

View File

@ -22,17 +22,18 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
import org.junit.Test;
import com.southernstorm.noise.protocol.CipherState;
import com.southernstorm.noise.protocol.Noise;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Perform tests on the cipher algorithms used by Noise.
@ -42,35 +43,51 @@ public class CipherStateTests {
private void testCipher(String name, int keyLen, int macLen,
String key, long nonce, String ad,
String plaintext, String ciphertext,
String mac, boolean forceFallbacks) throws NoSuchAlgorithmException, ShortBufferException, BadPaddingException {
String mac, boolean forceFallbacks)
{
byte[] keyBytes = TestUtils.stringToData(key);
byte[] adBytes = TestUtils.stringToData(ad);
byte[] plaintextBytes = TestUtils.stringToData(plaintext);
byte[] ciphertextBytes;
byte[] buffer;
if (ciphertext.length() > 0)
ciphertextBytes = TestUtils.stringToData(ciphertext + mac.substring(2));
else
ciphertextBytes = TestUtils.stringToData(mac);
final byte[] plaintextBuffer = new byte[plaintextBytes.length];
final byte[] ciphertextBuffer = new byte[ciphertextBytes.length];
// Create the cipher object and check its properties.
CipherState cipher = null;
Noise.setForceFallbacks(forceFallbacks);
final CipherState cipher = Noise.createCipher(name);
try {
cipher = Noise.createCipher(name);
} catch (NoSuchAlgorithmException e) {
fail(name + " cipher is not supported");
}
assertEquals(name, cipher.getCipherName());
assertEquals(keyLen, cipher.getKeyLength());
assertEquals(0, cipher.getMACLength()); // Key has not been set yet.
// Try to encrypt. Because the key is not set yet, this will
// return the plaintext as-is.
Arrays.fill(plaintextBuffer, (byte)0xAA);
assertEquals(plaintextBytes.length, cipher.encryptWithAd(adBytes, plaintextBytes, 0, plaintextBuffer, 0, plaintextBytes.length));
assertArrayEquals(plaintextBytes, plaintextBuffer);
try {
buffer = new byte [plaintextBytes.length];
Arrays.fill(buffer, (byte)0xAA);
assertEquals(plaintextBytes.length, cipher.encryptWithAd(adBytes, plaintextBytes, 0, buffer, 0, plaintextBytes.length));
assertArrayEquals(plaintextBytes, buffer);
} catch (ShortBufferException e) {
fail("Buffer should have been big enough");
}
// Try to decrypt. Will return the ciphertext and MAC as-is.
Arrays.fill(ciphertextBuffer, (byte)0xAA);
assertEquals(ciphertextBytes.length, cipher.decryptWithAd(adBytes, ciphertextBytes, 0, ciphertextBuffer, 0, ciphertextBytes.length));
buffer = new byte [ciphertextBytes.length];
Arrays.fill(buffer, (byte)0xAA);
try {
assertEquals(ciphertextBytes.length, cipher.decryptWithAd(adBytes, ciphertextBytes, 0, buffer, 0, ciphertextBytes.length));
} catch (BadPaddingException e) {
fail();
} catch (ShortBufferException e) {
fail();
}
// Set the key and fast-forward the nonce.
cipher.initializeKey(keyBytes, 0);
@ -78,24 +95,39 @@ public class CipherStateTests {
assertEquals(macLen, cipher.getMACLength());
// Encrypt the data.
Arrays.fill(ciphertextBuffer, (byte)0xAA);
assertEquals(ciphertextBytes.length, cipher.encryptWithAd(adBytes, plaintextBytes, 0, ciphertextBuffer, 0, plaintextBytes.length));
assertArrayEquals(ciphertextBytes, ciphertextBuffer);
try {
buffer = new byte [ciphertextBytes.length];
Arrays.fill(buffer, (byte)0xAA);
assertEquals(ciphertextBytes.length, cipher.encryptWithAd(adBytes, plaintextBytes, 0, buffer, 0, plaintextBytes.length));
assertArrayEquals(ciphertextBytes, buffer);
} catch (ShortBufferException e) {
fail("Buffer should have been big enough");
}
// Try to decrypt. The MAC check should fail because the internal
// nonce was incremented and no longer matches the parameter.
assertThrows(BadPaddingException.class, () ->
cipher.decryptWithAd(adBytes, ciphertextBytes, 0, ciphertextBuffer, 0, ciphertextBytes.length));
try {
cipher.decryptWithAd(adBytes, ciphertextBytes, 0, buffer, 0, ciphertextBytes.length);
fail();
} catch (BadPaddingException e) {
// Success!
} catch (ShortBufferException e) {
fail();
}
// Fast-forward the nonce to just before the rollover. We will be able
// to encrypt one more block, and then the next request will be rejected.
cipher.setNonce(-2L);
try {
Arrays.fill(ciphertextBuffer, (byte)0xAA);
cipher.encryptWithAd(adBytes, plaintextBytes, 0, ciphertextBuffer, 0, plaintextBytes.length);
assertThrows(IllegalStateException.class, () ->
cipher.encryptWithAd(adBytes, plaintextBytes, 0, ciphertextBuffer, 0, plaintextBytes.length));
buffer = new byte [ciphertextBytes.length];
Arrays.fill(buffer, (byte)0xAA);
cipher.encryptWithAd(adBytes, plaintextBytes, 0, buffer, 0, plaintextBytes.length);
try {
cipher.encryptWithAd(adBytes, plaintextBytes, 0, buffer, 0, plaintextBytes.length);
fail();
} catch (IllegalStateException e) {
// Success!
}
} catch (ShortBufferException e) {
fail("Buffer should have been big enough");
}
@ -106,34 +138,57 @@ public class CipherStateTests {
assertEquals(macLen, cipher.getMACLength());
// Decrypt the test ciphertext and MAC.
Arrays.fill(plaintextBuffer, (byte)0xAA);
assertEquals(plaintextBytes.length, cipher.decryptWithAd(adBytes, ciphertextBytes, 0, plaintextBuffer, 0, ciphertextBytes.length));
assertArrayEquals(plaintextBytes, plaintextBuffer);
try {
buffer = new byte [plaintextBytes.length];
Arrays.fill(buffer, (byte)0xAA);
assertEquals(plaintextBytes.length, cipher.decryptWithAd(adBytes, ciphertextBytes, 0, buffer, 0, ciphertextBytes.length));
assertArrayEquals(plaintextBytes, buffer);
} catch (BadPaddingException e) {
fail();
} catch (ShortBufferException e) {
fail();
}
// Fast-forward the nonce to just before the rollover. We will be able
// to decrypt one more block, and then the next request will be rejected.
cipher.setNonce(-2L);
try {
// Fast-forward the nonce to just before the rollover. We will be able
// to decrypt one more block, and then the next request will be rejected.
cipher.setNonce(-2L);
Arrays.fill(plaintextBuffer, (byte)0xAA);
assertThrows(BadPaddingException.class, () ->
cipher.decryptWithAd(adBytes, ciphertextBytes, 0, plaintextBuffer, 0, ciphertextBytes.length));
buffer = new byte [plaintextBytes.length];
Arrays.fill(buffer, (byte)0xAA);
try {
cipher.decryptWithAd(adBytes, ciphertextBytes, 0, buffer, 0, ciphertextBytes.length);
fail();
} catch (BadPaddingException e) {
// Success!
}
cipher.setNonce(-1L);
cipher.setNonce(-1L);
assertThrows(IllegalStateException.class, () ->
cipher.decryptWithAd(adBytes, ciphertextBytes, 0, plaintextBuffer, 0, ciphertextBytes.length));
try {
cipher.decryptWithAd(adBytes, ciphertextBytes, 0, buffer, 0, ciphertextBytes.length);
fail();
} catch (IllegalStateException e) {
// Success!
} catch (BadPaddingException e) {
fail();
}
} catch (ShortBufferException e) {
fail("Buffer should have been big enough");
}
}
private void testCipher(String name, int keyLen, int macLen,
String key, long nonce, String ad,
String plaintext, String ciphertext,
String mac) throws ShortBufferException, NoSuchAlgorithmException, BadPaddingException {
String mac)
{
testCipher(name, keyLen, macLen, key, nonce, ad, plaintext, ciphertext, mac, true);
testCipher(name, keyLen, macLen, key, nonce, ad, plaintext, ciphertext, mac, false);
}
@Test
public void AESGCM() throws ShortBufferException, NoSuchAlgorithmException, BadPaddingException {
public void AESGCM() {
/* Test vectors for AES in GCM mode from Appendix B of:
http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
We can only use a few of the vectors because most of the IV's in the
@ -161,7 +216,7 @@ public class CipherStateTests {
}
@Test
public void ChaChaPoly() throws ShortBufferException, NoSuchAlgorithmException, BadPaddingException {
public void ChaChaPoly() {
// ChaChaPoly test vectors from Appendix A.5 of RFC 7539.
testCipher
("ChaChaPoly", 32, 16,

View File

@ -22,12 +22,13 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.util.Arrays;
import com.southernstorm.noise.crypto.Curve25519;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import com.southernstorm.noise.crypto.Curve25519;
public class Curve25519Tests {

View File

@ -22,12 +22,13 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.util.Arrays;
import com.southernstorm.noise.crypto.Curve448;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import com.southernstorm.noise.crypto.Curve448;
public class Curve448Tests {

View File

@ -22,12 +22,13 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.util.Arrays;
import com.southernstorm.noise.crypto.GHASH;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import com.southernstorm.noise.crypto.GHASH;
public class GHASHTests {

View File

@ -22,21 +22,23 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.southernstorm.noise.protocol.Noise;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import com.southernstorm.noise.protocol.Noise;
/**
* Perform tests on the hash algorithms used by Noise.
*/
public class HashTests {
private void testHash(MessageDigest digest, String input, String hash) throws DigestException {
private void testHash(MessageDigest digest, String input, String hash)
{
byte[] inputBytes = TestUtils.stringToData(input);
byte[] hashBytes = TestUtils.stringToData(hash);
byte[] result = new byte [digest.getDigestLength()];
@ -44,36 +46,50 @@ public class HashTests {
// Hash the entire input in one request.
digest.reset();
digest.update(inputBytes);
digest.digest(result, 0, result.length);
try {
digest.digest(result, 0, result.length);
} catch (DigestException e) {
fail("digest failed");
}
assertArrayEquals(hashBytes, result);
// Hash the input in pieces to test split requests.
digest.reset();
digest.update(inputBytes, 0, inputBytes.length / 2);
digest.update(inputBytes, inputBytes.length / 2, inputBytes.length - (inputBytes.length / 2));
digest.digest(result, 0, result.length);
try {
digest.digest(result, 0, result.length);
} catch (DigestException e) {
fail("digest failed");
}
assertArrayEquals(hashBytes, result);
}
private void testHash(String name, String input, String hash) throws NoSuchAlgorithmException, DigestException {
private void testHash(String name, String input, String hash)
{
MessageDigest digest = null;
Noise.setForceFallbacks(true);
try {
digest = Noise.createHash(name);
} catch (NoSuchAlgorithmException e) {
fail("No crypto provider for " + name);
} finally {
Noise.setForceFallbacks(false);
}
testHash(digest, input, hash);
Noise.setForceFallbacks(false);
digest = Noise.createHash(name);
try {
digest = Noise.createHash(name);
} catch (NoSuchAlgorithmException e) {
fail("No crypto provider for " + name);
}
testHash(digest, input, hash);
}
@Test
public void blake2b() throws DigestException, NoSuchAlgorithmException {
public void blake2b() {
testHash("BLAKE2b", "", "0x786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce");
testHash("BLAKE2b", "abc", "0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923");
testHash("BLAKE2b", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "0x7285ff3e8bd768d69be62b3bf18765a325917fa9744ac2f582a20850bc2b1141ed1b3e4528595acc90772bdf2d37dc8a47130b44f33a02e8730e5ad8e166e888");
@ -81,7 +97,7 @@ public class HashTests {
}
@Test
public void blake2s() throws DigestException, NoSuchAlgorithmException {
public void blake2s() {
testHash("BLAKE2s", "", "0x69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9");
testHash("BLAKE2s", "abc", "0x508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982");
testHash("BLAKE2s", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "0x6f4df5116a6f332edab1d9e10ee87df6557beab6259d7663f3bcd5722c13f189");
@ -89,14 +105,14 @@ public class HashTests {
}
@Test
public void sha256() throws DigestException, NoSuchAlgorithmException {
public void sha256() {
testHash("SHA256", "", "0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
testHash("SHA256", "abc", "0xba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
testHash("SHA256", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "0x248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
}
@Test
public void sha512() throws DigestException, NoSuchAlgorithmException {
public void sha512() {
testHash("SHA512", "", "0xcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
testHash("SHA512", "abc", "0xddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
testHash("SHA512", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "0x8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");

View File

@ -22,12 +22,13 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.util.Arrays;
import com.southernstorm.noise.crypto.Poly1305;
import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import com.southernstorm.noise.crypto.Poly1305;
/**
* Perform tests on the Poly1305 implementation in isolation from ChaChaPoly.

View File

@ -22,12 +22,13 @@
package com.southernstorm.noise.tests;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import com.southernstorm.noise.crypto.RijndaelAES;
import org.junit.jupiter.api.Test;
/**
* AES test cases to verify the fallback RijndaelAES implementation.

View File

@ -0,0 +1,22 @@
package com.southernstorm.noise.tests;
import java.io.InputStream;
import java.net.URL;
import org.junit.Assert;
import org.junit.Test;
public class UnitVectorTests {
private static final String testVectorsCommit = "5d0a74760320e5486ced302e36ccad91606aac43";
@Test
public void testBasicVector() throws Exception {
try (InputStream stream = new URL(
"https://raw.githubusercontent.com/rweather/noise-c/" + testVectorsCommit
+ "/tests/vector/noise-c-basic.txt").openStream()) {
VectorTests vectorTests = new VectorTests();
vectorTests.processInputStream(stream);
Assert.assertEquals(vectorTests.getFailed(), 0);
}
}
}

View File

@ -22,14 +22,16 @@
package com.southernstorm.noise.tests;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import javax.crypto.BadPaddingException;
import javax.crypto.ShortBufferException;
@ -39,22 +41,27 @@ import com.southernstorm.json.JsonReader;
import com.southernstorm.noise.protocol.CipherState;
import com.southernstorm.noise.protocol.CipherStatePair;
import com.southernstorm.noise.protocol.HandshakeState;
import org.junit.jupiter.api.Named;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
/**
* Executes Noise vector tests in JSON format.
*/
public class VectorTests {
private int total;
private int failed;
private int skipped;
public VectorTests()
{
total = 0;
failed = 0;
skipped = 0;
}
/**
* Information about a handshake or transport message.
*/
private static class TestMessage
private class TestMessage
{
public byte[] payload;
public byte[] ciphertext;
@ -63,7 +70,7 @@ public class VectorTests {
/**
* Information about a Noise test vector that was parsed from a JSON stream.
*/
private static class TestVector
private class TestVector
{
public String name;
public String pattern;
@ -90,7 +97,7 @@ public class VectorTests {
public boolean failure_expected;
public boolean fallback_expected;
public TestMessage[] messages;
public void addMessage(TestMessage msg)
{
TestMessage[] newMessages;
@ -109,20 +116,18 @@ public class VectorTests {
private void assertSubArrayEquals(String msg, byte[] expected, byte[] actual)
{
for (int index = 0; index < expected.length; ++index)
assertEquals(expected[index], actual[index], msg + "[" + index + "]");
assertEquals(msg + "[" + Integer.toString(index) + "]", expected[index], actual[index]);
}
@ParameterizedTest
@MethodSource
void testVectors(TestVector vec) throws ShortBufferException, BadPaddingException, NoSuchAlgorithmException
/**
* Runs a Noise test vector.
*
* @param vec The test vector.
* @param initiator Handshake object for the initiator.
* @param responder Handshake object for the responder.
*/
private void runTest(TestVector vec, HandshakeState initiator, HandshakeState responder) throws ShortBufferException, BadPaddingException, NoSuchAlgorithmException
{
HandshakeState initiator = new HandshakeState(vec.name, HandshakeState.INITIATOR);
HandshakeState responder = new HandshakeState(vec.name, HandshakeState.RESPONDER);
assertEquals(HandshakeState.INITIATOR, initiator.getRole());
assertEquals(HandshakeState.RESPONDER, responder.getRole());
assertEquals(vec.name, initiator.getProtocolName());
assertEquals(vec.name, responder.getProtocolName());
// Set all keys and special values that we need.
if (vec.init_prologue != null)
initiator.setPrologue(vec.init_prologue, 0, vec.init_prologue.length);
@ -164,13 +169,12 @@ public class VectorTests {
// Work through the messages one by one until both sides "split".
int role = HandshakeState.INITIATOR;
int index = 0;
HandshakeState send, recv;
boolean isOneWay = (vec.pattern.length() == 1);
boolean fallback = vec.fallback_expected;
byte[] message = new byte [8192];
byte[] plaintext = new byte [8192];
for (; index < vec.messages.length; ++index) {
final HandshakeState send, recv;
if (initiator.getAction() == HandshakeState.SPLIT &&
responder.getAction() == HandshakeState.SPLIT) {
break;
@ -192,11 +196,15 @@ public class VectorTests {
TestMessage msg = vec.messages[index];
int len = send.writeMessage(message, 0, msg.payload, 0, msg.payload.length);
assertEquals(msg.ciphertext.length, len);
assertSubArrayEquals(index + ": ciphertext", msg.ciphertext, message);
assertSubArrayEquals(Integer.toString(index) + ": ciphertext", msg.ciphertext, message);
if (fallback) {
// Perform a read on the responder, which will fail.
assertThrows(BadPaddingException.class, () -> recv.readMessage(message, 0, len, plaintext, 0),
"read should have triggered fallback");
try {
recv.readMessage(message, 0, len, plaintext, 0);
fail("read should have triggered fallback");
} catch (BadPaddingException e) {
// Success!
}
// Look up the pattern to fall back to.
String pattern = vec.fallback_pattern;
@ -216,7 +224,7 @@ public class VectorTests {
} else {
int plen = recv.readMessage(message, 0, len, plaintext, 0);
assertEquals(msg.payload.length, plen);
assertSubArrayEquals(index + ": payload", msg.payload, plaintext);
assertSubArrayEquals(Integer.toString(index) + ": payload", msg.payload, plaintext);
}
}
if (vec.fallback_expected) {
@ -268,10 +276,10 @@ public class VectorTests {
}
int len = csend.encryptWithAd(null, msg.payload, 0, message, 0, msg.payload.length);
assertEquals(msg.ciphertext.length, len);
assertSubArrayEquals(index + ": ciphertext", msg.ciphertext, message);
assertSubArrayEquals(Integer.toString(index) + ": ciphertext", msg.ciphertext, message);
int plen = crecv.decryptWithAd(null, message, 0, plaintext, 0, len);
assertEquals(msg.payload.length, plen);
assertSubArrayEquals(index + ": payload", msg.payload, plaintext);
assertSubArrayEquals(Integer.toString(index) + ": payload", msg.payload, plaintext);
}
// Clean up.
@ -281,20 +289,16 @@ public class VectorTests {
respPair.destroy();
}
private static Stream<Arguments> testVectors() throws IOException {
try (InputStream testVectorInputStream = VectorTests.class.getResourceAsStream("test-vectors.json")) {
if (testVectorInputStream == null) {
throw new IOException("Could not load test vectors");
}
return loadTestVectors(testVectorInputStream).stream()
.map(testVector -> Arguments.of(Named.of(testVector.name, testVector)));
}
}
private static TestVector getNextVector(final JsonReader reader) throws IOException
/**
* Processes a single test vector from an input stream.
*
* @param reader The JSON reader for the input stream.
*
* The reader is positioned on the first field of the vector object.
*/
private void processVector(JsonReader reader) throws IOException
{
boolean res = true;
boolean res = true;
// Parse the contents of the test vector.
TestVector vec = new TestVector();
while (reader.hasNext()) {
@ -381,31 +385,116 @@ public class VectorTests {
if (vec.name == null)
vec.name = protocolName;
return vec;
}
private static List<TestVector> loadTestVectors(InputStream jsonInputStream) throws IOException {
List<TestVector> testVectors = new ArrayList<>();
try (JsonReader jsonReader = new JsonReader(new BufferedReader(new InputStreamReader(jsonInputStream)))) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("vectors")) {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonReader.beginObject();
testVectors.add(getNextVector(jsonReader));
jsonReader.endObject();
}
jsonReader.endArray();
// Execute the test vector.
++total;
System.out.print(vec.name);
System.out.print(" ... ");
System.out.flush();
try {
HandshakeState initiator = new HandshakeState(protocolName, HandshakeState.INITIATOR);
HandshakeState responder = new HandshakeState(protocolName, HandshakeState.RESPONDER);
assertEquals(HandshakeState.INITIATOR, initiator.getRole());
assertEquals(HandshakeState.RESPONDER, responder.getRole());
assertEquals(protocolName, initiator.getProtocolName());
assertEquals(protocolName, responder.getProtocolName());
runTest(vec, initiator, responder);
if (!vec.failure_expected) {
System.out.println("ok");
} else {
jsonReader.skipValue();
System.out.println("failure expected");
++failed;
}
} catch (NoSuchAlgorithmException e) {
System.out.println("unsupported");
++skipped;
} catch (AssertionError e) {
System.out.println(e.getMessage());
e.printStackTrace(System.out);
++failed;
} catch (Exception e) {
if (!vec.failure_expected) {
System.out.println("failed");
e.printStackTrace(System.out);
++failed;
} else {
System.out.println("ok");
}
}
jsonReader.endObject();
}
public void processFile(String filename) throws IOException {
try {
try (FileInputStream fileStream = new FileInputStream(filename)) {
System.out.print(filename + ": ");
processInputStream(fileStream);
}
} catch (FileNotFoundException e) {
System.err.println(filename + ": File not found");
}
}
public void processInputStream(InputStream jsonInputStream) throws IOException {
try(Reader streamReader = new BufferedReader(new InputStreamReader(jsonInputStream))) {
processReader(streamReader);
}
}
public void processReader(Reader jsonStream) throws IOException {
total = 0;
skipped = 0;
failed = 0;
JsonReader reader = new JsonReader(jsonStream);
try {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("vectors")) {
reader.beginArray();
while (reader.hasNext() /*&& total < 50*/) {
reader.beginObject();
processVector(reader);
reader.endObject();
}
reader.endArray();
} else {
reader.skipValue();
}
}
reader.endObject();
} catch (IOException e) {
System.err.println("Exception while parsing JSON: " + e.toString());
e.printStackTrace();
} finally {
reader.close();
}
System.out.print(total);
System.out.print(" tests, ");
System.out.print(skipped);
System.out.print(" skipped, ");
System.out.print(failed);
System.out.println(" failed");
}
return testVectors;
public int getTotal() {
return total;
}
public int getFailed() {
return failed;
}
public int getSkipped() {
return skipped;
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.out.println("Usage: VectorTests file1 file2 ...");
return;
}
VectorTests app = new VectorTests();
for (String filename : args)
app.processFile(filename);
}
}