How generate a valid private (RSA 1024) key for a tor onion service using java?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 13:46:01

问题


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?


回答1:


Solution: Change BEGIN RSA PRIVATE KEY with BEGIN PRIVATE KEY

Java encodes the key IN PKCS#8 format

PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyGenerated.getEncoded()));

But you are generating a PEM file with the header -----BEGIN RSA PRIVATE KEY----- which is reserved to PKCS#1 keys (old format but very common), and .onion is assuming that it is pkcs1 when it really is pkcs8. See the error

TLS error: RSA lib (in rsa routines:OLD_RSA_PRIV_DECODE:---)

So you need to use the PCKS#8 header -----BEGIN PRIVATE KEY-----

See also this post Load a RSA private key in Java (algid parse error, not a sequence)



来源:https://stackoverflow.com/questions/49671309/how-generate-a-valid-private-rsa-1024-key-for-a-tor-onion-service-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!