private static Key loadKeyEncryptionKey() throws Exception {
   Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
   PEMReader pr = new PEMReader(new FileReader(EncryptTool.PRIVATE_KEY));
   KeyPair k = (KeyPair) pr.readObject();
   pr.close();
   return k.getPrivate();
 }
Exemple #2
0
  public static X509CertificateObject getCertificate() {
    if (cert == null) {
      try {

        File f = new File(XMPConfig.getCertfile());
        FileReader fr;
        fr = new FileReader(f);

        PEMReader r = new PEMReader(fr);
        Object o = r.readObject();
        if (o instanceof X509CertificateObject) {
          cert = (X509CertificateObject) o;
        }
        cert.checkValidity();
        r.close();
      } catch (FileNotFoundException e) {
        logger.error("FATAL: couldn't load certificate file", e);
        System.exit(1);
      } catch (NullPointerException e) {
        logger.error("FATAL: couldn't load certificate file", e);
        System.exit(1);
      } catch (IOException e) {
        logger.error("FATAL: couldn't load certificate file", e);
        System.exit(1);
      } catch (CertificateExpiredException e) {
        logger.error("FATAL: couldn't load certificate file", e);
        System.exit(1);
      } catch (CertificateNotYetValidException e) {
        logger.error("FATAL: couldn't load certificate file", e);
        System.exit(1);
      }
    }
    return cert;
  }
Exemple #3
0
 public static List<X509CertificateObject> getTrustedCerts() {
   if (intermediates == null) {
     intermediates = new ArrayList<X509CertificateObject>();
     File dir = new File(XMPConfig.getTrustedCertsDir());
     File[] listFiles = dir.listFiles();
     for (File file : listFiles) {
       try {
         FileReader fr;
         fr = new FileReader(file);
         PEMReader p = new PEMReader(fr);
         Object o = p.readObject();
         X509CertificateObject cert = null;
         if (o instanceof X509CertificateObject) {
           cert = (X509CertificateObject) o;
           intermediates.add(cert);
         }
         p.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       } catch (NullPointerException e) {
         e.printStackTrace();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return intermediates;
 }
 /** {@inheritDoc} */
 public void addIdentity(String privateKey, final String passphrase, String comment)
     throws IOException {
   if (!SecurityUtils.isBouncyCastleRegistered()) {
     throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
   }
   try {
     PEMReader r =
         new PEMReader(
             new StringReader(privateKey),
             passphrase == null
                 ? null
                 : new PasswordFinder() {
                   public char[] getPassword() {
                     return passphrase.toCharArray();
                   }
                 });
     try {
       Object o = r.readObject();
       if (o instanceof KeyPair) {
         agent.getAgent().addIdentity((KeyPair) o, comment);
       }
     } finally {
       r.close();
     }
   } catch (Exception e) {
     listener.getLogger().println(Messages.SSHAgentBuildWrapper_UnableToReadKey(e.getMessage()));
     e.printStackTrace(listener.getLogger());
   }
 }
  /** @param args */
  public static void main(String[] args) throws Exception {
    if (args.length < 3) {
      System.err.println(
          "Usage: OSSLoadAgent OSS_URL SECRET_NAME WRAPPED_PASSPHRASE AGENT_AUTH_SOCK [KEY_FILE]");
      System.exit(1);
    }

    SSHAgentClient sshAgent = new SSHAgentClient(args[2]);

    // Get the secret from OSS
    // FIXME ? Provide a way to specify the ssh signing key fingerprint
    byte[] secret = OSSClient.getSecret(args[0], args[1], null);
    // Use the secret to unwrap the passphrase
    byte[] unwrap = CryptoHelper.unwrapBlob(secret, Hex.decode(args[3]));
    String password = new String(unwrap, "UTF-8");

    // Read private keys
    // openssh store it in PEM format
    List<File> sshKeyFiles;
    if (args.length > 4) {
      sshKeyFiles = new ArrayList<File>(1);
      sshKeyFiles.add(new File(args[4]));
    } else {
      sshKeyFiles = getDefaultsKeyFiles();
    }

    for (File sshKeyFile : sshKeyFiles) {
      Reader fRd = new BufferedReader(new FileReader(sshKeyFile));
      PEMReader pem = new PEMReader(fRd, new DefaultPasswordFinder(password.toCharArray()), "BC");

      Object o;
      try {
        while ((o = pem.readObject()) != null) {
          if (o instanceof KeyPair) {
            KeyPair kp = (KeyPair) o;
            // Add the identity in the ssh-agent
            byte[] keyblob = CryptoHelper.sshPrivateKeyBlobFromKeyPair(kp);
            System.out.println("Loading " + sshKeyFile.getPath());
            sshAgent.addIdentity(keyblob, sshKeyFile.getPath());
          }
        }
      } catch (EncryptionException ee) {
        System.err.println("Can't read private key in " + sshKeyFile.getAbsolutePath());
        ee.printStackTrace();
      }

      pem.close();
    }

    System.out.println("Keys in agent:");
    List<SSHKey> identities = sshAgent.requestIdentities();
    for (SSHKey identity : identities) {
      System.out.println(identity);
    }
  }
 public Certificate parseCertificate(String cert) {
   PEMReader certPem = new PEMReader(new StringReader(cert));
   try {
     return (Certificate) certPem.readObject();
   } catch (Exception e) {
     throw new InvalidParameterValueException(
         "Invalid Certificate format. Expected X509 certificate");
   } finally {
     IOUtils.closeQuietly(certPem);
   }
 }
Exemple #7
0
 public static KeyPair getKeyPair(final byte[] o) {
   KeyPair keyPair = null;
   PEMReader in = null;
   ByteArrayInputStream pemByteIn = new ByteArrayInputStream(o);
   in = new PEMReader(new InputStreamReader(pemByteIn));
   try {
     keyPair = (KeyPair) in.readObject();
   } catch (IOException e) {
     LOG.error(e, e); // this can never happen
   }
   return keyPair;
 }
Exemple #8
0
 public static X509Certificate getCert(final byte[] o) {
   X509Certificate x509 = null;
   PEMReader in = null;
   ByteArrayInputStream pemByteIn = new ByteArrayInputStream(o);
   in = new PEMReader(new InputStreamReader(pemByteIn));
   try {
     x509 = (X509Certificate) in.readObject();
   } catch (IOException e) {
     LOG.error(e, e); // this can never happen
   }
   return x509;
 }
  private void loadRSAKeys() {

    // Server - Private Key
    PEMReader in;
    try {
      // System.out.println("SERVER KEYFILE " + serverKeyfile);

      in =
          new PEMReader(
              new FileReader(serverKeyfile),
              new PasswordFinder() {
                @Override
                public char[] getPassword() {
                  return RSApassword.toCharArray();
                }
              });

      KeyPair keyPair;
      keyPair = (KeyPair) in.readObject();
      serverKey = keyPair.getPrivate();

    } catch (FileNotFoundException e) {
      System.out.println("RSA-Keyfile not found.");
      e.printStackTrace();
    } catch (IOException e1) {
      System.out.println("RSA-Key could not be loaded.");
      e1.printStackTrace();
    }

    // User - Public Keys
    File folder = new File(clientKeyDir);
    File[] listOfFiles = folder.listFiles();
    String name;

    for (int i = 0; i < listOfFiles.length; i++) {
      if ((listOfFiles[i].isFile()) && (listOfFiles[i].getName().endsWith(".pub.pem"))) {
        try {
          in = new PEMReader(new FileReader(clientKeyDir + listOfFiles[i].getName()));
          name = listOfFiles[i].getName();

          userPubRSAKeys.put(name.substring(0, name.indexOf(".pub")), (PublicKey) in.readObject());

        } catch (FileNotFoundException e) {
          System.out.println("File " + listOfFiles[i].getPath() + " could not be found.");
          e.printStackTrace();
        } catch (IOException e1) {
          System.out.println("RSA-Key could not be loaded.");
          e1.printStackTrace();
        }
      }
    }
  }
  public SamlLoginServerKeyManager(String key, String password, String certificate) {
    Security.addProvider(new BouncyCastleProvider());

    if (null == password) {
      password = "";
    }

    try {
      PEMReader reader =
          new PEMReader(new InputStreamReader(new ByteArrayInputStream(certificate.getBytes())));
      X509Certificate cert = (X509Certificate) reader.readObject();

      reader =
          new PEMReader(
              new InputStreamReader(new ByteArrayInputStream(key.getBytes())),
              new StringPasswordFinder(password));
      KeyPair pkey = (KeyPair) reader.readObject();

      KeyStore keystore = KeyStore.getInstance("JKS");
      keystore.load(null);
      keystore.setCertificateEntry("service-provider-cert", cert);
      keystore.setKeyEntry(
          "service-provider-cert",
          pkey.getPrivate(),
          password.toCharArray(),
          new Certificate[] {cert});

      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(keystore, password.toCharArray());

      keyManager =
          new JKSKeyManager(
              keystore,
              Collections.singletonMap("service-provider-cert", password),
              "service-provider-cert");

      if (null == keyManager) {
        throw new IllegalArgumentException(
            "Could not load service provider certificate. Check serviceProviderKey and certificate parameters");
      }

      logger.info("Loaded service provider certificate " + keyManager.getDefaultCredentialName());
    } catch (Throwable t) {
      logger.error("Could not load certificate", t);
      throw new IllegalArgumentException(
          "Could not load service provider certificate. Check serviceProviderKey and certificate parameters",
          t);
    }
  }
  public List<Certificate> parseChain(String chain) throws IOException {

    List<Certificate> certs = new ArrayList<Certificate>();
    PEMReader reader = new PEMReader(new StringReader(chain));

    Certificate crt = null;

    while ((crt = (Certificate) reader.readObject()) != null) {
      if (crt instanceof X509Certificate) {
        certs.add(crt);
      }
    }
    if (certs.size() == 0) throw new IllegalArgumentException("Unable to decode certificate chain");

    return certs;
  }
Exemple #12
0
 private static KeyPair getKey() {
   if (keyPair == null) {
     try {
       File f = new File(XMPConfig.getKeyfile());
       FileReader r = new FileReader(f);
       PEMReader pr = new PEMReader(r);
       Object o = pr.readObject();
       keyPair = (KeyPair) o;
       pr.close();
     } catch (FileNotFoundException e) {
       logger.error("FATAL: couldn't load private key", e);
       System.exit(1);
     } catch (NullPointerException e) {
       logger.error("FATAL: couldn't load private key", e);
       System.exit(1);
     } catch (IOException e) {
       logger.error("FATAL: couldn't load private key", e);
       System.exit(1);
     }
   }
   return keyPair;
 }
  private KeyStore initializeTrustStore(String name, String pemCertificate)
      throws CertificateException {
    try {
      PEMReader reader =
          new PEMReader(new InputStreamReader(new ByteArrayInputStream(pemCertificate.getBytes())));
      X509Certificate certificate = (X509Certificate) reader.readObject();

      if (certificate == null) {
        throw new CertificateException("No certificate found in parsing!");
      }

      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(null);
      keyStore.setCertificateEntry(name, certificate);

      return keyStore;
    } catch (IOException | KeyStoreException e) {
      throw new CertificateException(e);
    } catch (NoSuchAlgorithmException e) {
      throw new AssertionError(e);
    }
  }
  public PrivateKey parsePrivateKey(String key, String password) throws IOException {

    PasswordFinder pGet = null;

    if (password != null) pGet = new KeyPassword(password.toCharArray());

    PEMReader privateKey = new PEMReader(new StringReader(key), pGet);
    Object obj = null;
    try {
      obj = privateKey.readObject();
    } finally {
      IOUtils.closeQuietly(privateKey);
    }

    try {

      if (obj instanceof KeyPair) return ((KeyPair) obj).getPrivate();

      return (PrivateKey) obj;

    } catch (Exception e) {
      throw new IOException("Invalid Key format or invalid password.", e);
    }
  }
 @Override
 protected KeyPair[] loadKeys() {
   if (!SecurityUtils.isBouncyCastleRegistered()) {
     throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
   }
   List<KeyPair> keys = new ArrayList<KeyPair>();
   if (key != null) {
     try {
       PEMReader r =
           new PEMReader(new InputStreamReader(new ByteArrayInputStream(key.getContent())));
       try {
         Object o = r.readObject();
         if (o instanceof KeyPair) {
           keys.add((KeyPair) o);
         }
       } finally {
         r.close();
       }
     } catch (Exception e) {
       LOG.info("Unable to read key {}: {}", key, e);
     }
   }
   return keys.toArray(new KeyPair[keys.size()]);
 }
 @Override
 protected KeyPair doReadKeyPair(InputStream is) throws Exception {
   PEMReader r = new PEMReader(new InputStreamReader(is));
   return (KeyPair) r.readObject();
 }
  @Override
  public KeyConfiguration getKeyConfiguration() throws ConfigurationLoadingException {

    if (keyConfiguration == null) {
      // Load values out of configuration
      logger.trace("Loading Key Configuration");
      keyConfiguration = new KeyConfiguration();

      FileReader fileReader;
      try {

        // Load Key Agreement Private Key
        fileReader =
            new FileReader(
                propertiesConfiguration.getString(
                    PropertiesConfigurationEntries.SECURITY_KEYAGREEMENT_KEYPATH));
        PEMReader pemReader = new PEMReader(fileReader);
        KeyPair keyPair = (KeyPair) pemReader.readObject();
        keyConfiguration.setKeyAgreementPrivateKey(keyPair.getPrivate());
        pemReader.close();
        fileReader.close();

        // Load Blob Private Key
        fileReader =
            new FileReader(
                propertiesConfiguration.getString(
                    PropertiesConfigurationEntries.SECURITY_BLOB_KEYPATH_PRIVATE));
        pemReader = new PEMReader(fileReader);
        keyPair = (KeyPair) pemReader.readObject();
        keyConfiguration.setBlobPrivateKey(keyPair.getPrivate());
        pemReader.close();
        fileReader.close();

        // Load Blob Public Key
        fileReader =
            new FileReader(
                propertiesConfiguration.getString(
                    PropertiesConfigurationEntries.SECURITY_BLOB_KEYPATH_PUBLIC));
        pemReader = new PEMReader(fileReader);
        X509Certificate cert = (X509Certificate) pemReader.readObject();
        PublicKey publicKey = (PublicKey) cert.getPublicKey();
        keyConfiguration.setBlobPublicKey(publicKey);
        pemReader.close();
        fileReader.close();

      } catch (FileNotFoundException e) {
        logger.error("Error loading the Key Configuration: " + e.getMessage());
        keyConfiguration = null;
        throw new ConfigurationLoadingException(
            "Error loading the Key Configuration: " + e.getMessage());
      } catch (IOException e) {
        logger.error("Error loading the Key Configuration: " + e.getMessage());
        keyConfiguration = null;
        throw new ConfigurationLoadingException(
            "Error loading the Key Configuration: " + e.getMessage());
      } catch (Exception e) {
        logger.error("Error loading the Key Configuration: " + e.getMessage());
        throw new RuntimeException(e.getMessage());
      }
    } else {
      logger.trace("Key Configuration already loaded");
    }

    return keyConfiguration;
  }