title: How to generate a tor service onion address from the public key in java?
body: <p>I am trying to generate the onion address that is generated from a public key.</p>
  
  <p>If the following line is added to the code in a <a href="https://stackoverflow.com/questions/49671309/how-generate-a-valid-private-rsa-1024-key-for-a-tor-onion-service-using-java">previous post</a>, just after <em>privateKeyEncoded</em></p>
  
  <pre><code>String publicKeyEncoded = encoder.encodeToString(publicKey.getEncoded());
  </code></pre>
  
  <p>When I put the <em>privateKeyEncoded</em> into the <em>/var/lib/tor/hidden_service/private_key</em>, save the <em>publicKeyEncoded</em> and start the tor service, a new onion address is created. I am trying to get the same onion address as the tor service and from one created from the <em>publicKeyEncoded</em>. Using this code</p>
  
  <pre><code>import org.apache.commons.codec.binary.Base32;
  import org.apache.commons.codec.binary.Base64;
  
  //base64 string from the public key created
  String publicKeyTest = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMnFkJTMZ2ZxnqLwCiB/EWHjsHbnC+sKEIrGbyOTYiTl3LygsekAX6LhgcllscLUFqSKlMRB3jRB0GAPrIc73E/hTnmWBtF8NT8DhZzl06LZ1BtNjfON1pHm87STMAayiSaXPmSOwIqOA89aJPcA9m4v4IhtjYSFXmCAsE4RqoAwIDAQAB";
  //the onion address the tor service gives when the private key is used
  String onionAddressTest = "qqkhrc4men3fiqyl";
  
  byte[] publicKeyDecoded = Base64.decodeBase64(publicKeyTest);
  MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
  byte[] sha1hash = messageDigest.digest(publicKeyDecoded);
  int numberOfCharacters = 10;
  byte[] reducedHash = new byte[numberOfCharacters];
  for(int i = 0; i &lt; numberOfCharacters; i++) {
      reducedHash[i] = sha1hash[i];
  }
  Base32 base32encoder = new Base32();
  String onionAddress = base32encoder.encodeAsString(reducedHash).toLowerCase();
  System.out.println(onionAddress);  // but this gives "7j3iz4of464hje2e"
  </code></pre>
  
  <p>I've tried using <a href="https://rtyley.github.io/spongycastle/" rel="nofollow noreferrer">spongycastle</a> to  replicate my conversion but get the same answer. Which makes me think there's something wrong with how I generate the public key or there's something wrong in my initial conversion from base64.</p>
  
  <p>Given the public key (<em>publicKeyTest</em>) how can you get the onion address (<em>onionAddressTest</em>) using java?</p>