Migrated core and extension modules to Kotlin

(Except BitmessageContext and Bytes)
This commit is contained in:
2017-06-06 16:36:07 +02:00
parent 811625c051
commit fa0e53289c
213 changed files with 9846 additions and 11067 deletions

View File

@ -1,146 +0,0 @@
/*
* Copyright 2015 Christian Basler
*
* 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 ch.dissem.bitmessage.extensions;
import ch.dissem.bitmessage.entity.BitmessageAddress;
import ch.dissem.bitmessage.entity.CustomMessage;
import ch.dissem.bitmessage.entity.Streamable;
import ch.dissem.bitmessage.entity.payload.CryptoBox;
import ch.dissem.bitmessage.entity.payload.Pubkey;
import ch.dissem.bitmessage.exception.DecryptionFailedException;
import ch.dissem.bitmessage.factory.Factory;
import ch.dissem.bitmessage.utils.Encode;
import java.io.*;
import static ch.dissem.bitmessage.utils.Decode.*;
import static ch.dissem.bitmessage.utils.Singleton.cryptography;
/**
* A {@link CustomMessage} implementation that contains signed and encrypted data.
*
* @author Christian Basler
*/
public class CryptoCustomMessage<T extends Streamable> extends CustomMessage {
private static final long serialVersionUID = 7395193565986284426L;
public static final String COMMAND = "ENCRYPTED";
private final Reader<T> dataReader;
private CryptoBox container;
private BitmessageAddress sender;
private T data;
public CryptoCustomMessage(T data) throws IOException {
super(COMMAND);
this.data = data;
this.dataReader = null;
}
private CryptoCustomMessage(CryptoBox container, Reader<T> dataReader) {
super(COMMAND);
this.container = container;
this.dataReader = dataReader;
}
public static <T extends Streamable> CryptoCustomMessage<T> read(CustomMessage data, Reader<T> dataReader) throws IOException {
CryptoBox cryptoBox = CryptoBox.read(new ByteArrayInputStream(data.getData()), data.getData().length);
return new CryptoCustomMessage<>(cryptoBox, dataReader);
}
public BitmessageAddress getSender() {
return sender;
}
public void signAndEncrypt(BitmessageAddress identity, byte[] publicKey) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Encode.varInt(identity.getVersion(), out);
Encode.varInt(identity.getStream(), out);
Encode.int32(identity.getPubkey().getBehaviorBitfield(), out);
out.write(identity.getPubkey().getSigningKey(), 1, 64);
out.write(identity.getPubkey().getEncryptionKey(), 1, 64);
if (identity.getVersion() >= 3) {
Encode.varInt(identity.getPubkey().getNonceTrialsPerByte(), out);
Encode.varInt(identity.getPubkey().getExtraBytes(), out);
}
data.write(out);
Encode.varBytes(cryptography().getSignature(out.toByteArray(), identity.getPrivateKey()), out);
container = new CryptoBox(out.toByteArray(), publicKey);
}
public T decrypt(byte[] privateKey) throws IOException, DecryptionFailedException {
SignatureCheckingInputStream in = new SignatureCheckingInputStream(container.decrypt(privateKey));
long addressVersion = varInt(in);
long stream = varInt(in);
int behaviorBitfield = int32(in);
byte[] publicSigningKey = bytes(in, 64);
byte[] publicEncryptionKey = bytes(in, 64);
long nonceTrialsPerByte = addressVersion >= 3 ? varInt(in) : 0;
long extraBytes = addressVersion >= 3 ? varInt(in) : 0;
sender = new BitmessageAddress(Factory.createPubkey(
addressVersion,
stream,
publicSigningKey,
publicEncryptionKey,
nonceTrialsPerByte,
extraBytes,
behaviorBitfield
));
data = dataReader.read(sender, in);
in.checkSignature(sender.getPubkey());
return data;
}
@Override
public void write(OutputStream out) throws IOException {
Encode.varString(COMMAND, out);
container.write(out);
}
public interface Reader<T> {
T read(BitmessageAddress sender, InputStream in) throws IOException;
}
private class SignatureCheckingInputStream extends InputStream {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final InputStream wrapped;
private SignatureCheckingInputStream(InputStream wrapped) {
this.wrapped = wrapped;
}
@Override
public int read() throws IOException {
int read = wrapped.read();
if (read >= 0) out.write(read);
return read;
}
public void checkSignature(Pubkey pubkey) throws IOException, IllegalStateException {
if (!cryptography().isSignatureValid(out.toByteArray(), varBytes(wrapped), pubkey)) {
throw new IllegalStateException("Signature check failed");
}
}
}
}

View File

@ -1,134 +0,0 @@
/*
* Copyright 2015 Christian Basler
*
* 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 ch.dissem.bitmessage.extensions.pow;
import ch.dissem.bitmessage.entity.BitmessageAddress;
import ch.dissem.bitmessage.entity.Streamable;
import ch.dissem.bitmessage.extensions.CryptoCustomMessage;
import ch.dissem.bitmessage.utils.Encode;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import static ch.dissem.bitmessage.utils.Decode.*;
/**
* @author Christian Basler
*/
public class ProofOfWorkRequest implements Streamable {
private static final long serialVersionUID = 4729003751499662713L;
private final BitmessageAddress sender;
private final byte[] initialHash;
private final Request request;
private final byte[] data;
public ProofOfWorkRequest(BitmessageAddress sender, byte[] initialHash, Request request) {
this(sender, initialHash, request, new byte[0]);
}
public ProofOfWorkRequest(BitmessageAddress sender, byte[] initialHash, Request request, byte[] data) {
this.sender = sender;
this.initialHash = initialHash;
this.request = request;
this.data = data;
}
public static ProofOfWorkRequest read(BitmessageAddress client, InputStream in) throws IOException {
return new ProofOfWorkRequest(
client,
bytes(in, 64),
Request.valueOf(varString(in)),
varBytes(in)
);
}
public BitmessageAddress getSender() {
return sender;
}
public byte[] getInitialHash() {
return initialHash;
}
public Request getRequest() {
return request;
}
public byte[] getData() {
return data;
}
@Override
public void write(OutputStream out) throws IOException {
out.write(initialHash);
Encode.varString(request.name(), out);
Encode.varBytes(data, out);
}
@Override
public void write(ByteBuffer buffer) {
buffer.put(initialHash);
Encode.varString(request.name(), buffer);
Encode.varBytes(data, buffer);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProofOfWorkRequest other = (ProofOfWorkRequest) o;
if (!sender.equals(other.sender)) return false;
if (!Arrays.equals(initialHash, other.initialHash)) return false;
if (request != other.request) return false;
return Arrays.equals(data, other.data);
}
@Override
public int hashCode() {
int result = sender.hashCode();
result = 31 * result + Arrays.hashCode(initialHash);
result = 31 * result + request.hashCode();
result = 31 * result + Arrays.hashCode(data);
return result;
}
public static class Reader implements CryptoCustomMessage.Reader<ProofOfWorkRequest> {
private final BitmessageAddress identity;
public Reader(BitmessageAddress identity) {
this.identity = identity;
}
@Override
public ProofOfWorkRequest read(BitmessageAddress sender, InputStream in) throws IOException {
return ProofOfWorkRequest.read(identity, in);
}
}
public enum Request {
CALCULATE,
CALCULATING,
COMPLETE
}
}

View File

@ -0,0 +1,146 @@
/*
* Copyright 2017 Christian Basler
*
* 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 ch.dissem.bitmessage.extensions
import ch.dissem.bitmessage.entity.BitmessageAddress
import ch.dissem.bitmessage.entity.CustomMessage
import ch.dissem.bitmessage.entity.Streamable
import ch.dissem.bitmessage.entity.payload.CryptoBox
import ch.dissem.bitmessage.entity.payload.Pubkey
import ch.dissem.bitmessage.exception.DecryptionFailedException
import ch.dissem.bitmessage.factory.Factory
import ch.dissem.bitmessage.utils.Decode.bytes
import ch.dissem.bitmessage.utils.Decode.int32
import ch.dissem.bitmessage.utils.Decode.varBytes
import ch.dissem.bitmessage.utils.Decode.varInt
import ch.dissem.bitmessage.utils.Encode
import ch.dissem.bitmessage.utils.Singleton.cryptography
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.OutputStream
/**
* A [CustomMessage] implementation that contains signed and encrypted data.
* @author Christian Basler
*/
class CryptoCustomMessage<T : Streamable> : CustomMessage {
private val dataReader: Reader<T>?
private var container: CryptoBox? = null
var sender: BitmessageAddress? = null
private set
private var data: T? = null
private set
constructor(data: T) : super(COMMAND, null) {
this.data = data
this.dataReader = null
}
private constructor(container: CryptoBox, dataReader: Reader<T>) : super(COMMAND, null) {
this.container = container
this.dataReader = dataReader
}
fun signAndEncrypt(identity: BitmessageAddress, publicKey: ByteArray) {
val out = ByteArrayOutputStream()
val privateKey = identity.privateKey ?: throw IllegalStateException("signing identity must have a private key")
Encode.varInt(identity.version, out)
Encode.varInt(identity.stream, out)
Encode.int32(privateKey.pubkey.behaviorBitfield.toLong(), out)
out.write(privateKey.pubkey.signingKey, 1, 64)
out.write(privateKey.pubkey.encryptionKey, 1, 64)
if (identity.version >= 3) {
Encode.varInt(privateKey.pubkey.nonceTrialsPerByte, out)
Encode.varInt(privateKey.pubkey.extraBytes, out)
}
data?.write(out) ?: throw IllegalStateException("no unencrypted data available")
Encode.varBytes(cryptography().getSignature(out.toByteArray(), privateKey), out)
container = CryptoBox(out.toByteArray(), publicKey)
}
@Throws(DecryptionFailedException::class)
fun decrypt(privateKey: ByteArray): T {
val `in` = SignatureCheckingInputStream(container?.decrypt(privateKey) ?: throw IllegalStateException("no encrypted data available"))
if (dataReader == null) throw IllegalStateException("no data reader available")
val addressVersion = varInt(`in`)
val stream = varInt(`in`)
val behaviorBitfield = int32(`in`)
val publicSigningKey = bytes(`in`, 64)
val publicEncryptionKey = bytes(`in`, 64)
val nonceTrialsPerByte = if (addressVersion >= 3) varInt(`in`) else 0
val extraBytes = if (addressVersion >= 3) varInt(`in`) else 0
val sender = BitmessageAddress(Factory.createPubkey(
addressVersion,
stream,
publicSigningKey,
publicEncryptionKey,
nonceTrialsPerByte,
extraBytes,
behaviorBitfield
))
this.sender = sender
data = dataReader.read(sender, `in`)
`in`.checkSignature(sender.pubkey!!)
return data!!
}
override fun write(out: OutputStream) {
Encode.varString(COMMAND, out)
container?.write(out) ?: throw IllegalStateException("not encrypted yet")
}
interface Reader<T> {
fun read(sender: BitmessageAddress, `in`: InputStream): T
}
private inner class SignatureCheckingInputStream internal constructor(private val wrapped: InputStream) : InputStream() {
private val out = ByteArrayOutputStream()
override fun read(): Int {
val read = wrapped.read()
if (read >= 0) out.write(read)
return read
}
@Throws(IllegalStateException::class)
fun checkSignature(pubkey: Pubkey) {
if (!cryptography().isSignatureValid(out.toByteArray(), varBytes(wrapped), pubkey)) {
throw IllegalStateException("Signature check failed")
}
}
}
companion object {
@JvmField val COMMAND = "ENCRYPTED"
@JvmStatic fun <T : Streamable> read(data: CustomMessage, dataReader: Reader<T>): CryptoCustomMessage<T> {
val cryptoBox = CryptoBox.read(ByteArrayInputStream(data.getData()), data.getData().size)
return CryptoCustomMessage(cryptoBox, dataReader)
}
}
}

View File

@ -0,0 +1,89 @@
/*
* Copyright 2017 Christian Basler
*
* 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 ch.dissem.bitmessage.extensions.pow
import ch.dissem.bitmessage.entity.BitmessageAddress
import ch.dissem.bitmessage.entity.Streamable
import ch.dissem.bitmessage.extensions.CryptoCustomMessage
import ch.dissem.bitmessage.utils.Decode.bytes
import ch.dissem.bitmessage.utils.Decode.varBytes
import ch.dissem.bitmessage.utils.Decode.varString
import ch.dissem.bitmessage.utils.Encode
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.util.*
/**
* @author Christian Basler
*/
data class ProofOfWorkRequest @JvmOverloads constructor(val sender: BitmessageAddress, val initialHash: ByteArray, val request: ProofOfWorkRequest.Request, val data: ByteArray = ByteArray(0)) : Streamable {
override fun write(out: OutputStream) {
out.write(initialHash)
Encode.varString(request.name, out)
Encode.varBytes(data, out)
}
override fun write(buffer: ByteBuffer) {
buffer.put(initialHash)
Encode.varString(request.name, buffer)
Encode.varBytes(data, buffer)
}
class Reader(private val identity: BitmessageAddress) : CryptoCustomMessage.Reader<ProofOfWorkRequest> {
override fun read(sender: BitmessageAddress, `in`: InputStream): ProofOfWorkRequest {
return ProofOfWorkRequest.read(identity, `in`)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ProofOfWorkRequest) return false
if (sender != other.sender) return false
if (!Arrays.equals(initialHash, other.initialHash)) return false
if (request != other.request) return false
return Arrays.equals(data, other.data)
}
override fun hashCode(): Int {
var result = sender.hashCode()
result = 31 * result + Arrays.hashCode(initialHash)
result = 31 * result + request.hashCode()
result = 31 * result + Arrays.hashCode(data)
return result
}
enum class Request {
CALCULATE,
CALCULATING,
COMPLETE
}
companion object {
fun read(client: BitmessageAddress, `in`: InputStream): ProofOfWorkRequest {
return ProofOfWorkRequest(
client,
bytes(`in`, 64),
Request.valueOf(varString(`in`)),
varBytes(`in`)
)
}
}
}

View File

@ -1,86 +0,0 @@
/*
* Copyright 2015 Christian Basler
*
* 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 ch.dissem.bitmessage.extensions;
import ch.dissem.bitmessage.entity.BitmessageAddress;
import ch.dissem.bitmessage.entity.CustomMessage;
import ch.dissem.bitmessage.entity.payload.GenericPayload;
import ch.dissem.bitmessage.entity.valueobject.PrivateKey;
import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest;
import ch.dissem.bitmessage.utils.TestBase;
import ch.dissem.bitmessage.utils.TestUtils;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static ch.dissem.bitmessage.utils.Singleton.cryptography;
import static org.junit.Assert.assertEquals;
public class CryptoCustomMessageTest extends TestBase {
@Test
public void ensureEncryptThenDecryptYieldsSameObject() throws Exception {
PrivateKey privateKey = PrivateKey.read(TestUtils.getResource("BM-2cSqjfJ8xK6UUn5Rw3RpdGQ9RsDkBhWnS8.privkey"));
BitmessageAddress sendingIdentity = new BitmessageAddress(privateKey);
GenericPayload payloadBefore = new GenericPayload(0, 1, cryptography().randomBytes(100));
CryptoCustomMessage<GenericPayload> messageBefore = new CryptoCustomMessage<>(payloadBefore);
messageBefore.signAndEncrypt(sendingIdentity, cryptography().createPublicKey(sendingIdentity.getPublicDecryptionKey()));
ByteArrayOutputStream out = new ByteArrayOutputStream();
messageBefore.write(out);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
CustomMessage customMessage = CustomMessage.read(in, out.size());
CryptoCustomMessage<GenericPayload> messageAfter = CryptoCustomMessage.read(customMessage,
new CryptoCustomMessage.Reader<GenericPayload>() {
@Override
public GenericPayload read(BitmessageAddress ignore, InputStream in) throws IOException {
return GenericPayload.read(0, 1, in, 100);
}
});
GenericPayload payloadAfter = messageAfter.decrypt(sendingIdentity.getPublicDecryptionKey());
assertEquals(payloadBefore, payloadAfter);
}
@Test
public void testWithActualRequest() throws Exception {
PrivateKey privateKey = PrivateKey.read(TestUtils.getResource("BM-2cSqjfJ8xK6UUn5Rw3RpdGQ9RsDkBhWnS8.privkey"));
final BitmessageAddress sendingIdentity = new BitmessageAddress(privateKey);
ProofOfWorkRequest requestBefore = new ProofOfWorkRequest(sendingIdentity, cryptography().randomBytes(64),
ProofOfWorkRequest.Request.CALCULATE);
CryptoCustomMessage<ProofOfWorkRequest> messageBefore = new CryptoCustomMessage<>(requestBefore);
messageBefore.signAndEncrypt(sendingIdentity, cryptography().createPublicKey(sendingIdentity.getPublicDecryptionKey()));
ByteArrayOutputStream out = new ByteArrayOutputStream();
messageBefore.write(out);
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
CustomMessage customMessage = CustomMessage.read(in, out.size());
CryptoCustomMessage<ProofOfWorkRequest> messageAfter = CryptoCustomMessage.read(customMessage,
new ProofOfWorkRequest.Reader(sendingIdentity));
ProofOfWorkRequest requestAfter = messageAfter.decrypt(sendingIdentity.getPublicDecryptionKey());
assertEquals(requestBefore, requestAfter);
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright 2017 Christian Basler
*
* 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 ch.dissem.bitmessage.extensions
import ch.dissem.bitmessage.entity.BitmessageAddress
import ch.dissem.bitmessage.entity.CustomMessage
import ch.dissem.bitmessage.entity.payload.GenericPayload
import ch.dissem.bitmessage.entity.valueobject.PrivateKey
import ch.dissem.bitmessage.extensions.pow.ProofOfWorkRequest
import ch.dissem.bitmessage.utils.TestBase
import ch.dissem.bitmessage.utils.TestUtils
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import ch.dissem.bitmessage.utils.Singleton.cryptography
import org.junit.Assert.assertEquals
class CryptoCustomMessageTest : TestBase() {
@Test
fun `ensure encrypt then decrypt yields same object`() {
val privateKey = PrivateKey.read(TestUtils.getResource("BM-2cSqjfJ8xK6UUn5Rw3RpdGQ9RsDkBhWnS8.privkey"))
val sendingIdentity = BitmessageAddress(privateKey)
val payloadBefore = GenericPayload(0, 1, cryptography().randomBytes(100))
val messageBefore = CryptoCustomMessage(payloadBefore)
messageBefore.signAndEncrypt(sendingIdentity, cryptography().createPublicKey(sendingIdentity.publicDecryptionKey))
val out = ByteArrayOutputStream()
messageBefore.write(out)
val `in` = ByteArrayInputStream(out.toByteArray())
val customMessage = CustomMessage.read(`in`, out.size())
val messageAfter = CryptoCustomMessage.read(customMessage,
object : CryptoCustomMessage.Reader<GenericPayload> {
override fun read(sender: BitmessageAddress, `in`: InputStream): GenericPayload {
return GenericPayload.read(0, 1, `in`, 100)
}
})
val payloadAfter = messageAfter.decrypt(sendingIdentity.publicDecryptionKey)
assertEquals(payloadBefore, payloadAfter)
}
@Test
fun `test with actual request`() {
val privateKey = PrivateKey.read(TestUtils.getResource("BM-2cSqjfJ8xK6UUn5Rw3RpdGQ9RsDkBhWnS8.privkey"))
val sendingIdentity = BitmessageAddress(privateKey)
val requestBefore = ProofOfWorkRequest(sendingIdentity, cryptography().randomBytes(64),
ProofOfWorkRequest.Request.CALCULATE)
val messageBefore = CryptoCustomMessage(requestBefore)
messageBefore.signAndEncrypt(sendingIdentity, cryptography().createPublicKey(sendingIdentity.publicDecryptionKey))
val out = ByteArrayOutputStream()
messageBefore.write(out)
val `in` = ByteArrayInputStream(out.toByteArray())
val customMessage = CustomMessage.read(`in`, out.size())
val messageAfter = CryptoCustomMessage.read(customMessage,
ProofOfWorkRequest.Reader(sendingIdentity))
val requestAfter = messageAfter.decrypt(sendingIdentity.publicDecryptionKey)
assertEquals(requestBefore, requestAfter)
}
}