Skip to content

Commit

Permalink
Merge pull request #1180 from alvasw/tor_id_keygen
Browse files Browse the repository at this point in the history
Implement TorOnionKey Generation
  • Loading branch information
alvasw authored Sep 15, 2023
2 parents e4e870e + af42315 commit 69f4b18
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
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;
}
}

0 comments on commit 69f4b18

Please sign in to comment.