List of usage examples for java.security KeyStore getKey
public final Key getKey(String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
From source file:com.vimukti.accounter.license.LicenseManager.java
private PrivateKey getPrivateKey() { Key key = null;//from w ww . j a va 2 s .c om try { FileInputStream is = new FileInputStream( ServerConfiguration.getConfig() + File.separator + "license.keystore"); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); String password = ServerConfiguration.getLicenseKeystorePWD(); keystore.load(is, password.toCharArray()); key = keystore.getKey(ServerConfiguration.getLicenseAlias(), password.toCharArray()); } catch (NoSuchAlgorithmException e) { throw new LicenseException(e); } catch (CertificateException e) { throw new LicenseException(e); } catch (IOException e) { throw new LicenseException(e); } catch (UnrecoverableKeyException e) { throw new LicenseException(e); } catch (KeyStoreException e) { throw new LicenseException(e); } return (PrivateKey) key; }
From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java
@Test public void testSignAuthnCertCredential() throws Exception { LOG.debug("sign"); // operate//from w w w . jav a 2 s . c o m Security.addProvider(new BeIDProvider()); KeyStore beidKeyStore = KeyStore.getInstance("BeID"); beidKeyStore.load(null); X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication"); PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null); Security.addProvider(new HSMProxyProvider()); KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy"); HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert, "https://www.e-contract.be/hsm-proxy-ws/dss", // "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit()); keyStoreParameter.setProxy("proxy.yourict.net", 8080); hsmProxyKeyStore.load(keyStoreParameter); PrivateKey hsmPrivateKey = (PrivateKey) hsmProxyKeyStore.getKey("alias", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(hsmPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); }
From source file:org.kse.gui.actions.SignCsrAction.java
/** * Do action.//w w w. j a v a 2s. c om */ @Override protected void doAction() { FileOutputStream fos = null; File caReplyFile = null; try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); String alias = kseFrame.getSelectedEntryAlias(); Password password = getEntryPassword(alias, currentState); if (password == null) { return; } KeyStore keyStore = currentState.getKeyStore(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); Certificate[] certs = keyStore.getCertificateChain(alias); KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey); File csrFile = chooseCsrFile(); if (csrFile == null) { return; } PKCS10CertificationRequest pkcs10Csr = null; Spkac spkacCsr = null; try { CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile)); if (fileType == CryptoFileType.PKCS10_CSR) { pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile)); if (!Pkcs10Util.verifyCsr(pkcs10Csr)) { JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } else if (fileType == CryptoFileType.SPKAC_CSR) { spkacCsr = new Spkac(new FileInputStream(csrFile)); if (!spkacCsr.verify()) { JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.NoVerifySpkacCsr.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } else { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignCsrAction.FileNotRecognisedType.message"), csrFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } catch (Exception ex) { String problemStr = MessageFormat.format(res.getString("SignCsrAction.NoOpenCsr.Problem"), csrFile.getName()); String[] causes = new String[] { res.getString("SignCsrAction.NotCsr.Cause"), res.getString("SignCsrAction.CorruptedCsr.Cause") }; Problem problem = new Problem(problemStr, causes, ex); DProblem dProblem = new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"), problem); dProblem.setLocationRelativeTo(frame); dProblem.setVisible(true); return; } X509Certificate[] signingChain = X509CertUtil .orderX509CertChain(X509CertUtil.convertCertificates(certs)); X509Certificate signingCert = signingChain[0]; PublicKey publicKey = null; X500Name subject = null; DSignCsr dSignCsr = null; Provider provider = history.getExplicitProvider(); if (pkcs10Csr != null) { publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey(); subject = pkcs10Csr.getSubject(); dSignCsr = new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider); } else { publicKey = spkacCsr.getPublicKey(); subject = spkacCsr.getSubject().getName(); dSignCsr = new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider); } dSignCsr.setLocationRelativeTo(frame); dSignCsr.setVisible(true); X509CertificateVersion version = dSignCsr.getVersion(); SignatureType signatureType = dSignCsr.getSignatureType(); Date validityStart = dSignCsr.getValidityStart(); Date validityEnd = dSignCsr.getValidityEnd(); BigInteger serialNumber = dSignCsr.getSerialNumber(); caReplyFile = dSignCsr.getCaReplyFile(); X509ExtensionSet extensions = dSignCsr.getExtensions(); if (version == null) { return; } X500Name issuer = X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal()); // CA Reply is a cert with subject from CSR and issuer from signing cert's subject X509CertificateGenerator generator = new X509CertificateGenerator(version); X509Certificate caReplyCert = generator.generate(subject, issuer, validityStart, validityEnd, publicKey, privateKey, signatureType, serialNumber, extensions, provider); X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1]; caReplyChain[0] = caReplyCert; // Add all of the signing chain to the reply System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length); byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain); fos = new FileOutputStream(caReplyFile); fos.write(caCertEncoded); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } catch (Exception ex) { DError.displayError(frame, ex); return; } finally { IOUtils.closeQuietly(fos); } JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.SignCsrSuccessful.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.INFORMATION_MESSAGE); }
From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java
@Test public void testGetCertificateAuthnCertCredential() throws Exception { LOG.debug("sign"); // operate//from w w w .j a v a 2 s . c o m Security.addProvider(new BeIDProvider()); KeyStore beidKeyStore = KeyStore.getInstance("BeID"); beidKeyStore.load(null); X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication"); PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null); Security.addProvider(new HSMProxyProvider()); KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy"); HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert, // "https://www.e-contract.be/hsm-proxy-ws/dss", "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit()); hsmProxyKeyStore.load(keyStoreParameter); Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases(); assertNotNull(aliasesEnum); while (aliasesEnum.hasMoreElements()) { String alias = aliasesEnum.nextElement(); LOG.debug("alias: " + alias); X509Certificate certificate = (X509Certificate) hsmProxyKeyStore.getCertificate(alias); assertNotNull(certificate); LOG.debug("certificate: " + certificate); assertTrue(hsmProxyKeyStore.containsAlias(alias)); Certificate[] certificateChain = hsmProxyKeyStore.getCertificateChain(alias); assertNotNull(certificateChain); PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) hsmProxyKeyStore.getEntry(alias, null); assertNotNull(privateKeyEntry); } }
From source file:org.taverna.server.master.localworker.SecurityContextDelegateImpl.java
/** * Tests whether the given key-pair credential descriptor is valid. If it is * invalid, an exception will be thrown describing what the problem is. * // w w w . j ava 2 s . co m * @param keypairDescriptor * The descriptor to validate. * @throws InvalidCredentialException * If the descriptor is invalid * @throws KeyStoreException * If we don't understand the keystore type or the contents of * the keystore * @throws NoSuchAlgorithmException * If the keystore is of a known type but we can't comprehend * its security * @throws CertificateException * If the keystore does not include enough information about the * trust chain of the keypair * @throws UnrecoverableKeyException * If we can't get the key out of the keystore * @throws IOException * If we can't read the keystore for prosaic reasons (e.g., file * absent) */ protected void validateKeyCredential(Credential.KeyPair keypairDescriptor) throws InvalidCredentialException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { if (keypairDescriptor.credentialName == null || keypairDescriptor.credentialName.trim().isEmpty()) throw new InvalidCredentialException("absent or empty credentialName"); InputStream contentsAsStream; if (keypairDescriptor.credentialBytes != null && keypairDescriptor.credentialBytes.length > 0) { contentsAsStream = new ByteArrayInputStream(keypairDescriptor.credentialBytes); keypairDescriptor.credentialFile = null; } else if (keypairDescriptor.credentialFile == null || keypairDescriptor.credentialFile.trim().isEmpty()) throw new InvalidCredentialException("absent or empty credentialFile"); else { contentsAsStream = contents(keypairDescriptor.credentialFile); keypairDescriptor.credentialBytes = new byte[0]; } if (keypairDescriptor.fileType == null || keypairDescriptor.fileType.trim().isEmpty()) keypairDescriptor.fileType = KeyStore.getDefaultType(); keypairDescriptor.fileType = keypairDescriptor.fileType.trim(); KeyStore ks = KeyStore.getInstance(keypairDescriptor.fileType); char[] password = keypairDescriptor.unlockPassword.toCharArray(); ks.load(contentsAsStream, password); try { keypairDescriptor.loadedKey = ks.getKey(keypairDescriptor.credentialName, password); } catch (UnrecoverableKeyException ignored) { keypairDescriptor.loadedKey = ks.getKey(keypairDescriptor.credentialName, new char[0]); } if (keypairDescriptor.loadedKey == null) throw new InvalidCredentialException("no such credential in key store"); keypairDescriptor.loadedTrustChain = ks.getCertificateChain(keypairDescriptor.credentialName); if (keypairDescriptor.loadedTrustChain == null || keypairDescriptor.loadedTrustChain.length == 0) throw new InvalidCredentialException("could not establish trust chain for credential"); }
From source file:com.zacwolf.commons.crypto.Crypter_AES.java
/** * @param keyStore//from w w w. j av a2 s. com * @param keystorepass * @param alias * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public Crypter_AES(final KeyStore keyStore, final String keystorepass, final String alias) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { this(keyStore.getKey(alias, keystorepass.toCharArray()).getEncoded()); }
From source file:com.zacwolf.commons.crypto.Crypter_AES.java
/** * @param keyStore//from ww w . j ava 2s .c o m * @param keystorepass * @param alias * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public Crypter_AES(final KeyStore keyStore, final char[] keystorepass, final String alias) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { this(keyStore.getKey(alias, keystorepass).getEncoded()); }
From source file:com.zacwolf.commons.crypto.Crypter_Blowfish.java
/** * @param keyStore//www .j av a2 s .c o m * @param keystorepass * @param alias * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public Crypter_Blowfish(final KeyStore keyStore, final String keystorepass, final String alias) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { this(keyStore.getKey(alias, keystorepass.toCharArray()).getEncoded()); }
From source file:com.zacwolf.commons.crypto.Crypter_Blowfish.java
/** * @param keyStore/*w ww . j av a 2s .c om*/ * @param keystorepass * @param alias * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public Crypter_Blowfish(final KeyStore keyStore, final char[] keystorepass, final String alias) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { this(keyStore.getKey(alias, keystorepass).getEncoded()); }
From source file:com.netscape.cmstools.pkcs11.PKCS11KeyFindCLI.java
public void execute(String[] args) throws Exception { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { printHelp();//from w w w. jav a2 s . c o m return; } if (cmd.hasOption("verbose")) { PKILogger.setLevel(PKILogger.Level.INFO); } else if (cmd.hasOption("debug")) { PKILogger.setLevel(PKILogger.Level.DEBUG); } String tokenName = getConfig().getTokenName(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); KeyStore ks = KeyStore.getInstance("pkcs11"); ks.load(new JSSLoadStoreParameter(token)); Enumeration<String> aliases = ks.aliases(); boolean first = true; while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (ks.isCertificateEntry(alias)) { continue; } Key key = ks.getKey(alias, null); if (key == null) { continue; } if (first) { first = false; } else { System.out.println(); } PKCS11KeyCLI.printKeyInfo(alias, key); } }