Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement TorOnionKey Generation #1180

Merged
merged 1 commit into from
Sep 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions network/tor/tor/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ dependencies {
implementation 'network:common'
implementation 'network:socks5-socket-channel'

implementation libs.bouncycastle

implementation libs.google.guava
implementation libs.failsafe
implementation libs.tukaani
Expand Down
39 changes: 39 additions & 0 deletions network/tor/tor/src/main/java/bisq/tor/TorIdentity.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,15 @@

import lombok.Getter;
import lombok.ToString;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.math.ec.rfc8032.Ed25519;

import java.security.SecureRandom;

@Getter
@ToString
public class TorIdentity {

@ToString.Exclude
private final String privateKey;
private final int port;
Expand All @@ -31,4 +36,38 @@ public TorIdentity(String privateKey, int port) {
this.privateKey = privateKey;
this.port = port;
}

public static TorIdentity generate(int port) {
// Key Format definition:
// https://gitlab.torproject.org/tpo/core/torspec/-/blob/main/control-spec.txt

byte[] privateKey = new byte[32];
Ed25519.generatePrivateKey(new SecureRandom(), privateKey);

byte[] secretScalar = generateSecretScalar(privateKey);
String base64EncodedSecretScalar = java.util.Base64.getEncoder()
.encodeToString(secretScalar);

String torOnionKey = "-----BEGIN OPENSSH PRIVATE KEY-----\n" +
base64EncodedSecretScalar + "\n" +
"-----END OPENSSH PRIVATE KEY-----\n";

return new TorIdentity(torOnionKey, port);
}

private static byte[] generateSecretScalar(byte[] privateKey) {
// https://www.rfc-editor.org/rfc/rfc8032#section-5.1

SHA512Digest sha512Digest = new SHA512Digest();
sha512Digest.update(privateKey, 0, privateKey.length);

byte[] secretScalar = new byte[64];
sha512Digest.doFinal(secretScalar, 0);

secretScalar[0] &= (byte) 248;
secretScalar[31] &= 127;
secretScalar[31] |= 64;

return secretScalar;
}
}