2016-04-03 100 views
0

以下是獲取公鑰的代碼。我需要將公鑰轉換爲OpenSSH格式,將其添加到Linux中的authorized_keys文件中。我怎樣才能做到這一點?如何將PublicKey轉換爲OpenSSH authorized_keys格式

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

我確實使用了PEMWriter。但它沒有給出正確格式的輸出字符串。

回答

1

@gotoalberto's answer一個不同的問題:

如果想逆轉這一過程,即PublicKey Java對象 編碼到Linux authorized_keys輸入格式,可以使用此代碼:

/** 
* 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密鑰。如果你需要其他鍵,你必須自己添加它們。

相關問題