gpt4 book ai didi

java - 如何将 PublicKey 转换为 OpenSSHauthorized_keys 格式

转载 作者:行者123 更新时间:2023-11-30 02:59:13 24 4
gpt4 key购买 nike

这是获取公钥的代码。我需要将公钥转换为 OpenSSH 格式,以将其添加到 Linux 中的 authorized_keys 文件中。我怎样才能做到这一点?

KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC");
kpGen.initialize(1024, new SecureRandom());
KeyPair keypair = kpGen.generateKeyPair();

我确实使用了PEMWriter。但它没有给出正确格式的输出字符串。

最佳答案

@gotoalberto's answer对于不同的问题:

If you want reverse the process, i.e. encode a PublicKey Java object to a Linux authorized_keys entry format, one can use this code:

/**
* Encode PublicKey (DSA or RSA encoded) to authorized_keys like string
*
* @param publicKey DSA or RSA encoded
* @param user username for output authorized_keys like string
* @return authorized_keys like string
* @throws IOException
*/
public static String encodePublicKey(PublicKey publicKey, String user)
throws IOException {
String publicKeyEncoded;
if(publicKey.getAlgorithm().equals("RSA")){
RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(byteOs);
dos.writeInt("ssh-rsa".getBytes().length);
dos.write("ssh-rsa".getBytes());
dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
dos.write(rsaPublicKey.getPublicExponent().toByteArray());
dos.writeInt(rsaPublicKey.getModulus().toByteArray().length);
dos.write(rsaPublicKey.getModulus().toByteArray());
publicKeyEncoded = new String(
Base64.encodeBase64(byteOs.toByteArray()));
return "ssh-rsa " + publicKeyEncoded + " " + user;
}
else if(publicKey.getAlgorithm().equals("DSA")){
DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
DSAParams dsaParams = dsaPublicKey.getParams();

ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(byteOs);
dos.writeInt("ssh-dss".getBytes().length);
dos.write("ssh-dss".getBytes());
dos.writeInt(dsaParams.getP().toByteArray().length);
dos.write(dsaParams.getP().toByteArray());
dos.writeInt(dsaParams.getQ().toByteArray().length);
dos.write(dsaParams.getQ().toByteArray());
dos.writeInt(dsaParams.getG().toByteArray().length);
dos.write(dsaParams.getG().toByteArray());
dos.writeInt(dsaPublicKey.getY().toByteArray().length);
dos.write(dsaPublicKey.getY().toByteArray());
publicKeyEncoded = new String(
Base64.encodeBase64(byteOs.toByteArray()));
return "ssh-dss " + publicKeyEncoded + " " + user;
}
else{
throw new IllegalArgumentException(
"Unknown public key encoding: " + publicKey.getAlgorithm());
}
}
<小时/>

@gotoalberto 的代码仅针对 RSA 和 DSA key 实现。如果您需要其他 key ,则必须自行添加。

关于java - 如何将 PublicKey 转换为 OpenSSHauthorized_keys 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36382913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com