如何使用java为tor洋葱服务生成有效的私有(RSA 1024)密钥? [英] How generate a valid private (RSA 1024) key for a tor onion service using java?
问题描述
我正在尝试为 java 中的 Tor onion 服务生成一个有效的私钥.使用这个私钥,我想获得一个有效的 .onion 地址.
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();
生成后,我将密钥复制到我的/var/lib/tor/hidden_service/private_key,删除任何关联的主机名并启动 Tor 服务.在日志中,我收到错误:
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:---)
如果生成了结果 .onion 地址,则它不起作用.
If a resulting .onion address is generated it doesn't work.
如何生成有效的私钥?
推荐答案
解决方案:将 BEGIN RSA PRIVATE KEY
更改为 BEGIN PRIVATE KEY
Solution: Change BEGIN RSA PRIVATE KEY
with BEGIN PRIVATE KEY
Java 以 PKCS#8 格式对密钥进行编码
Java encodes the key IN PKCS#8 format
PrivateKey privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyGenerated.getEncoded()));
但是您正在生成一个带有标题 -----BEGIN RSA PRIVATE KEY-----
的 PEM 文件,该文件保留给 PKCS#1 密钥(旧格式但很常见),并且 .onion 假设它是 pkcs1,而实际上它是 pkcs8.查看错误
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:---)
所以你需要使用PCKS#8头-----BEGIN PRIVATE KEY-----
So you need to use the PCKS#8 header -----BEGIN PRIVATE KEY-----
另见这篇文章 在 Java 中加载 RSA 私钥(algid 解析错误,不是序列)
这篇关于如何使用java为tor洋葱服务生成有效的私有(RSA 1024)密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!