コード例 #1
0
ファイル: KeyStoreFile.java プロジェクト: jlcsmith/ddf
 /**
  * Add a new entry to the keystore. Use the given alias.
  *
  * @param alias of keystore entry
  * @param entry instance
  */
 public void setEntry(String alias, KeyStore.Entry entry) {
   try {
     keyStore.setEntry(alias, entry, getPasswordObject());
   } catch (KeyStoreException e) {
     throw new RuntimeException(String.format("Could not add %s to keystore", alias), e);
   }
 }
コード例 #2
0
 @BeforeClass
 public static void setUp() throws Exception {
   KEY = MessageDigest.getInstance("SHA-256").digest(ALIAS.getBytes());
   // Create a JKECS store containing a test secret key
   KeyStore store = KeyStore.getInstance("JCEKS");
   store.load(null, PASSWORD.toCharArray());
   store.setEntry(
       ALIAS,
       new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")),
       new KeyStore.PasswordProtection(PASSWORD.toCharArray()));
   // Create the test directory
   String dataDir = TEST_UTIL.getDataTestDir().toString();
   new File(dataDir).mkdirs();
   // Write the keystore file
   storeFile = new File(dataDir, "keystore.jks");
   FileOutputStream os = new FileOutputStream(storeFile);
   try {
     store.store(os, PASSWORD.toCharArray());
   } finally {
     os.close();
   }
   // Write the password file
   Properties p = new Properties();
   p.setProperty(ALIAS, PASSWORD);
   passwordFile = new File(dataDir, "keystore.pw");
   os = new FileOutputStream(passwordFile);
   try {
     p.store(os, "");
   } finally {
     os.close();
   }
 }
コード例 #3
0
  private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null)
        || (builder.clientCertPath == null)
        || (builder.clientKeyPath == null)) {
      throw new DockerCertificateException(
          "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }

    try {
      final CertificateFactory cf = CertificateFactory.getInstance("X.509");
      final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
      final Certificate clientCert =
          cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

      final PEMKeyPair clientKeyPair =
          (PEMKeyPair)
              new PEMParser(
                      Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset()))
                  .readObject();

      final PKCS8EncodedKeySpec spec =
          new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
      final KeyFactory kf = KeyFactory.getInstance("RSA");
      final PrivateKey clientKey = kf.generatePrivate(spec);

      final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

      final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(null, null);
      keyStore.setCertificateEntry("client", clientCert);
      keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] {clientCert});

      this.sslContext =
          SSLContexts.custom()
              .loadTrustMaterial(trustStore)
              .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD)
              .useTLS()
              .build();
    } catch (CertificateException
        | IOException
        | NoSuchAlgorithmException
        | InvalidKeySpecException
        | KeyStoreException
        | UnrecoverableKeyException
        | KeyManagementException e) {
      throw new DockerCertificateException(e);
    }
  }
コード例 #4
0
ファイル: TLSClient.java プロジェクト: r3ek0/mirakel-android
  // //////////////////////////////////////////////////////////////////////////////
  public void init(final String root, final String user_ca, final String user_key)
      throws ParseException, CertificateException {
    Log.i(TAG, "init");
    try {
      final X509Certificate ROOT = generateCertificateFromPEM(root);
      final X509Certificate USER_CERT = generateCertificateFromPEM(user_ca);
      final RSAPrivateKey USER_KEY = generatePrivateKeyFromPEM(user_key);
      final KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
      trusted.load(null);
      trusted.setCertificateEntry("taskwarrior-ROOT", ROOT);
      trusted.setCertificateEntry("taskwarrior-USER", USER_CERT);
      final Certificate[] chain = {USER_CERT, ROOT};
      final KeyManagerFactory keyManagerFactory =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      // Hack to get it working on android 2.2
      final String pwd = "secret";
      trusted.setEntry(
          "user",
          new KeyStore.PrivateKeyEntry(USER_KEY, chain),
          new KeyStore.PasswordProtection(pwd.toCharArray()));

      keyManagerFactory.init(trusted, pwd.toCharArray());

      final SSLContext context = SSLContext.getInstance("TLS");
      final TrustManagerFactory tmf =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init(trusted);
      final TrustManager[] trustManagers = tmf.getTrustManagers();
      context.init(keyManagerFactory.getKeyManagers(), trustManagers, new SecureRandom());
      this.sslFact = context.getSocketFactory();
    } catch (final UnrecoverableKeyException e) {
      Log.w(TAG, "cannot restore key");
      throw new CertificateException(e);
    } catch (final KeyManagementException e) {
      Log.w(TAG, "cannot access key");
      throw new CertificateException(e);
    } catch (final KeyStoreException e) {
      Log.w(TAG, "cannot handle keystore");
      throw new CertificateException(e);
    } catch (final NoSuchAlgorithmException e) {
      Log.w(TAG, "no matching algorithm founr");
      throw new CertificateException(e);
    } catch (final CertificateException e) {
      Log.w(TAG, "certificat not readable");
      throw new CertificateException(e);
    } catch (final IOException e) {
      Log.w(TAG, "general io problem");
      throw new CertificateException(e);
    }
  }
コード例 #5
0
  /** java.security.KeyStore#deleteEntry(String) */
  public void test_deleteEntry() throws Exception {
    try {
      KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
      keyTest.load(null, null);
      keyTest.deleteEntry(null);
      fail();
    } catch (NullPointerException expected) {
    }

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, "password".toCharArray());

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    Certificate[] chain = {
      new MyCertificate("DSA", testEncoding), new MyCertificate("DSA", testEncoding)
    };
    KeyStore.PrivateKeyEntry pkEntry = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);

    keyTest.setEntry("symKey", pkEntry, pp);

    keyTest.deleteEntry("symKey");
  }
コード例 #6
0
  @SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE")
  public static void writeSharedSecret(
      String keyStorePath, String keyStorePassword, byte[] sharedSecret) throws Exception {
    char[] password = keyStorePassword.toCharArray();
    KeyStore ks;
    try {
      ks = readKeyStore(keyStorePath, password);
    } catch (FileNotFoundException e) {
      ks = KeyStore.getInstance("JCEKS");
      ks.load(null, password);
    }

    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(password);
    SecretKeySpec signingKey = new SecretKeySpec(sharedSecret, "HmacSHA1");
    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(signingKey);
    ks.setEntry(CHALLENGE_RESPONSE_SECRET, skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    File keyStoreFile = new File(keyStorePath);
    File parent = keyStoreFile.getParentFile();
    if (parent != null) parent.mkdirs();

    try {
      fos = new java.io.FileOutputStream(keyStoreFile);
      ks.store(fos, password);
      keyStoreFile.setReadable(false, false);
      keyStoreFile.setReadable(true, true);
      keyStoreFile.setWritable(false, false);
      keyStoreFile.setWritable(true, true);
      keyStoreFile.setExecutable(false, false);
    } finally {
      if (fos != null) {
        fos.close();
      }
    }
  }
コード例 #7
0
  /** java.security.KeyStore#setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter) */
  public void test_setEntry() throws Exception {
    String type = "DSA";

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, pssWord);

    Certificate[] chain = {
      new MyCertificate(type, testEncoding), new MyCertificate(type, testEncoding)
    };
    DSAPrivateKey privateKey1 =
        (DSAPrivateKey)
            KeyFactory.getInstance(type)
                .generatePrivate(
                    new DSAPrivateKeySpec(
                        new BigInteger("1"),
                        new BigInteger("2"),
                        new BigInteger("3"),
                        new BigInteger("4")));

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);
    KeyStore.PrivateKeyEntry pke1 = new KeyStore.PrivateKeyEntry(privateKey1, chain);

    try {
      keyTest.setEntry("alias", pke, null);
      assertFalse(StandardNames.IS_RI); // BKS KeyStore does not require a password
    } catch (KeyStoreException e) {
      assertTrue(StandardNames.IS_RI); // JKS KeyStore requires a password
    }

    keyTest.setEntry("alias", pke, pp);

    KeyStore.PrivateKeyEntry pkeActual = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias", pp);

    assertTrue(Arrays.equals(chain, pkeActual.getCertificateChain()));
    assertEquals(getPrivateKey(), pkeActual.getPrivateKey());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias", KeyStore.PrivateKeyEntry.class));

    keyTest.setEntry("alias", pke1, pp);
    pkeActual = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias", pp);

    assertTrue(Arrays.equals(chain, pkeActual.getCertificateChain()));
    DSAPrivateKey actualPrivateKey = (DSAPrivateKey) pkeActual.getPrivateKey();
    assertEquals(privateKey1.getX(), actualPrivateKey.getX());
    assertEquals(privateKey1.getParams().getG(), actualPrivateKey.getParams().getG());
    assertEquals(privateKey1.getParams().getP(), actualPrivateKey.getParams().getP());
    assertEquals(privateKey1.getParams().getQ(), actualPrivateKey.getParams().getQ());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias", KeyStore.PrivateKeyEntry.class));

    keyTest.setEntry("alias2", pke1, pp);
    pkeActual = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias2", pp);

    assertTrue(Arrays.equals(chain, pkeActual.getCertificateChain()));
    actualPrivateKey = (DSAPrivateKey) pkeActual.getPrivateKey();
    assertEquals(privateKey1.getX(), actualPrivateKey.getX());
    assertEquals(privateKey1.getParams().getG(), actualPrivateKey.getParams().getG());
    assertEquals(privateKey1.getParams().getP(), actualPrivateKey.getParams().getP());
    assertEquals(privateKey1.getParams().getQ(), actualPrivateKey.getParams().getQ());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias2", KeyStore.PrivateKeyEntry.class));

    try {
      keyTest.setEntry(null, null, null);
      fail();
    } catch (NullPointerException expected) {
    }
  }
コード例 #8
0
  /** java.security.KeyStore#getEntry(String, KeyStore.ProtectionParameter) */
  public void test_getEntry() throws Exception {
    String type = "DSA";

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.getEntry("anAlias", new KeyStore.PasswordProtection(new char[] {}));
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, pssWord);

    try {
      keyTest.getEntry(null, new KeyStore.PasswordProtection(new char[] {}));
      fail();
    } catch (NullPointerException expected) {
    }

    keyTest.getEntry("anAlias", null);

    try {
      keyTest.getEntry(null, null);
      fail();
    } catch (NullPointerException expected) {
    }

    assertNull(keyTest.getEntry("alias", null));

    Certificate[] chain = {
      new MyCertificate(type, testEncoding), new MyCertificate(type, testEncoding)
    };

    DSAPrivateKey privateKey1 =
        (DSAPrivateKey)
            KeyFactory.getInstance(type)
                .generatePrivate(
                    new DSAPrivateKeySpec(
                        new BigInteger("1"),
                        new BigInteger("2"),
                        new BigInteger("3"),
                        new BigInteger("4")));

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    assertNull(keyTest.getEntry("alias", pp));

    KeyStore.PrivateKeyEntry pke1 = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);
    KeyStore.PrivateKeyEntry pke2 = new KeyStore.PrivateKeyEntry(privateKey1, chain);

    keyTest.setEntry("alias1", pke1, pp);
    keyTest.setEntry("alias2", pke2, pp);

    assertNull(keyTest.getEntry("alias", pp));
    KeyStore.PrivateKeyEntry pkeActual1 = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias1", pp);
    KeyStore.PrivateKeyEntry pkeActual2 = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias2", pp);

    assertTrue(Arrays.equals(chain, pkeActual1.getCertificateChain()));
    assertEquals(getPrivateKey(), pkeActual1.getPrivateKey());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual1.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias1", KeyStore.PrivateKeyEntry.class));

    assertTrue(Arrays.equals(chain, pkeActual2.getCertificateChain()));
    DSAPrivateKey entryPrivateKey = (DSAPrivateKey) pkeActual2.getPrivateKey();
    assertEquals(privateKey1.getX(), entryPrivateKey.getX());
    assertEquals(privateKey1.getParams().getG(), entryPrivateKey.getParams().getG());
    assertEquals(privateKey1.getParams().getP(), entryPrivateKey.getParams().getP());
    assertEquals(privateKey1.getParams().getQ(), entryPrivateKey.getParams().getQ());

    assertEquals(new MyCertificate(type, testEncoding), pkeActual2.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias2", KeyStore.PrivateKeyEntry.class));
  }
コード例 #9
0
  /** java.security.KeyStore#getCreationDate(String) */
  public void test_getCreationDate() throws Exception {
    String type = "DSA";

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.getCreationDate("anAlias");
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, pssWord);

    assertNull(keyTest.getCreationDate(""));
    try {
      keyTest.getCreationDate(null);
      fail();
    } catch (NullPointerException expected) {
    }

    Certificate[] chain = {
      new MyCertificate(type, testEncoding), new MyCertificate(type, testEncoding)
    };
    PrivateKey privateKey1 =
        KeyFactory.getInstance(type)
            .generatePrivate(
                new DSAPrivateKeySpec(
                    new BigInteger("0"),
                    new BigInteger("0"),
                    new BigInteger("0"),
                    new BigInteger("0")));

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);
    KeyStore.PrivateKeyEntry pke1 = new KeyStore.PrivateKeyEntry(privateKey1, chain);

    keyTest.setEntry("alias1", pke, pp);
    keyTest.setEntry("alias2", pke1, pp);
    Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

    int dayExpected = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    int monthExpected = Calendar.getInstance().get(Calendar.MONTH);
    int yearExpected = Calendar.getInstance().get(Calendar.YEAR);
    int hourExpected = Calendar.getInstance().get(Calendar.HOUR);
    int minuteExpected = Calendar.getInstance().get(Calendar.MINUTE);

    Calendar.getInstance().setTimeInMillis(keyTest.getCreationDate("alias1").getTime());
    int dayActual1 = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    int monthActual1 = Calendar.getInstance().get(Calendar.MONTH);
    int yearActual1 = Calendar.getInstance().get(Calendar.YEAR);
    int hourActual1 = Calendar.getInstance().get(Calendar.HOUR);
    int minuteActual1 = Calendar.getInstance().get(Calendar.MINUTE);

    assertEquals(dayExpected, dayActual1);
    assertEquals(monthExpected, monthActual1);
    assertEquals(yearExpected, yearActual1);
    assertEquals(hourExpected, hourActual1);
    assertEquals(minuteExpected, minuteActual1);

    Calendar.getInstance().setTimeInMillis(keyTest.getCreationDate("alias2").getTime());
    int dayActual2 = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    int monthActual2 = Calendar.getInstance().get(Calendar.MONTH);
    int yearActual2 = Calendar.getInstance().get(Calendar.YEAR);
    int hourActual2 = Calendar.getInstance().get(Calendar.HOUR);
    int minuteActual2 = Calendar.getInstance().get(Calendar.MINUTE);

    assertEquals(dayExpected, dayActual2);
    assertEquals(monthExpected, monthActual2);
    assertEquals(yearExpected, yearActual2);
    assertEquals(hourExpected, hourActual2);
    assertEquals(minuteExpected, minuteActual2);

    try {
      keyTest.getCreationDate(null);
      fail();
    } catch (NullPointerException expected) {
    }
  }