I'm trying to generate a valid private key for a tor onion service in java. With this private key I want to get a valid .onion address.
I have run various combinations (with this bit/without that bit) of the code below
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PrivateKey privateKeyGenerated = keyPair.getPrivate();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyGenerated.getEncoded()));
Base64.Encoder encoder = Base64.getEncoder();
String privateKeyEncoded = encoder.encodeToString(privateKey.getEncoded());
String fileName = "{{where I'm wanting to store the file}}";
Writer writer = new FileWriter(fileName);
writer.write("-----BEGIN RSA PRIVATE KEY-----\n");
writer.write(privateKeyEncoded);
writer.write("\n-----END RSA PRIVATE KEY-----\n");
writer.close();
After generation I copy the key to my /var/lib/tor/hidden_service/private_key, remove any associated hostname and start the tor service. In the logs I get the error:
TLS error: wrong tag (in asn1 encoding routines:ASN1_CHECK_TLEN:---)
TLS error: nested asn1 error (in asn1 encoding routines:ANS1_D2I_EX_PRIMITIVE:---)
TLS error: nested asn1 error (in asn1 endoding routines:ASN1_TEMPLATE_NOEXP_D2I:---)
TLS error: RSA lib (in rsa routines:OLD_RSA_PRIV_DECODE:---)
If a resulting .onion address is generated it doesn't work.
How do I generate a valid private key?