Java 类java.security.KeyStore.PrivateKeyEntry 实例源码

项目:atlas    文件:PatchBuilder.java   
public PatchBuilder(File outFile, File dexFile, PrivateKeyEntry key,
                    PrintStream verboseStream) {
    try {
        if (null != key) {
            mBuilder = new SignedJarBuilder(
                    new FileOutputStream(outFile, false), key.getPrivateKey(),
                    (X509Certificate) key.getCertificate());
        } else {
            mBuilder = new SignedJarBuilder(
                    new FileOutputStream(outFile, false), null,
                    null);
        }
        mBuilder.writeFile(dexFile, "classes.dex");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:xtf    文件:XTFKeyStore.java   
public void addSelfSignedCertificate(String certificateAlias, String dn, String password) {
    try {
        KeyPair keys = generateKeyPair();

        Calendar start = Calendar.getInstance();
        Calendar expiry = Calendar.getInstance();
        expiry.add(Calendar.YEAR, 1);
        X500Name name = new X500Name(dn);
        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(name, BigInteger.ONE,
                start.getTime(), expiry.getTime(), name, SubjectPublicKeyInfo.getInstance(keys.getPublic().getEncoded()));
        ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(new BouncyCastleProvider()).build(keys.getPrivate());
        X509CertificateHolder holder = certificateBuilder.build(signer);
        Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);

        Entry entry = new PrivateKeyEntry(keys.getPrivate(), new Certificate[]{ cert });
        keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray()));
    } catch (GeneralSecurityException | OperatorCreationException ex) {
        throw new RuntimeException("Unable to generate self-signed certificate", ex);
    }
}
项目:xtf    文件:XTFKeyStore.java   
/**
 * Asymmetric cryptography - only the private key from generated pair is used.
 * Pre-condition: #certificateAlias refers to existing certificate
 *
 * @throws {@link NullPointerException} when #certificateAlias is @code{null}
 */
public void addPrivateKey(String keyAlias, String certificateAlias, String password) {
    keyAlias = String.format("%s (%s)", keyAlias, certificateAlias);

    try {
        Certificate[] certChain = keystore.getCertificateChain(certificateAlias);
        if (certChain == null) {
            LoggerFactory.getLogger(getClass()).warn("Could not find certificate");
            certChain = new Certificate[0];
        }
        Entry entry = new PrivateKeyEntry(generateKeyPair().getPrivate(), certChain);
        ProtectionParameter protParam = new KeyStore.PasswordProtection(password.toCharArray());
        keystore.setEntry(keyAlias, entry, protParam);
    } catch (KeyStoreException | NoSuchAlgorithmException ex) {
        throw new RuntimeException("Unable to add new private key", ex);
    }
}
项目:mi-firma-android    文件:CeresKeyStoreImpl.java   
/** {@inheritDoc} */
  @Override
  public KeyStore.Entry engineGetEntry(final String alias,
                                     final ProtectionParameter protParam) {
    if (protParam instanceof KeyStore.PasswordProtection) {
    final PasswordCallback pwc = new CachePasswordCallback(((KeyStore.PasswordProtection)protParam).getPassword());
    this.cryptoCard.setPasswordCallback(pwc);
    }
    if (!engineContainsAlias(alias)) {
        return null;
    }
    final PrivateKey key = (PrivateKey) engineGetKey(
    alias,
    null // Le pasamos null porque ya hemos establecido el PasswordCallback o el CallbackHander antes
);
    return new PrivateKeyEntry(key, engineGetCertificateChain(alias));
  }
项目:conscrypt    文件:OpenJdkEngineFactory.java   
private static SslContext newNettyServerContext(
        io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) {
    try {
        PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
        SslContextBuilder ctx =
                SslContextBuilder
                        .forServer(server.getPrivateKey(),
                                (X509Certificate[]) server.getCertificateChain())
                        .sslProvider(sslProvider);
        if (useAlpn) {
            ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG);
        }
        return ctx.build();
    } catch (SSLException e) {
        throw new RuntimeException(e);
    }
}
项目:commons-eid    文件:JCATest.java   
@Test
public void testGetEntry() throws Exception {
    Security.addProvider(new BeIDProvider());

    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
    assertNotNull(privateKeyEntry);
    assertTrue(privateKeyEntry.getPrivateKey() instanceof BeIDPrivateKey);

    TrustedCertificateEntry caEntry = (TrustedCertificateEntry) keyStore.getEntry("CA", null);
    assertNotNull(caEntry);
    LOGGER.debug("CA entry: {}", ((X509Certificate) caEntry.getTrustedCertificate()).getSubjectX500Principal());

    TrustedCertificateEntry rootEntry = (TrustedCertificateEntry) keyStore.getEntry("Root", null);
    assertNotNull(rootEntry);
    LOGGER.debug("root entry: {}", ((X509Certificate) rootEntry.getTrustedCertificate()).getSubjectX500Principal());
}
项目:commons-eid    文件:BeIDKeyStore.java   
@Override
public Entry engineGetEntry(String alias, ProtectionParameter protParam)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
    LOGGER.debug("engineGetEntry: {}", alias);
    if ("Authentication".equals(alias) || "Signature".equals(alias)) {
        PrivateKey privateKey = (PrivateKey) engineGetKey(alias, null);
        Certificate[] chain = engineGetCertificateChain(alias);
        PrivateKeyEntry privateKeyEntry = new PrivateKeyEntry(privateKey, chain);
        return privateKeyEntry;
    }
    if ("CA".equals(alias) || "Root".equals(alias) || "RRN".equals(alias)) {
        Certificate certificate = engineGetCertificate(alias);
        TrustedCertificateEntry trustedCertificateEntry = new TrustedCertificateEntry(certificate);
        return trustedCertificateEntry;
    }
    return super.engineGetEntry(alias, protParam);
}
项目:In-the-Box-Fork    文件:KeyManagerFactoryTest.java   
private void test_X509KeyManager_alias(X509KeyManager km, String alias, String keyType) {
    if (alias == null) {
        assertNull(km.getCertificateChain(alias));
        assertNull(km.getPrivateKey(alias));
        return;
    }

    X509Certificate[] certificateChain = km.getCertificateChain(alias);
    PrivateKey privateKey = km.getPrivateKey(alias);

    if (keyType == null) {
        keyType = privateKey.getAlgorithm();
    } else {
        assertEquals(keyType, certificateChain[0].getPublicKey().getAlgorithm());
        assertEquals(keyType, privateKey.getAlgorithm());
    }

    PrivateKeyEntry privateKeyEntry
            = TestKeyStore.privateKey(TEST_KEY_STORE.keyStore,
                                      TEST_KEY_STORE.storePassword,
                                      keyType);
    assertEquals(Arrays.asList(privateKeyEntry.getCertificateChain()),
                 Arrays.asList(certificateChain));
    assertEquals(privateKeyEntry.getPrivateKey(), privateKey);
}
项目:12306-android-Decompile    文件:WLDeviceAuthManager.java   
public boolean isCertificateExists(String paramString)
{
  if (this.context == null)
    return false;
  try
  {
    KeyStore.PrivateKeyEntry localPrivateKeyEntry = getPrivateKeyEntry(paramString);
    int i = 0;
    if (localPrivateKeyEntry != null)
      i = 1;
    return i;
  }
  catch (Exception localException)
  {
    WLUtils.error("Failed to determine the existence of certificate for device authentication with " + localException.getMessage(), localException);
  }
  return false;
}
项目:12306-android-Decompile    文件:WLDeviceAuthManager.java   
public String signDeviceAuth(String paramString1, String paramString2, boolean paramBoolean)
  throws Exception
{
  if ((paramBoolean) && (isCertificateExists(paramString2)))
  {
    JSONObject localJSONObject = new JSONObject();
    localJSONObject.put("alg", "RS256");
    KeyStore.PrivateKeyEntry localPrivateKeyEntry = getPrivateKeyEntry(paramString2);
    localJSONObject.put("x5c", Base64.encodeUrlSafe(localPrivateKeyEntry.getCertificate().getEncoded(), "UTF-8"));
    String str1 = localJSONObject.toString();
    String str2 = Base64.encodeUrlSafe(str1.getBytes(), "UTF-8") + "." + Base64.encodeUrlSafe(paramString1.getBytes(), "UTF-8");
    String str3 = Base64.encodeUrlSafe(signData(str2, localPrivateKeyEntry.getPrivateKey()), "UTF-8");
    return str2 + "." + str3;
  }
  return paramString1;
}
项目:aws-dynamodb-encryption-java    文件:KeyStoreMaterialsProvider.java   
private static KeyPair entry2Pair(Entry entry) {
    PublicKey pub = null;
    PrivateKey priv = null;

    if (entry instanceof PrivateKeyEntry) {
        PrivateKeyEntry pk = (PrivateKeyEntry) entry;
        if (pk.getCertificate() != null) {
            pub = pk.getCertificate().getPublicKey();
        }
        priv = pk.getPrivateKey();
    } else if (entry instanceof TrustedCertificateEntry) {
        TrustedCertificateEntry tc = (TrustedCertificateEntry) entry;
        pub = tc.getTrustedCertificate().getPublicKey();
    } else {
        throw new IllegalArgumentException(
                "Only entry types PrivateKeyEntry and TrustedCertificateEntry are supported.");
    }
    return new KeyPair(pub, priv);
}
项目:pushy    文件:ApnsClientBuilderTest.java   
@Test
public void testBuildClientWithCertificateAndPasswordProtectedKey() throws Exception {
    // We're happy here as long as nothing throws an exception
    try (final InputStream p12InputStream = this.getClass().getResourceAsStream(SINGLE_TOPIC_CLIENT_KEYSTORE_FILENAME)) {
        final PrivateKeyEntry privateKeyEntry =
                P12Util.getFirstPrivateKeyEntryFromP12InputStream(p12InputStream, KEYSTORE_PASSWORD);

        final ApnsClient client = new ApnsClientBuilder()
                .setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST)
                .setEventLoopGroup(EVENT_LOOP_GROUP)
                .setClientCredentials((X509Certificate) privateKeyEntry.getCertificate(), privateKeyEntry.getPrivateKey(), KEYSTORE_PASSWORD)
                .build();

        client.close().await();
    }
}
项目:pushy    文件:ApnsClientBuilderTest.java   
@Test
public void testBuildClientWithCertificateAndUnprotectedKey() throws Exception {
    // We DO need a password to unlock the keystore, but the key itself should be unprotected
    try (final InputStream p12InputStream = this.getClass().getResourceAsStream(SINGLE_TOPIC_CLIENT_KEYSTORE_UNPROTECTED_FILENAME)) {

        final PrivateKeyEntry privateKeyEntry =
                P12Util.getFirstPrivateKeyEntryFromP12InputStream(p12InputStream, KEYSTORE_PASSWORD);

        final ApnsClient client = new ApnsClientBuilder()
                .setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST)
                .setEventLoopGroup(EVENT_LOOP_GROUP)
                .setClientCredentials((X509Certificate) privateKeyEntry.getCertificate(), privateKeyEntry.getPrivateKey(), null)
                .build();

        client.close().await();
    }
}
项目:pushy    文件:ApnsClientBuilderTest.java   
@Test(expected = IllegalStateException.class)
public void testBuildWithClientCredentialsAndSigningCertificate() throws Exception {
    try (final InputStream p12InputStream = this.getClass().getResourceAsStream(SINGLE_TOPIC_CLIENT_KEYSTORE_UNPROTECTED_FILENAME)) {

        final PrivateKeyEntry privateKeyEntry =
                P12Util.getFirstPrivateKeyEntryFromP12InputStream(p12InputStream, KEYSTORE_PASSWORD);

        try (final InputStream p8InputStream = this.getClass().getResourceAsStream(SIGNING_KEY_FILENAME)) {

            final ApnsSigningKey signingKey = ApnsSigningKey.loadFromInputStream(p8InputStream, "TEAM_ID", "KEY_ID");

            new ApnsClientBuilder()
                    .setEventLoopGroup(EVENT_LOOP_GROUP)
                    .setClientCredentials((X509Certificate) privateKeyEntry.getCertificate(), privateKeyEntry.getPrivateKey(), null)
                    .setSigningKey(signingKey)
                    .build();
        }
    }
}
项目:12306-android-Decompile    文件:WLDeviceAuthManager.java   
public boolean isCertificateExists(String paramString)
{
  if (this.context == null)
    return false;
  try
  {
    KeyStore.PrivateKeyEntry localPrivateKeyEntry = getPrivateKeyEntry(paramString);
    int i = 0;
    if (localPrivateKeyEntry != null)
      i = 1;
    return i;
  }
  catch (Exception localException)
  {
    WLUtils.error("Failed to determine the existence of certificate for device authentication with " + localException.getMessage(), localException);
  }
  return false;
}
项目:12306-android-Decompile    文件:WLDeviceAuthManager.java   
public String signDeviceAuth(String paramString1, String paramString2, boolean paramBoolean)
  throws Exception
{
  if ((paramBoolean) && (isCertificateExists(paramString2)))
  {
    JSONObject localJSONObject = new JSONObject();
    localJSONObject.put("alg", "RS256");
    KeyStore.PrivateKeyEntry localPrivateKeyEntry = getPrivateKeyEntry(paramString2);
    localJSONObject.put("x5c", Base64.encodeUrlSafe(localPrivateKeyEntry.getCertificate().getEncoded(), "UTF-8"));
    String str1 = localJSONObject.toString();
    String str2 = Base64.encodeUrlSafe(str1.getBytes(), "UTF-8") + "." + Base64.encodeUrlSafe(paramString1.getBytes(), "UTF-8");
    String str3 = Base64.encodeUrlSafe(signData(str2, localPrivateKeyEntry.getPrivateKey()), "UTF-8");
    return str2 + "." + str3;
  }
  return paramString1;
}
项目:dCache-Cloud    文件:KeyStoreHelper.java   
public static boolean storeOwnAsymmetric(KeyPair pair)
    {
        X509Certificate cert = generateSelfSignedCertificate(pair);
        KeyStore.PrivateKeyEntry privEntry = new PrivateKeyEntry(pair.getPrivate(), new java.security.cert.Certificate[] {cert});

        try {
//          KeyStore ks = load(c);
            ks.setEntry("ownPrivate", privEntry, pp);
            ks.setCertificateEntry("ownCert", cert);
//          closeStore();
            return true;
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

        return false;
    }
项目:oscm    文件:SignTask.java   
private PrivateKeyEntry loadCAKeyEntry() throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore();
    final Entry entry = keystore.getEntry(this.alias,
            new PasswordProtection(this.password.toCharArray()));
    return (PrivateKeyEntry) entry;
}
项目:oscm    文件:CertificateHandler.java   
private void loadPrivateKeyEntry() throws GeneralSecurityException {
    rootPrivateKeyEntry = (PrivateKeyEntry) rootCaKeystore.getEntry(
            rootCaAlias,
            new PasswordProtection(rootCaPassword.toCharArray()));

    if (rootPrivateKeyEntry == null) {
        throw new RuntimeException(
                "Could not read private key entry from rootca keystore with alias "
                        + rootCaAlias);
    }
}
项目:xtf    文件:XTFKeyStore.java   
public void addSignedCertificate(final XTFKeyStore signerKeyStore, final String signerAlias, final String signerPassword, final String dn, final String certificateAlias, final String password) {
    try {
        final X509Certificate caCert = (X509Certificate) signerKeyStore.keystore.getCertificate(signerAlias);
        final PrivateKey caKey = (PrivateKey) signerKeyStore.keystore.getKey(signerAlias, signerPassword.toCharArray());
        final Calendar start = Calendar.getInstance();
        final Calendar expiry = Calendar.getInstance();
        expiry.add(Calendar.YEAR, 1);
        final KeyPair keyPair = generateKeyPair();
        final X500Name certName = new X500Name(dn);
        final X500Name issuerName = new X500Name(caCert.getSubjectDN().getName());
        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                issuerName,
                BigInteger.valueOf(System.nanoTime()),
                start.getTime(),
                expiry.getTime(),
                certName,
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));
        final JcaX509ExtensionUtils u = new JcaX509ExtensionUtils();
        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                u.createAuthorityKeyIdentifier(caCert));
        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                u.createSubjectKeyIdentifier(keyPair.getPublic()));
        ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(caKey);
        X509CertificateHolder holder = certificateBuilder.build(signer);
        Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);

        Entry entry = new PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] {cert, caCert});
        keystore.setEntry(certificateAlias, entry, new PasswordProtection(password.toCharArray()));
    } catch (GeneralSecurityException | OperatorCreationException | CertIOException ex) {
        throw new RuntimeException("Unable to generate signed certificate", ex);
    }
}
项目:mi-firma-android    文件:SignTask.java   
/** Construye la tarea encargada de realizar la operación criptográfica.
 * @param context Contexto de la aplicación.
 * @param pke Clave privada para la firma.
 * @param extraParams Parámetros adicionales para la configuración de la firma.*/
public SignTask(final Activity context,
                final PrivateKeyEntry pke,
                final Properties extraParams,
                final ProgressDialog progDialog) throws IOException {
    this.context = context;
    this.pke = pke;
    this.extraParams = extraParams != null ? extraParams : new Properties();
    this.progDailog = progDialog;

    final Properties p = new Properties();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open(Utils.CONFIG_FILE);
    p.load(inputStream);

    final String urlProp = p.getProperty(Utils.CONFIG_FILE_KEY_PROPOSALS);
    if (urlProp == null) {
        throw new IOException(
                "El fichero de configuracion no contiene la URL: " + Utils.CONFIG_FILE_KEY_PROPOSALS //$NON-NLS-1$
        );
    }

    urlSign = p.getProperty(Utils.CONFIG_FILE_KEY_SIGNATURE);
    if (urlSign == null) {
        throw new IOException(
                "El fichero de configuracion no contiene la URL: " + Utils.CONFIG_FILE_KEY_PROPOSALS //$NON-NLS-1$
        );
    }
}
项目:mi-firma-android    文件:MobileKeyStoreManager.java   
/** Obtiene la entrada que apunta a una clave privada asociada al evento.
 * @return Entrada que apunta a una clave privada asiciada al evento
 * @throws Throwable Si la obtención de la clave privada produjo algun error */
PrivateKeyEntry getPrivateKeyEntry() throws Throwable {
    if (this.e != null) {
        throw this.e;
    }
    return this.pke;
}
项目:mi-firma-android    文件:CeresKeyStoreImpl.java   
/** {@inheritDoc} */
@Override
public boolean engineEntryInstanceOf(final String alias, final Class<? extends KeyStore.Entry> entryClass) {
    if (!engineContainsAlias(alias)) {
        return false;
    }
    return entryClass.equals(PrivateKeyEntry.class);
}
项目:mi-firma-android    文件:DnieKeyStoreImpl.java   
/** {@inheritDoc} */
  @Override
  public KeyStore.Entry engineGetEntry(final String alias,
                                     final ProtectionParameter protParam) {

    if(protParam instanceof KeyStore.CallbackHandlerProtection) {
        // Establecemos el CallbackHandler
        final CallbackHandler chp = ((KeyStore.CallbackHandlerProtection) protParam).getCallbackHandler();
        if(chp != null) {
            this.cryptoCard.setCallbackHandler(chp);
        }
    }
    else if (protParam instanceof KeyStore.PasswordProtection) {
        // Establecemos el PasswordCallback
        final PasswordCallback pwc = new CachePasswordCallback(((KeyStore.PasswordProtection)protParam).getPassword());
        this.cryptoCard.setPasswordCallback(pwc);
    }
    else {
        LOGGER.warning(
                "Se ha proporcionado un ProtectionParameter de tipo no soportado, se ignorara: " + (protParam != null ? protParam.getClass().getName() : "NULO") //$NON-NLS-1$ //$NON-NLS-2$
    );
    }
    if (!engineContainsAlias(alias)) {
        return null;
    }
    final PrivateKey key = (PrivateKey) engineGetKey(
    alias,
    null // Le pasamos null porque ya hemos establecido el PasswordCallback o el CallbackHander antes
);
    return new PrivateKeyEntry(key, engineGetCertificateChain(alias));
  }
项目:mi-firma-android    文件:DnieKeyStoreImpl.java   
/** {@inheritDoc} */
@Override
public boolean engineEntryInstanceOf(final String alias, final Class<? extends KeyStore.Entry> entryClass) {
    if (!engineContainsAlias(alias)) {
        return false;
    }
    return entryClass.equals(PrivateKeyEntry.class);
}
项目:java-bambou    文件:DynamicKeystoreGenerator.java   
public static KeyStore createAndLoadDynamicKeystore(RSAPrivateKey rsaPrivateKey, Certificate certificate) throws KeyManagementException {
    logger.debug("Generating Keystore from RSA private key and X509 certificate");
    Certificate[] certificateChain = { certificate };
    PrivateKeyEntry privateKeyEntry = new KeyStore.PrivateKeyEntry(rsaPrivateKey, certificateChain);
    ProtectionParameter protectionParameter = new KeyStore.PasswordProtection(KEY_PASSWORD);
    KeyStore keystore = null;
    try {
        keystore = KeyStore.getInstance(KEYSTORE_INSTANCE_TYPE);
        keystore.load(null, null);
        keystore.setEntry(KEYSTORE_ALIAS, privateKeyEntry, protectionParameter);
    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException ex) {
        throw new KeyManagementException(ex);
    }
    return keystore;
}
项目:conscrypt    文件:NativeCryptoTest.java   
/**
 * Lazily create shared test certificates.
 */
private static synchronized void initCerts() {
    if (SERVER_PRIVATE_KEY != null) {
        return;
    }

    try {
        PrivateKeyEntry serverPrivateKeyEntry =
                TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
        SERVER_PRIVATE_KEY = OpenSSLKey.fromPrivateKey(serverPrivateKeyEntry.getPrivateKey());
        SERVER_CERTIFICATES_HOLDER =
                encodeCertificateList(serverPrivateKeyEntry.getCertificateChain());
        SERVER_CERTIFICATE_REFS = getCertificateReferences(SERVER_CERTIFICATES_HOLDER);
        ENCODED_SERVER_CERTIFICATES = getEncodedCertificates(SERVER_CERTIFICATES_HOLDER);

        PrivateKeyEntry clientPrivateKeyEntry =
                TestKeyStore.getClientCertificate().getPrivateKey("RSA", "RSA");
        CLIENT_PRIVATE_KEY = OpenSSLKey.fromPrivateKey(clientPrivateKeyEntry.getPrivateKey());
        CLIENT_CERTIFICATES_HOLDER =
                encodeCertificateList(clientPrivateKeyEntry.getCertificateChain());
        CLIENT_CERTIFICATE_REFS = getCertificateReferences(CLIENT_CERTIFICATES_HOLDER);
        ENCODED_CLIENT_CERTIFICATES = getEncodedCertificates(CLIENT_CERTIFICATES_HOLDER);

        KeyStore ks = TestKeyStore.getClient().keyStore;
        String caCertAlias = ks.aliases().nextElement();
        X509Certificate certificate = (X509Certificate) ks.getCertificate(caCertAlias);
        X500Principal principal = certificate.getIssuerX500Principal();
        CA_PRINCIPALS = new byte[][] {principal.getEncoded()};
        initChannelIdKey();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:conscrypt    文件:TestKeyStore.java   
private static OCSPResp generateOCSPResponse(PrivateKeyEntry server, PrivateKeyEntry issuer,
        CertificateStatus status) throws CertificateException {
    try {
        X509Certificate serverCertJca = (X509Certificate) server.getCertificate();
        X509Certificate caCertJca = (X509Certificate) issuer.getCertificate();

        X509CertificateHolder caCert = new JcaX509CertificateHolder(caCertJca);

        DigestCalculatorProvider digCalcProv = new BcDigestCalculatorProvider();
        BasicOCSPRespBuilder basicBuilder = new BasicOCSPRespBuilder(
                SubjectPublicKeyInfo.getInstance(caCertJca.getPublicKey().getEncoded()),
                digCalcProv.get(CertificateID.HASH_SHA1));

        CertificateID certId = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1),
                caCert, serverCertJca.getSerialNumber());

        basicBuilder.addResponse(certId, status);

        BasicOCSPResp resp = basicBuilder.build(
                new JcaContentSignerBuilder("SHA256withRSA").build(issuer.getPrivateKey()),
                null, new Date());

        OCSPRespBuilder builder = new OCSPRespBuilder();
        return builder.build(OCSPRespBuilder.SUCCESSFUL, resp);
    } catch (Exception e) {
        throw new CertificateException("cannot generate OCSP response", e);
    }
}
项目:conscrypt    文件:TestKeyStore.java   
public static byte[] getOCSPResponseForGood(PrivateKeyEntry server, PrivateKeyEntry issuer)
        throws CertificateException {
    try {
        return generateOCSPResponse(server, issuer, CertificateStatus.GOOD).getEncoded();
    } catch (IOException e) {
        throw new CertificateException(e);
    }
}
项目:conscrypt    文件:TestKeyStore.java   
public static byte[] getOCSPResponseForRevoked(PrivateKeyEntry server, PrivateKeyEntry issuer)
        throws CertificateException {
    try {
        return generateOCSPResponse(
                server, issuer, new RevokedStatus(new Date(), CRLReason.keyCompromise))
                .getEncoded();
    } catch (IOException e) {
        throw new CertificateException(e);
    }
}
项目:conscrypt    文件:TrustManagerFactoryTest.java   
@Test
public void test_TrustManagerFactory_intermediate() throws Exception {
    // chain should be server/intermediate/root
    PrivateKeyEntry pke = TestKeyStore.getServer().getPrivateKey("RSA", "RSA");
    X509Certificate[] chain = (X509Certificate[]) pke.getCertificateChain();
    assertEquals(3, chain.length);

    // keyStore should contain only the intermediate CA so we can
    // test proper validation even if there are extra certs after
    // the trusted one (in this case the original root is "extra")
    KeyStore keyStore = TestKeyStore.createKeyStore();
    keyStore.setCertificateEntry("alias", chain[1]);

    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
        Set<Provider.Service> services = provider.getServices();
        for (Provider.Service service : services) {
            String type = service.getType();
            if (!type.equals("TrustManagerFactory")) {
                continue;
            }
            String algorithm = service.getAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(keyStore);
            TrustManager[] trustManagers = tmf.getTrustManagers();
            for (TrustManager trustManager : trustManagers) {
                if (!(trustManager instanceof X509TrustManager)) {
                    continue;
                }
                X509TrustManager tm = (X509TrustManager) trustManager;
                tm.checkClientTrusted(chain, "RSA");
                tm.checkServerTrusted(chain, "RSA");
            }
        }
    }
}
项目:conscrypt    文件:TrustManagerFactoryTest.java   
@Test
public void test_TrustManagerFactory_keyOnly() throws Exception {
    // create a KeyStore containing only a private key with chain.
    // unlike PKIXParameters(KeyStore), the cert chain of the key should be trusted.
    KeyStore ks = TestKeyStore.createKeyStore();
    KeyStore.PrivateKeyEntry pke = getTestKeyStore().getPrivateKey("RSA", "RSA");
    ks.setKeyEntry("key", pke.getPrivateKey(), "pw".toCharArray(), pke.getCertificateChain());

    String algorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ks);
    X509TrustManager trustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    trustManager.checkServerTrusted((X509Certificate[]) pke.getCertificateChain(), "RSA");
}
项目:conscrypt    文件:KeyManagerFactoryTest.java   
private void test_X509KeyManager_alias(X509KeyManager km, String alias, String keyType,
        boolean many, boolean empty) throws Exception {
    if (empty || (!many && (keyType == null || keyType.isEmpty()))) {
        assertNull(keyType, alias);
        assertNull(keyType, km.getCertificateChain(alias));
        assertNull(keyType, km.getPrivateKey(alias));
        return;
    }
    assertNotNull(keyType, alias);

    X509Certificate[] certificateChain = km.getCertificateChain(alias);
    PrivateKey privateKey = km.getPrivateKey(alias);

    String keyAlgName = privateKey.getAlgorithm();

    X509Certificate certificate = certificateChain[0];
    assertEquals(keyType, keyAlgName, certificate.getPublicKey().getAlgorithm());

    String sigAlgName = certificate.getSigAlgName();

    PrivateKeyEntry privateKeyEntry = getTestKeyStore().getPrivateKey(keyAlgName, sigAlgName);

    assertEquals(keyType, Arrays.asList(privateKeyEntry.getCertificateChain()),
            Arrays.<Certificate>asList(certificateChain));
    assertEquals(keyType, privateKeyEntry.getPrivateKey(), privateKey);

    if (keyType != null) {
        assertEquals(TestKeyStore.keyAlgorithm(keyType), keyAlgName);

        // Skip this when we're given only "DH" or "EC" instead of "DH_DSA",
        // "EC_RSA", etc. since we don't know what the expected
        // algorithm was.
        if (!keyType.equals("DH") && !keyType.equals("EC")) {
            assertTrue(sigAlgName.contains(TestKeyStore.signatureAlgorithm(keyType)));
        }
    }
}
项目:aws-encryption-sdk-java    文件:KeyStoreProvider.java   
private JceMasterKey internalGetMasterKey(final String provider, final String keyId) {
    final Entry entry;
    try {
        entry = keystore_.getEntry(keyId, keystore_.isKeyEntry(keyId) ? protection_ : null);
    } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
        throw new UnsupportedProviderException(e);
    }
    if (entry == null) {
        throw new NoSuchMasterKeyException();
    }
    if (entry instanceof SecretKeyEntry) {
        final SecretKeyEntry skEntry = (SecretKeyEntry) entry;
        if (!skEntry.getSecretKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(skEntry.getSecretKey(), provider, keyId, wrappingAlgorithm_);
    } else if (entry instanceof PrivateKeyEntry) {
        final PrivateKeyEntry pkEntry = (PrivateKeyEntry) entry;
        if (!pkEntry.getPrivateKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey(), provider,
                keyId, wrappingAlgorithm_);
    } else if (entry instanceof TrustedCertificateEntry) {
        final TrustedCertificateEntry certEntry = (TrustedCertificateEntry) entry;
        if (!certEntry.getTrustedCertificate().getPublicKey().getAlgorithm().equals(keyAlgorithm_)) {
            return null;
        }
        return JceMasterKey.getInstance(certEntry.getTrustedCertificate().getPublicKey(), null, provider, keyId,
                wrappingAlgorithm_);
    } else {
        throw new NoSuchMasterKeyException();
    }
}
项目:eid-applet    文件:PKCS11Test.java   
@Test
public void testPKCS1viaPKCS11() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=2");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
    keyStore.load(null, null);
    PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));

    // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj)
}
项目:development    文件:SignTask.java   
private PrivateKeyEntry loadCAKeyEntry() throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore();
    final Entry entry = keystore.getEntry(this.alias,
            new PasswordProtection(this.password.toCharArray()));
    return (PrivateKeyEntry) entry;
}
项目:development    文件:CertificateHandler.java   
private void loadPrivateKeyEntry() throws GeneralSecurityException {
    rootPrivateKeyEntry = (PrivateKeyEntry) rootCaKeystore.getEntry(
            rootCaAlias,
            new PasswordProtection(rootCaPassword.toCharArray()));

    if (rootPrivateKeyEntry == null) {
        throw new RuntimeException(
                "Could not read private key entry from rootca keystore with alias "
                        + rootCaAlias);
    }
}
项目:dss    文件:AbstractKeyStoreTokenConnection.java   
private KSPrivateKeyEntry getKSPrivateKeyEntry(final String alias, ProtectionParameter passwordProtection) {
    KeyStore keyStore = getKeyStore();
    try {
        if (keyStore.isKeyEntry(alias)) {
            final PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, passwordProtection);
            return new KSPrivateKeyEntry(alias, entry);
        }
    } catch (GeneralSecurityException e) {
        throw new DSSException("Unable to retrieve key for alias '" + alias + "'", e);
    }
    return null;
}
项目:In-the-Box-Fork    文件:KeyManagerImpl.java   
private String[] chooseAlias(String[] keyType, Principal[] issuers) {
    if (keyType == null || keyType.length == 0) {
        return null;
    }
    Vector<String> found = new Vector<String>();
    for (Enumeration<String> aliases = hash.keys(); aliases.hasMoreElements();) {
        final String alias = aliases.nextElement();
        final KeyStore.PrivateKeyEntry entry = hash.get(alias);
        final Certificate[] certs = entry.getCertificateChain();
        final String alg = certs[0].getPublicKey().getAlgorithm();
        for (int i = 0; i < keyType.length; i++) {
            if (alg.equals(keyType[i])) {
                if (issuers != null && issuers.length != 0) {
                    // check that certificate was issued by specified issuer
                    loop: for (int ii = 0; ii < certs.length; ii++) {
                        if (certs[ii] instanceof X509Certificate) {
                            X500Principal issuer = ((X509Certificate) certs[ii])
                                    .getIssuerX500Principal();
                            for (int iii = 0; iii < issuers.length; iii++) {
                                if (issuer.equals(issuers[iii])) {
                                    found.add(alias);
                                    break loop;
                                }
                            }
                        }

                    }
                } else {
                    found.add(alias);
                }
            }
        }
    }
    if (!found.isEmpty()) {
        return found.toArray(new String[found.size()]);
    }
    return null;
}
项目:In-the-Box-Fork    文件:KeyStoreTest.java   
public static void setPrivateKey(KeyStore ks,
                                 String alias,
                                 PrivateKeyEntry privateKey)
        throws Exception {
    ks.setKeyEntry(alias,
                   privateKey.getPrivateKey(),
                   PASSWORD_KEY,
                   privateKey.getCertificateChain());
}