Java Code Examples for java.security.KeyStore#getKey()

The following examples show how to use java.security.KeyStore#getKey() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KeyStoreAdmin.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public Key getPrivateKey(String alias, boolean isSuperTenant) throws SecurityConfigException {
    KeyStoreData[] keystores = getKeyStores(isSuperTenant);
    KeyStore keyStore = null;
    String privateKeyPassowrd = null;

    try {

        for (int i = 0; i < keystores.length; i++) {
            if (KeyStoreUtil.isPrimaryStore(keystores[i].getKeyStoreName())) {
                KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
                keyStore = keyMan.getPrimaryKeyStore();
                ServerConfiguration serverConfig = ServerConfiguration.getInstance();
                privateKeyPassowrd = serverConfig
                        .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
                return keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
            }
        }
    } catch (Exception e) {
        String msg = "Error has encounted while loading the key for the given alias " + alias;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
    return null;
}
 
Example 2
Source File: MetadataStoreLoadTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example 3
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpSignatureRsaSha512ServiceProperties() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner("rsa-sha512", keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsigrsasha512props/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 4
Source File: CastError.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = new FileInputStream(
            new File(System.getProperty("test.src"),
                    "../tools/jarsigner/JarSigning.keystore"));
    ks.load(fis, "bbbbbb".toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey("c", "bbbbbb".toCharArray());
    Certificate cert = ks.getCertificate("c");

    ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);

    ks.setKeyEntry("8143913", pk, null, new Certificate[]{cert});
    ks.deleteEntry("8143913");
}
 
Example 5
Source File: MetadataStoreLoadTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example 6
Source File: KeystoreOptionsSubPanel.java    From NBANDROID-V2 with Apache License 2.0 6 votes vote down vote up
@Override
public boolean valid() {
    try {
        File f = new File(path.getText());
        if (f.exists()) {
            KeyStore ks = KeyStore.getInstance("jks");
            ks.load(new FileInputStream(f), keystorePassword.getPassword());
            Key key = ks.getKey(alias.getText(), keyPassword.getPassword());
            if (key != null) {
                return true;
            }
        }
    } catch (Exception ex) {
    }
    return false;
}
 
Example 7
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttpSignature() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    MessageSigner messageSigner = new MessageSigner(keyId -> privateKey, "alice-key-id");
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 8
Source File: KeyStoreFileManager.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param keystorePath
 * @param keyName
 * @param encodedPassword
 * @throws UnrecoverableKeyException if the password is invalid
 */
public static void validateKeyPassword( String keystorePath, String keyName, String encodedPassword)
    throws Exception
{
    char[] password = null;
    try {
        KeyStore ks = KeyStoreFileManager.loadKeyStore( keystorePath, (char[])null);
        password = PasswordObfuscator.getInstance().decodeAliasPassword(keystorePath,keyName, encodedPassword);
        ks.getKey(keyName, password);
    } finally {
        if (password != null) PasswordObfuscator.flush(password);
    }

}
 
Example 9
Source File: KeyPairManager.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
static KeyPair getKeyPair(String alias) throws IOException {
  checkNotNull(alias, "alias cannot be null");
  String keyStoreFile = System.getProperty(KEY_STORE_KEY);
  if (keyStoreFile == null) {
    throw new IOException(KEY_STORE_KEY + " is not set");
  }
  String keyStoreType = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
  String keyStorePassword = System.getProperty(KEY_STORE_PASSWORD_KEY);
  if (keyStorePassword == null) {
    throw new IOException(KEY_STORE_PASSWORD_KEY + " is not set");
  }

  try (InputStream inputStream = new FileInputStream(keyStoreFile)) {
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(inputStream, keyStorePassword.toCharArray());
    Key key = keyStore.getKey(alias, keyStorePassword.toCharArray());

    if (key == null) {
      throw new IOException("No key for alias " + alias);
    }

    PrivateKey privateKey = (PrivateKey) key;
    PublicKey publicKey = keyStore.getCertificate(alias).getPublicKey();
    return new KeyPair(publicKey, privateKey);
  } catch (KeyStoreException
      | CertificateException
      | NoSuchAlgorithmException
      | UnrecoverableKeyException e) {
    throw new IOException(e);
  }
}
 
Example 10
Source File: RootCertificateLoader.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
static RootCertificateImpl loadRootCertificate(final KeyStore keystore, final String alias) {
  try {
    final Certificate certificate = keystore.getCertificate(alias);
    final PrivateKey privateKey = (PrivateKey) keystore.getKey(alias, null);
    if (certificate == null || privateKey == null)
      throw new CaException("Keystore does not contain certificate and key for alias " + alias);
    return new RootCertificateImpl((X509Certificate) certificate, privateKey);
  } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
    throw new CaException(e);
  }
}
 
Example 11
Source File: SM2Pkcs12MakerTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPkcs12Sign() {
    //先生成一个pkcs12
    testMakePkcs12();

    try {
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        try (InputStream is = Files.newInputStream(Paths.get(TEST_P12_FILENAME),
                                  StandardOpenOption.READ)) {
            ks.load(is, TEST_P12_PASSWD);
        }

        PrivateKey privateKey = (BCECPrivateKey) ks.getKey("User Key", TEST_P12_PASSWD);
        X509Certificate cert = (X509Certificate) ks.getCertificate("User Key");

        byte[] srcData = "1234567890123456789012345678901234567890".getBytes();

        // create signature
        Signature sign = Signature.getInstance(SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2, "BC");
        sign.initSign(privateKey);
        sign.update(srcData);
        byte[] signatureValue = sign.sign();

        // verify signature
        Signature verify = Signature.getInstance(SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2, "BC");
        verify.initVerify(cert);
        verify.update(srcData);
        boolean sigValid = verify.verify(signatureValue);
        Assert.assertTrue("signature validation result", sigValid);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 12
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderTrailingWhitespace() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    List<String> headerList = Arrays.asList("custom", "(request-target)");
    MessageSigner messageSigner = new MessageSigner(keyid -> privateKey, "alice-key-id", headerList);
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    client.header("custom", " someval    ");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 13
Source File: FingerprintActivity.java    From AndroidSamples with Apache License 2.0 5 votes vote down vote up
@Nullable
private KeyPair getKeyPair(String keyName) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);
    if (keyStore.containsAlias(keyName)) {
        // Get public key
        PublicKey publicKey = keyStore.getCertificate(keyName).getPublicKey();
        // Get private key
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyName, null);
        // Return a key pair
        return new KeyPair(publicKey, privateKey);
    }
    return null;
}
 
Example 14
Source File: OpcUaClientSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private OpcUaClient createClient() throws Exception {
  SecurityPolicy securityPolicy = conf.securityPolicy.getSecurityPolicy();

  EndpointDescription[] endpoints = UaTcpStackClient.getEndpoints(conf.resourceUrl).get();

  EndpointDescription endpoint = Arrays.stream(endpoints)
      .filter(e -> e.getSecurityPolicyUri().equals(securityPolicy.getSecurityPolicyUri()))
      .findFirst().orElseThrow(() -> new StageException(Errors.OPC_UA_01));

  ChannelConfig channelConfig = new ChannelConfig(
      conf.channelConf.maxChunkSize,
      conf.channelConf.maxChunkCount,
      conf.channelConf.maxMessageSize,
      conf.channelConf.maxArrayLength,
      conf.channelConf.maxStringLength
  );
  OpcUaClientConfigBuilder clientConfigBuilder = OpcUaClientConfig.builder()
      .setApplicationName(LocalizedText.english(conf.applicationName))
      .setApplicationUri(conf.applicationUri)
      .setChannelConfig(channelConfig);

  if (!securityPolicy.equals(SecurityPolicy.None)) {
    KeyStore keyStore = conf.tlsConfig.getKeyStore();
    if (keyStore != null) {
      Key clientPrivateKey = keyStore.getKey(conf.clientKeyAlias, conf.tlsConfig.keyStorePassword.get().toCharArray());
      if (clientPrivateKey instanceof PrivateKey) {
        X509Certificate clientCertificate = (X509Certificate) keyStore.getCertificate(conf.clientKeyAlias);
        PublicKey clientPublicKey = clientCertificate.getPublicKey();
        KeyPair clientKeyPair = new KeyPair(clientPublicKey, (PrivateKey) clientPrivateKey);
        clientConfigBuilder.setCertificate(clientCertificate)
            .setKeyPair(clientKeyPair);
      }
    }
  }

  OpcUaClientConfig config = clientConfigBuilder.setEndpoint(endpoint)
      .setIdentityProvider(new AnonymousProvider())
      .setRequestTimeout(uint(conf.requestTimeoutMillis))
      .setSessionTimeout(uint(conf.sessionTimeoutMillis))
      .build();

  return new OpcUaClient(config);
}
 
Example 15
Source File: RenameKeyAction.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Rename the currently selected entry
 */
public void renameSelectedEntry() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
		KeyStoreState currentState = history.getCurrentState();

		String alias = kseFrame.getSelectedEntryAlias();

		Password password = getEntryPassword(alias, currentState);

		if (password == null) {
			return;
		}

		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();

		Key key = keyStore.getKey(alias, password.toCharArray());

		DGetAlias dGetAlias = new DGetAlias(frame, res.getString("RenameKeyAction.NewEntryAlias.Title"), alias);
		dGetAlias.setLocationRelativeTo(frame);
		dGetAlias.setVisible(true);
		String newAlias = dGetAlias.getAlias();

		if (newAlias == null) {
			return;
		}

		if (newAlias.equalsIgnoreCase(alias)) {
			JOptionPane.showMessageDialog(frame,
					MessageFormat.format(res.getString("RenameKeyAction.RenameAliasIdentical.message"), alias),
					res.getString("RenameKeyAction.RenameEntry.Title"), JOptionPane.WARNING_MESSAGE);
			return;
		}

		if (keyStore.containsAlias(newAlias)) {
			String message = MessageFormat
					.format(res.getString("RenameKeyAction.OverWriteEntry.message"), newAlias);

			int selected = JOptionPane.showConfirmDialog(frame, message,
					res.getString("RenameKeyAction.RenameEntry.Title"), JOptionPane.YES_NO_OPTION);
			if (selected != JOptionPane.YES_OPTION) {
				return;
			}

			keyStore.deleteEntry(newAlias);
			newState.removeEntryPassword(newAlias);
		}

		keyStore.setKeyEntry(newAlias, key, password.toCharArray(), null);
		newState.setEntryPassword(newAlias, new Password(password));

		keyStore.deleteEntry(alias);
		newState.removeEntryPassword(alias);

		currentState.append(newState);

		kseFrame.updateControls(true);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 16
Source File: BigCRL.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int n = 500000;
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "."
            + X509CertInfo.DN_NAME);

    Date date = new Date();
    PrivateKey privateKey = (PrivateKey)
            keyStore.getKey(alias, pass.toCharArray());
    String sigAlgName = signerCertImpl.getSigAlgOID();

    X509CRLEntry[] badCerts = new X509CRLEntry[n];
    CRLExtensions ext = new CRLExtensions();
    ext.set("Reason", new CRLReasonCodeExtension(1));
    for (int i = 0; i < n; i++) {
        badCerts[i] = new X509CRLEntryImpl(
                BigInteger.valueOf(i), date, ext);
    }
    X509CRLImpl crl = new X509CRLImpl(owner, date, date, badCerts);
    crl.sign(privateKey, sigAlgName);
    byte[] data = crl.getEncodedInternal();

    // Make sure the CRL is big enough
    if ((data[1]&0xff) != 0x84) {
        throw new Exception("The file should be big enough?");
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cf.generateCRL(new ByteArrayInputStream(data));
}
 
Example 17
Source File: ReadP12Test.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private void readTest(String inKeyStore) throws Exception {

        KeyStore inputKeyStore;

        // Initialize KeyStore
        String dir = System.getProperty("test.src", ".");
        String keystorePath = dir + File.separator + "certs" + File.separator
                + "readP12";
        inputKeyStore = KeyStore
                .getInstance(IN_KETYSTORE_TYPE, IN_KEYSTORE_PRV);
        // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
        // first.
        byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
        ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64
                .getMimeDecoder().decode(input));
        inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
        out.println("Initialize KeyStore : " + inKeyStore + " success");

        out.println("getProvider : " + inputKeyStore.getProvider());
        out.println("getType : " + inputKeyStore.getType());
        out.println("getDefaultType : " + KeyStore.getDefaultType());

        int idx = 0;
        Enumeration<String> e = inputKeyStore.aliases();
        String alias;
        while (e.hasMoreElements()) {
            alias = e.nextElement();
            out.println("Alias " + idx + " : " + alias);
            if (inputKeyStore.containsAlias(alias) == false) {
                throw new RuntimeException("Alias not found");
            }

            out.println("getCreationDate : "
                    + inputKeyStore.getCreationDate(alias));

            X509Certificate cert = (X509Certificate) inputKeyStore
                    .getCertificate(alias);
            out.println("getCertificate : " + cert.getSubjectDN());
            String retAlias = inputKeyStore.getCertificateAlias(cert);
            if (!retAlias.equals(alias)) {
                throw new RuntimeException("Alias mismatch");
            }
            out.println("getCertificateAlias : " + retAlias);

            Certificate[] certs = inputKeyStore.getCertificateChain(alias);
            for (int i = 0; i < certs.length; i++) {
                out.println("getCertificateChain " + i + " : "
                        + ((X509Certificate) certs[i]).getSubjectDN());
            }

            boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
            // test KeyStore only contain key pair entries.
            if (isCertEntry == true) {
                throw new RuntimeException(
                        "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
            }

            boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
            if (isKeyEntry) {
                Key key = inputKeyStore.getKey(alias,
                        IN_STORE_PASS.toCharArray());
                out.println("Key : " + key.toString());
            } else {
                throw new RuntimeException("Entry type unknown\n");
            }
            idx++;
        }

        int size = inputKeyStore.size();
        if (idx != size) {
            throw new RuntimeException("Size not match");
        }

    }
 
Example 18
Source File: BigCRL.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    int n = 500000;
    String ks = System.getProperty("test.src", ".")
            + "/../../ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name owner = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "."
            + X509CertInfo.DN_NAME);

    Date date = new Date();
    PrivateKey privateKey = (PrivateKey)
            keyStore.getKey(alias, pass.toCharArray());
    String sigAlgName = signerCertImpl.getSigAlgOID();

    X509CRLEntry[] badCerts = new X509CRLEntry[n];
    CRLExtensions ext = new CRLExtensions();
    ext.set("Reason", new CRLReasonCodeExtension(1));
    for (int i = 0; i < n; i++) {
        badCerts[i] = new X509CRLEntryImpl(
                BigInteger.valueOf(i), date, ext);
    }
    X509CRLImpl crl = new X509CRLImpl(owner, date, date, badCerts);
    crl.sign(privateKey, sigAlgName);
    byte[] data = crl.getEncodedInternal();

    // Make sure the CRL is big enough
    if ((data[1]&0xff) != 0x84) {
        throw new Exception("The file should be big enough?");
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    cf.generateCRL(new ByteArrayInputStream(data));
}
 
Example 19
Source File: AddPrivateKey.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static void test(Provider p, PrivateKeyEntry entry) throws Exception {
    PrivateKey key = entry.getPrivateKey();
    X509Certificate[] chain = (X509Certificate[])entry.getCertificateChain();
    PublicKey publicKey = chain[0].getPublicKey();
    System.out.println(toString(key));
    sign(p, key, publicKey);

    KeyStore ks = KeyStore.getInstance("PKCS11", p);
    ks.load(null, null);
    if (ks.size() != 0) {
        throw new Exception("KeyStore not empty");
    }
    List<String> aliases;

    // test 1: add entry
    ks.setKeyEntry(ALIAS1, key, null, chain);
    aliases = aliases(ks);
    if (aliases.size() != 1) {
        throw new Exception("size not 1: " + aliases);
    }
    if (aliases.get(0).equals(ALIAS1) == false) {
        throw new Exception("alias mismatch: " + aliases);
    }

    PrivateKey key2 = (PrivateKey)ks.getKey(ALIAS1, null);
    System.out.println(toString(key2));
    X509Certificate[] chain2 =
            (X509Certificate[]) ks.getCertificateChain(ALIAS1);
    if (Arrays.equals(chain, chain2) == false) {
        throw new Exception("chain mismatch");
    }
    sign(p, key2, publicKey);

    ks.deleteEntry(ALIAS1);
    if (ks.size() != 0) {
        throw new Exception("KeyStore not empty");
    }

    // test 2: translate to session object, then add entry
    KeyFactory kf = KeyFactory.getInstance(key.getAlgorithm(), p);
    PrivateKey key3 = (PrivateKey)kf.translateKey(key);
    System.out.println(toString(key3));
    sign(p, key3, publicKey);

    ks.setKeyEntry(ALIAS2, key3, null, chain);
    aliases = aliases(ks);
    if (aliases.size() != 1) {
        throw new Exception("size not 1");
    }
    if (aliases.get(0).equals(ALIAS2) == false) {
        throw new Exception("alias mismatch: " + aliases);
    }

    PrivateKey key4 = (PrivateKey)ks.getKey(ALIAS2, null);
    System.out.println(toString(key4));
    X509Certificate[] chain4 = (X509Certificate[])
            ks.getCertificateChain(ALIAS2);
    if (Arrays.equals(chain, chain4) == false) {
        throw new Exception("chain mismatch");
    }
    sign(p, key4, publicKey);

    // test 3: change alias
    ks.setKeyEntry(ALIAS3, key3, null, chain);
    aliases = aliases(ks);
    if (aliases.size() != 1) {
        throw new Exception("size not 1");
    }
    if (aliases.get(0).equals(ALIAS3) == false) {
        throw new Exception("alias mismatch: " + aliases);
    }

    PrivateKey key5 = (PrivateKey)ks.getKey(ALIAS3, null);
    System.out.println(toString(key5));
    X509Certificate[] chain5 = (X509Certificate[])
            ks.getCertificateChain(ALIAS3);
    if (Arrays.equals(chain, chain5) == false) {
        throw new Exception("chain mismatch");
    }
    sign(p, key5, publicKey);

    ks.deleteEntry(ALIAS3);
    if (ks.size() != 0) {
        throw new Exception("KeyStore not empty");
    }

    System.out.println("OK");
}
 
Example 20
Source File: ToolCertificate.java    From protools with Apache License 2.0 1 votes vote down vote up
/**
 * 由KeyStore获得私钥
 *
 * @param keyStorePath
 *         密钥库路径
 * @param alias
 *         别名
 * @param password
 *         密码
 *
 * @return PrivateKey 私钥
 *
 * @throws Exception
 */
private static PrivateKey getPrivateKeyByKeyStore(String keyStorePath, String alias, String password) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException {

    // 获得密钥库
    KeyStore ks = getKeyStore(keyStorePath, password);

    // 获得私钥
    return (PrivateKey) ks.getKey(alias, password.toCharArray());

}