List of usage examples for java.security KeyStore getEntry
public final Entry getEntry(String alias, ProtectionParameter protParam) throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException
From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Given some data and a signature, uses the key pair stored in the Android Key Store to verify * that the data was signed by this application, using that key pair. * @param input The data to be verified. * @param signatureStr The signature provided for the data. * @return A boolean value telling you whether the signature is valid or not. *//*from w ww . ja va 2 s. c om*/ public boolean verifyData(String input, String signatureStr) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException, InvalidKeyException, SignatureException { byte[] data = input.getBytes(); byte[] signature; // BEGIN_INCLUDE(decode_signature) // Make sure the signature string exists. If not, bail out, nothing to do. if (signatureStr == null) { Log.w(TAG, "Invalid signature."); Log.w(TAG, "Exiting verifyData()..."); return false; } try { // The signature is going to be examined as a byte array, // not as a base64 encoded string. signature = Base64.decode(signatureStr, Base64.DEFAULT); } catch (IllegalArgumentException e) { // signatureStr wasn't null, but might not have been encoded properly. // It's not a valid Base64 string. return false; } // END_INCLUDE(decode_signature) KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); // Weird artifact of Java API. If you don't have an InputStream to load, you still need // to call "load", or it'll crash. ks.load(null); // Load the key pair from the Android Key Store KeyStore.Entry entry = ks.getEntry(mAlias, null); if (entry == null) { Log.w(TAG, "No key found under alias: " + mAlias); Log.w(TAG, "Exiting verifyData()..."); return false; } if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); return false; } // This class doesn't actually represent the signature, // just the engine for creating/verifying signatures, using // the specified algorithm. Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA); // BEGIN_INCLUDE(verify_data) // Verify the data. s.initVerify(((KeyStore.PrivateKeyEntry) entry).getCertificate()); s.update(data); return s.verify(signature); // END_INCLUDE(verify_data) }
From source file:be.fedict.hsm.model.KeyStoreLoaderBean.java
private Map<String, PrivateKeyEntry> loadKeys(KeyStoreEntity keyStoreEntity, KeyStore keyStore, String keyStorePassword)/* w ww .j a v a 2 s . c om*/ throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException { Enumeration<String> aliases = keyStore.aliases(); Map<String, PrivateKeyEntry> keyStorePrivateKeys = new HashMap<String, PrivateKeyEntry>(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); PrivateKeyEntry privateKeyEntry; if (null != keyStorePassword) { privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyStorePassword.toCharArray())); } else { privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias, null); } keyStorePrivateKeys.put(alias, privateKeyEntry); } return keyStorePrivateKeys; }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testGetEntry() throws Exception { Security.addProvider(new BeIDProvider()); final KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);//from w ww.j a va 2s .co m PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null); assertNotNull(privateKeyEntry); assertTrue(privateKeyEntry.getPrivateKey() instanceof BeIDPrivateKey); TrustedCertificateEntry caEntry = (TrustedCertificateEntry) keyStore.getEntry("CA", null); assertNotNull(caEntry); LOG.debug("CA entry: " + ((X509Certificate) caEntry.getTrustedCertificate()).getSubjectX500Principal()); TrustedCertificateEntry rootEntry = (TrustedCertificateEntry) keyStore.getEntry("Root", null); assertNotNull(rootEntry); LOG.debug("root entry: " + ((X509Certificate) rootEntry.getTrustedCertificate()).getSubjectX500Principal()); }
From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Signs the data using the key pair stored in the Android Key Store. This signature can be * used with the data later to verify it was signed by this application. * @return A string encoding of the data signature generated *///from w ww . j a v a 2s . c o m public String signData(String inputStr) throws KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException, CertificateException { byte[] data = inputStr.getBytes(); // BEGIN_INCLUDE(sign_load_keystore) KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); // Weird artifact of Java API. If you don't have an InputStream to load, you still need // to call "load", or it'll crash. ks.load(null); // Load the key pair from the Android Key Store KeyStore.Entry entry = ks.getEntry(mAlias, null); /* If the entry is null, keys were never stored under this alias. * Debug steps in this situation would be: * -Check the list of aliases by iterating over Keystore.aliases(), be sure the alias * exists. * -If that's empty, verify they were both stored and pulled from the same keystore * "AndroidKeyStore" */ if (entry == null) { Log.w(TAG, "No key found under alias: " + mAlias); Log.w(TAG, "Exiting signData()..."); return null; } /* If entry is not a KeyStore.PrivateKeyEntry, it might have gotten stored in a previous * iteration of your application that was using some other mechanism, or been overwritten * by something else using the same keystore with the same alias. * You can determine the type using entry.getClass() and debug from there. */ if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); Log.w(TAG, "Exiting signData()..."); return null; } // END_INCLUDE(sign_data) // BEGIN_INCLUDE(sign_create_signature) // This class doesn't actually represent the signature, // just the engine for creating/verifying signatures, using // the specified algorithm. Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA); // Initialize Signature using specified private key s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); // Sign the data, store the result as a Base64 encoded String. s.update(data); byte[] signature = s.sign(); String result = Base64.encodeToString(signature, Base64.DEFAULT); // END_INCLUDE(sign_data) return result; }
From source file:org.asimba.wa.integrationtest.saml2.model.AuthnRequest.java
private KeyPair getKeyPairFromKeystore(KeyStore keystore, String keyAlias, String keyPassword) { try {//from ww w . j av a2s. c o m PasswordProtection passwordProtected = new PasswordProtection(keyPassword.toCharArray()); Entry keyEntry = keystore.getEntry(keyAlias, passwordProtected); if (!(keyEntry instanceof PrivateKeyEntry)) { // Invalid key entry return null; } PrivateKeyEntry pkEntry = (PrivateKeyEntry) keyEntry; return new KeyPair(pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey()); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) { // Problem occurred e.printStackTrace(); return null; } }
From source file:org.wso2.identity.integration.test.oidc.OIDCAuthzCodeIdTokenValidationTestCase.java
private void initServiceProviderKeys() throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); String jksPath = TestConfigurationProvider.getResourceLocation("IS") + File.separator + "sp" + File.separator + "keystores" + File.separator + "sp1KeyStore.jks"; String jksPassword = "wso2carbon"; keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray()); String alias = "wso2carbon"; KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(jksPassword.toCharArray())); spPrivateKey = (RSAPrivateKey) pkEntry.getPrivateKey(); // Load certificate chain Certificate[] chain = keyStore.getCertificateChain(alias); spX509PublicCert = (X509Certificate) chain[0]; }
From source file:org.apache.juddi.v3.tck.TckBusiness.java
private boolean verifySignedJAXBObject(Object obj) { try {//ww w .j a v a 2 s . c om DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); KeyStore ks = KeyStore.getInstance(SIGNATURE_KEYSTORE_TYPE); URL url = Thread.currentThread().getContextClassLoader().getResource(SIGNATURE_KEYSTORE); ks.load(url.openStream(), SIGNATURE_KEYSTORE_PASSWORD.toCharArray()); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(SIGNATURE_KEYSTORE_ALIAS, new KeyStore.PasswordProtection(SIGNATURE_KEYSTORE_PASSWORD.toCharArray())); PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); PublicKey validatingKey = origCert.getPublicKey(); return TckSigningUtil.verifySignature(docElement, validatingKey); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.wildfly.security.tool.VaultCommand.java
private CredentialSourceProtectionParameter getVaultCredentialStoreProtectionParameter(final String keyStoreURL, final String vaultPassword, final String salt, final int iterationCount, final String secretKeyAlias) throws GeneralSecurityException, IOException { char[] password = vaultPassword.startsWith("MASK-") ? decodeMaskedPassword(vaultPassword.substring("MASK-".length()), salt, iterationCount) : vaultPassword.toCharArray(); final KeyStore keyStore = KeyStore.getInstance(defaultKeyStoreType); try (FileInputStream in = new FileInputStream(new File(keyStoreURL))) { keyStore.load(in, password);//from w ww.ja va 2s .c o m } final KeyStore.Entry entry = keyStore.getEntry(secretKeyAlias, new KeyStore.PasswordProtection(password)); if (entry instanceof KeyStore.SecretKeyEntry) { return new CredentialSourceProtectionParameter(new CredentialSource() { @Override public SupportLevel getCredentialAcquireSupport(Class<? extends Credential> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { return null; } @Override public <C extends Credential> C getCredential(Class<C> credentialType, String algorithmName, AlgorithmParameterSpec parameterSpec) throws IOException { SecretKeyCredential credential = new SecretKeyCredential( ((KeyStore.SecretKeyEntry) entry).getSecretKey()); return credential.castAs(credentialType, algorithmName, parameterSpec); } }); } else { throw ElytronToolMessages.msg.cannotLocateAdminKey(secretKeyAlias); } }
From source file:mitm.common.tools.PfxTool.java
private void mergePfx() throws Exception { if (StringUtils.isEmpty(destFile)) { throw new MissingOptionException(destOption.getOpt() + " is missing."); }//from w ww . j a va2 s . c o m if (StringUtils.isEmpty(destPassword)) { throw new MissingOptionException(destPasswordOption.getOpt() + " is missing."); } KeyStore inStore = loadKeyStore(inFile, true, inPassword); KeyStore destStore = loadKeyStore(destFile, false, destPassword); Enumeration<String> aliases = inStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); String destAlias = retainAliases ? alias : UUID.randomUUID().toString() + "_" + alias; if (inStore.isKeyEntry(alias)) { KeyStore.Entry entry = inStore.getEntry(alias, new KeyStore.PasswordProtection(inPassword.toCharArray())); destStore.setEntry(destAlias, entry, new KeyStore.PasswordProtection(destPassword.toCharArray())); } else { Certificate certificate = inStore.getCertificate(alias); destStore.setCertificateEntry(destAlias, certificate); } } destStore.store(new FileOutputStream(destFile), destPassword.toCharArray()); }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testRRNCertificate() throws Exception { // setup//from w w w.ja v a 2 s. c o m Security.addProvider(new BeIDProvider()); final KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); // operate assertTrue(keyStore.containsAlias("RRN")); Entry entry = keyStore.getEntry("RRN", null); assertNotNull(entry); assertTrue(entry instanceof TrustedCertificateEntry); TrustedCertificateEntry trustedCertificateEntry = (TrustedCertificateEntry) entry; assertNotNull(trustedCertificateEntry.getTrustedCertificate()); assertTrue(((X509Certificate) trustedCertificateEntry.getTrustedCertificate()).getSubjectX500Principal() .toString().contains("RRN")); assertNotNull(keyStore.getCertificate("RRN")); Certificate[] certificateChain = keyStore.getCertificateChain("RRN"); assertNotNull(certificateChain); assertEquals(2, certificateChain.length); LOG.debug("RRN subject: " + ((X509Certificate) certificateChain[0]).getSubjectX500Principal()); LOG.debug("RRN issuer: " + ((X509Certificate) certificateChain[0]).getIssuerX500Principal()); LOG.debug("root subject: " + ((X509Certificate) certificateChain[1]).getSubjectX500Principal()); LOG.debug("root issuer: " + ((X509Certificate) certificateChain[1]).getIssuerX500Principal()); }