List of usage examples for java.security KeyStore getKey
public final Key getKey(String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testSwingParent2() throws Exception { Security.addProvider(new BeIDProvider()); MyFrame myFrame = new MyFrame(); final KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(myFrame);/*from www . j a v a 2s. co m*/ final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); final Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(authnPrivateKey); final byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); Certificate[] certificateChain = keyStore.getCertificateChain("Authentication"); signature.initVerify(certificateChain[0]); signature.update(toBeSigned); assertTrue(signature.verify(signatureValue)); }
From source file:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java
/** * Load all signing information necessary for pass generation from the filesystem or classpath. * /*from ww w . j av a2 s . co m*/ * @param pkcs12KeyStoreFilePath * path to keystore (classpath or filesystem) * @param keyStorePassword * Password used to access the key store * @param appleWWDRCAFilePath * path to apple's WWDRCA certificate file (classpath or filesystem) * @return * a {@link PKSigningInformation} object filled with all certificates from the provided files * @throws IOException * @throws NoSuchAlgorithmException * @throws CertificateException * @throws KeyStoreException * @throws NoSuchProviderException * @throws UnrecoverableKeyException */ public PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificate( final String pkcs12KeyStoreFilePath, final String keyStorePassword, final String appleWWDRCAFilePath) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException { KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreFilePath, keyStorePassword); Enumeration<String> aliases = pkcs12KeyStore.aliases(); PrivateKey signingPrivateKey = null; X509Certificate signingCert = null; // find the certificate while (aliases.hasMoreElements()) { String aliasName = aliases.nextElement(); Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray()); if (key instanceof PrivateKey) { signingPrivateKey = (PrivateKey) key; Object cert = pkcs12KeyStore.getCertificate(aliasName); if (cert instanceof X509Certificate) { signingCert = (X509Certificate) cert; break; } } } X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFilePath); return checkCertsAndReturnSigningInformationObject(signingPrivateKey, signingCert, appleWWDRCACert); }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd, final String keyAlias, final String signAlg, final boolean withTag) { try {/*from w ww . ja va2 s . c o m*/ if (odlKeyStore.containsAlias(keyAlias)) { final X509Certificate odlCert = (X509Certificate) odlKeyStore.getCertificate(keyAlias); final PublicKey pubKey = odlCert.getPublicKey(); final PrivateKey privKey = (PrivateKey) odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray()); final String subject = odlCert.getSubjectDN().getName(); final X509Name xname = new X509Name(subject); final String signatureAlgorithm = signAlg; final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname, pubKey, null, privKey); final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST); sb.append("\n"); sb.append(certReq); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST); return sb.toString(); } return certReq; } LOG.info("KeyStore does not contain alias {}", keyAlias); return null; } catch (final NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) { LOG.error("Failed to generate certificate request", e); return null; } }
From source file:mitm.djigzo.web.pages.admin.SSLCertificateManager.java
public void onValidateForm() { if (password != null && file != null) { try {/*from w w w.j a v a 2s .c o m*/ KeyStore keyStore = getKeyStore(); boolean keyFound = false; boolean validForSSL = true; Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.getKey(alias, null) != null) { Certificate certificate = keyStore.getCertificate(alias); if (!(certificate instanceof X509Certificate)) { continue; } /* * Check if the certificate is valid for SSL */ X509CertificateInspector inspector = new X509CertificateInspector( (X509Certificate) certificate); Set<ExtendedKeyUsageType> extendedKeyUsage = inspector.getExtendedKeyUsage(); if (extendedKeyUsage != null && !(extendedKeyUsage.contains(ExtendedKeyUsageType.ANYKEYUSAGE) || extendedKeyUsage.contains(ExtendedKeyUsageType.SERVERAUTH))) { validForSSL = false; } Set<KeyUsageType> keyUsage = inspector.getKeyUsage(); if (keyUsage != null && !(keyUsage.contains(KeyUsageType.KEYAGREEMENT) || keyUsage.contains(KeyUsageType.KEYENCIPHERMENT))) { validForSSL = false; } keyFound = true; break; } } if (!keyFound) { form.recordError(upload, "The PFX file does not contain a key."); } else { if (!validForSSL) { form.recordError(upload, "The certificate contained in the PFX file is not valid for SSL"); } } } catch (Exception e) { /* * loading a PFX can sometime result in a ClassCastException so we catch Exception. */ form.recordError(upload, "The PFX file could not be read. Message: " + e.getMessage()); logger.error("File is not a valid PFX file.", e); } } }
From source file:org.sonatype.flexmojos.air.SignAirMojo.java
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException, MojoFailureException { AIRPackager airPackager = new AIRPackager(); try {/* w w w .ja va 2 s.com*/ String c = this.classifier == null ? "" : "-" + this.classifier; File output = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + AIR); airPackager.setOutput(output); airPackager.setDescriptor(getAirDescriptor()); KeyStore keyStore = KeyStore.getInstance(storetype); keyStore.load(new FileInputStream(keystore.getAbsolutePath()), storepass.toCharArray()); String alias = keyStore.aliases().nextElement(); airPackager.setPrivateKey((PrivateKey) keyStore.getKey(alias, storepass.toCharArray())); airPackager.setSignerCertificate(keyStore.getCertificate(alias)); airPackager.setCertificateChain(keyStore.getCertificateChain(alias)); if (this.timestampURL != null) { airPackager.setTimestampURL(TIMESTAMP_NONE.equals(this.timestampURL) ? null : this.timestampURL); } String packaging = project.getPackaging(); if (AIR.equals(packaging)) { Set<Artifact> deps = project.getDependencyArtifacts(); for (Artifact artifact : deps) { if (SWF.equals(artifact.getType())) { File source = artifact.getFile(); String path = source.getName(); if (stripVersion && path.contains(artifact.getVersion())) { path = path.replace("-" + artifact.getVersion(), ""); } getLog().debug(" adding source " + source + " with path " + path); airPackager.addSourceWithPath(source, path); } } } else if (SWF.equals(packaging)) { File source = project.getArtifact().getFile(); String path = source.getName(); getLog().debug(" adding source " + source + " with path " + path); airPackager.addSourceWithPath(source, path); } else { throw new MojoFailureException("Unexpected project packaging " + packaging); } if (includeFiles == null && includeFileSets == null) { includeFileSets = resources.toArray(new FileSet[0]); } if (includeFiles != null) { for (final String includePath : includeFiles) { String directory = project.getBuild().getOutputDirectory(); addSourceWithPath(airPackager, directory, includePath); } } if (includeFileSets != null) { for (FileSet set : includeFileSets) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(set.getDirectory()); scanner.setIncludes((String[]) set.getIncludes().toArray(new String[0])); scanner.setExcludes((String[]) set.getExcludes().toArray(new String[0])); scanner.addDefaultExcludes(); scanner.scan(); String[] files = scanner.getIncludedFiles(); for (String path : files) { addSourceWithPath(airPackager, set.getDirectory(), path); } } } if (classifier != null) { projectHelper.attachArtifact(project, project.getArtifact().getType(), classifier, output); } else if (SWF.equals(packaging)) { projectHelper.attachArtifact(project, AIR, output); } else { project.getArtifact().setFile(output); } final List<Message> messages = new ArrayList<Message>(); airPackager.setListener(new Listener() { public void message(final Message message) { messages.add(message); } public void progress(final int soFar, final int total) { getLog().info(" completed " + soFar + " of " + total); } }); airPackager.createAIR(); if (messages.size() > 0) { for (final Message message : messages) { getLog().error(" " + message.errorDescription); } throw new MojoExecutionException("Error creating AIR application"); } else { getLog().info(" AIR package created: " + output.getAbsolutePath()); } } catch (MojoExecutionException e) { // do not handle throw e; } catch (Exception e) { throw new MojoExecutionException("Error invoking AIR api", e); } finally { airPackager.close(); } }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
@Override public String generateNodePKCS10CertificateRequestString() throws CertificateException { KeyStore keyStore = loadKeyStore(); Key key;//from ww w . j a v a 2 s. c o m try { key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray()); } catch (UnrecoverableKeyException e) { throw new CertificateException("Error opening node private key", e); } catch (KeyStoreException e) { throw new CertificateException("Error opening node private key", e); } catch (NoSuchAlgorithmException e) { throw new CertificateException("Error opening node private key", e); } assert key instanceof PrivateKey; Certificate cert; try { cert = keyStore.getCertificate(nodeAlias); } catch (KeyStoreException e) { throw new CertificateException("Error opening node certificate", e); } assert cert instanceof X509Certificate; return certificateService.generatePKCS10CertificateRequestString((X509Certificate) cert, (PrivateKey) key); }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
@Override public String generateNodePKCS7CertificateString() throws CertificateException { KeyStore keyStore = loadKeyStore(); Key key;//from w w w . j ava 2 s . c om try { key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray()); } catch (UnrecoverableKeyException e) { throw new CertificateException("Error opening node private key", e); } catch (KeyStoreException e) { throw new CertificateException("Error opening node private key", e); } catch (NoSuchAlgorithmException e) { throw new CertificateException("Error opening node private key", e); } assert key instanceof PrivateKey; Certificate cert; try { cert = keyStore.getCertificate(nodeAlias); } catch (KeyStoreException e) { throw new CertificateException("Error opening node certificate", e); } assert cert instanceof X509Certificate; return certificateService .generatePKCS7CertificateChainString(new X509Certificate[] { (X509Certificate) cert }); }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
@Override public void saveNodeSignedCertificate(String pem) throws CertificateException { KeyStore keyStore = loadKeyStore(); Key key;// w ww .ja v a 2s .co m try { key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray()); } catch (UnrecoverableKeyException e) { throw new CertificateException("Error opening node private key", e); } catch (KeyStoreException e) { throw new CertificateException("Error opening node private key", e); } catch (NoSuchAlgorithmException e) { throw new CertificateException("Error opening node private key", e); } X509Certificate nodeCert = getNodeCertificate(keyStore); if (nodeCert == null) { throw new CertificateException( "The node does not have a private key, start the association process over."); } X509Certificate[] chain = certificateService.parsePKCS7CertificateChainString(pem); saveNodeCertificateChain(keyStore, key, getKeyStorePassword(), nodeCert, chain); saveKeyStore(keyStore); }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
@Override public String generateNodePKCS7CertificateChainString() throws CertificateException { KeyStore keyStore = loadKeyStore(); Key key;//from www .j a v a 2 s. c om try { key = keyStore.getKey(nodeAlias, getKeyStorePassword().toCharArray()); } catch (UnrecoverableKeyException e) { throw new CertificateException("Error opening node private key", e); } catch (KeyStoreException e) { throw new CertificateException("Error opening node private key", e); } catch (NoSuchAlgorithmException e) { throw new CertificateException("Error opening node private key", e); } assert key instanceof PrivateKey; Certificate[] chain; try { chain = keyStore.getCertificateChain(nodeAlias); } catch (KeyStoreException e) { throw new CertificateException("Error opening node certificate", e); } X509Certificate[] x509Chain = new X509Certificate[chain.length]; for (int i = 0; i < chain.length; i++) { assert chain[i] instanceof X509Certificate; x509Chain[i] = (X509Certificate) chain[i]; } return certificateService.generatePKCS7CertificateChainString(x509Chain); }
From source file:com.google.samples.apps.abelana.AbelanaThings.java
public AbelanaThings(Context ctx, String phint) { final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); final HttpTransport httpTransport = new NetHttpTransport(); Resources r = ctx.getResources(); byte[] android, server; byte[] password = new byte[32]; android = Base64.decode("vW7CmbQWdPjpdfpBU39URsjHQV50KEKoSfafHdQPSh8", Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP); server = Base64.decode(phint, Base64.URL_SAFE); int i = 0;//from w w w. ja v a2 s . co m for (byte b : android) { password[i] = (byte) (android[i] ^ server[i]); i++; } byte[] pw = Base64.encode(password, Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP); String pass = new String(pw); if (storage == null) { try { KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(r.openRawResource(R.raw.abelananew), pass.toCharArray()); credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory) .setServiceAccountId(r.getString(R.string.service_account)) .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL)) .setServiceAccountPrivateKey((PrivateKey) keystore.getKey("privatekey", pass.toCharArray())) .build(); storage = new Storage.Builder(httpTransport, jsonFactory, credential) .setApplicationName(r.getString(R.string.app_name) + "/1.0").build(); } catch (CertificateException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("loaded"); } }