Esempio n. 1
0
  @Override
  public KeyPairProvider get() {
    Path objKey = site.ssh_key;
    Path rsaKey = site.ssh_rsa;
    Path dsaKey = site.ssh_dsa;

    final List<String> stdKeys = new ArrayList<>(2);
    if (Files.exists(rsaKey)) {
      stdKeys.add(rsaKey.toAbsolutePath().toString());
    }
    if (Files.exists(dsaKey)) {
      stdKeys.add(dsaKey.toAbsolutePath().toString());
    }

    if (Files.exists(objKey)) {
      if (stdKeys.isEmpty()) {
        SimpleGeneratorHostKeyProvider p = new SimpleGeneratorHostKeyProvider();
        p.setPath(objKey.toAbsolutePath().toString());
        return p;

      } else {
        // Both formats of host key exist, we don't know which format
        // should be authoritative. Complain and abort.
        //
        stdKeys.add(objKey.toAbsolutePath().toString());
        throw new ProvisionException("Multiple host keys exist: " + stdKeys);
      }

    } else {
      if (stdKeys.isEmpty()) {
        throw new ProvisionException("No SSH keys under " + site.etc_dir);
      }
      if (!SecurityUtils.isBouncyCastleRegistered()) {
        throw new ProvisionException(
            "Bouncy Castle Crypto not installed;"
                + " needed to read server host keys: "
                + stdKeys
                + "");
      }
      return new FileKeyPairProvider(stdKeys.toArray(new String[stdKeys.size()]));
    }
  }
Esempio n. 2
0
  public static void main(String[] args)
      throws GeneralSecurityException, JSchException, IOException {
    SimpleGeneratorHostKeyProvider p;

    if (args.length != 1) {
      System.err.println("Error: requires path to the SSH host key");
      return;
    } else {
      File file = new File(args[0]);
      if (!file.exists() || !file.isFile() || !file.canRead()) {
        System.err.println("Error: ssh key should exist and be readable");
        return;
      }
    }

    p = new SimpleGeneratorHostKeyProvider();
    // Gerrit's SSH "simple" keys are always RSA.
    p.setPath(args[0]);
    p.setAlgorithm("RSA");
    Iterable<KeyPair> keys = p.loadKeys(); // forces the key to generate.
    for (KeyPair k : keys) {
      System.out.println("Public Key (" + k.getPublic().getAlgorithm() + "):");
      // From Gerrit's SshDaemon class; use JSch to get the public
      // key/type
      final Buffer buf = new Buffer();
      buf.putRawPublicKey(k.getPublic());
      final byte[] keyBin = buf.getCompactData();
      HostKey pub = new HostKey("localhost", keyBin);
      System.out.println(pub.getType() + " " + pub.getKey());
      System.out.println("Private Key:");
      // Use Bouncy Castle to write the private key back in PEM format
      // (PKCS#1)
      // http://stackoverflow.com/questions/25129822/export-rsa-public-key-to-pem-string-using-java
      StringWriter privout = new StringWriter();
      JcaPEMWriter privWriter = new JcaPEMWriter(privout);
      privWriter.writeObject(k.getPrivate());
      privWriter.close();
      System.out.println(privout);
    }
  }