是否有Java标准库直接从ssh-keygen生成的密钥文件构造私钥和公钥对象?

时间:2013-03-13 01:24:42

标签: java

我想使用id_rsa和id_rsa.pub为Java中的应用程序创建质询 - 响应登录系统。为此,我希望能够从id_rsa和id_rsa.pub构建PublicKeyPrivateKey

直接方法是以通常解析文本文件的方式解析这些,然后手动构建适当的java.security数据结构,以便在客户端和服务器中进行签名和验证。

是否有直接摄取这些文件的标准库快捷方式?

2 个答案:

答案 0 :(得分:0)

我所知道的最接近和最简单的方法是使用The Legion of the Bouncy Castle Java API与此类似的东西 -

// Just for the public / private key files...
private static String readFileAsString(
    String filePath) throws java.io.IOException {

  StringBuilder sb = new StringBuilder(100);
  BufferedReader reader = null;
  try {
    reader = new BufferedReader(new FileReader(
        filePath));
    int fileIn;
    while ((fileIn = reader.read()) != -1) {
      sb.append((char) fileIn);
    }
  } finally {
    reader.close();
  }
  return sb.toString();
}

// Add the SecurityProvider and a Base64 Decoder (Once)
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
BASE64Decoder b64 = new BASE64Decoder();

// For the publicKey
String publicKeyString = readFileAsString(publicKeyFileName);
AsymmetricKeyParameter publicKey =
  (AsymmetricKeyParameter) PublicKeyFactory.createKey(b64.decodeBuffer(publicKeyString));

// For the privateKey
String privateKeyString = readFileAsString(privateKeyFilename);
AsymmetricKeyParameter privateKey =
  (AsymmetricKeyParameter) PrivateKeyFactory.createKey(b64.decodeBuffer(privateKeyString));

答案 1 :(得分:0)

是的,我刚写了:openssh-java。 : - )