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.vmware.identity.idm.server.ClientCertTestUtils.java
public PrivateKey getTenantCredentialCustomPrivateKey(String keyAlias) throws Exception { Properties props = getTestProperties(); KeyStore ks = loadKeyStore(props.getProperty(CUSTOM_STORE_JKS), props.getProperty(CUSTOM_STORE_PASS)); return (PrivateKey) ks.getKey(keyAlias, props.getProperty(CUSTOM_KEY_PASS).toCharArray()); }
From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java
/** * Tries to encrypt some data with the generated key in {@link #createKey} which is * only works if the user has just authenticated via device credentials. *//* w w w. j a v a 2s .c o m*/ private boolean tryEncrypt() { try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null); Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); // Try encrypting something, it will only work if the user authenticated within // the last AUTHENTICATION_DURATION_SECONDS seconds. cipher.init(Cipher.ENCRYPT_MODE, secretKey); cipher.doFinal(SECRET_BYTE_ARRAY); // If the user has recently authenticated, you will reach here. showAlreadyAuthenticated(); return true; } catch (UserNotAuthenticatedException e) { // User is not authenticated, let's authenticate with device credentials. showAuthenticationScreen(); return false; } catch (KeyPermanentlyInvalidatedException e) { // This happens if the lock screen has been disabled or reset after the key was // generated after the key was generated. Toast.makeText(this, "Keys are invalidated after created. Retry the purchase\n" + e.getMessage(), Toast.LENGTH_LONG).show(); return false; } catch (BadPaddingException | IllegalBlockSizeException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } }
From source file:org.talend.components.common.oauth.X509Key.java
private X509Key(Builder b) { try (InputStream keyStoreIS = new FileInputStream(b.keyStorePath)) { KeyStore keystore = KeyStore.getInstance(storeTypeKJS); keystore.load(keyStoreIS, b.keyStorePassword.toCharArray()); this.privateKey = (PrivateKey) keystore.getKey(b.certificateAlias, b.keyStorePassword.toCharArray()); this.publicKey = (X509Certificate) keystore.getCertificate(b.certificateAlias); if (privateKey == null || publicKey == null) { throw new RuntimeException( messages.getMessage("msg.err.notFoundCert", b.certificateAlias, b.keyStorePath)); }/*from w w w . j a va 2s .c om*/ } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException e) { throw new RuntimeException(e); } }
From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java
/** * Get the cipher for the key protecting the saved password for a file *//* w w w . j ava2 s . co m*/ @TargetApi(Build.VERSION_CODES.M) private Cipher getKeyCipher(Uri fileUri, boolean encrypt) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { String keyName = getPrefsKey(fileUri); KeyStore keystore = getKeystore(); Key key = keystore.getKey(keyName, null); if (key == null) { throw new IOException(itsContext.getString(R.string.key_not_found, fileUri)); } Cipher ciph = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); if (encrypt) { ciph.init(Cipher.ENCRYPT_MODE, key); } else { SharedPreferences prefs = getPrefs(); String ivStr = prefs.getString(getIvPrefsKey(keyName), null); if (TextUtils.isEmpty(ivStr)) { throw new IOException("Key IV not found for " + fileUri); } byte[] iv = Base64.decode(ivStr, Base64.NO_WRAP); ciph.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); } return ciph; }
From source file:org.wso2.identity.integration.common.clients.sso.saml.query.ClientSignKeyDataHolder.java
/** * Constructor method/*from w w w . j ava2s . c om*/ * @param keyStorePath path to the key store * @param password password of keystore * @param keyAlias key alias of keystore * @throws Exception if, Algorithm fails, input stream fails */ public ClientSignKeyDataHolder(String keyStorePath, String password, String keyAlias) throws Exception { Certificate[] certificates; InputStream is = null; try { File file = new File(keyStorePath); is = new FileInputStream(file); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, password.toCharArray()); privateKey = (PrivateKey) keystore.getKey(keyAlias, password.toCharArray()); certificates = keystore.getCertificateChain(keyAlias); issuerCerts = new X509Certificate[certificates.length]; int i = 0; for (Certificate certificate : certificates) { issuerCerts[i++] = (X509Certificate) certificate; } signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_RSA; publicKey = issuerCerts[0].getPublicKey(); String pubKeyAlgo = publicKey.getAlgorithm(); if (DSA_ENCRYPTION_ALGORITHM.equalsIgnoreCase(pubKeyAlgo)) { signatureAlgorithm = XMLSignature.ALGO_ID_SIGNATURE_DSA; } } catch (CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | IOException e) { String mgs = "Error while initializing credentials"; log.error(mgs, e); throw new Exception(mgs); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error("Unable to close input stream", e); } } } }
From source file:org.wso2.carbon.appfactory.git.AppFactoryRepositoryAuthorizationClient.java
private String getSignedAuthHeader(String username) throws AppFactoryException { try {/*from w w w . j a va 2 s . c om*/ //Get the default primary certificate of the keystore String keystoreName = gitBlitConfiguration.getProperty(GitBlitConstants.APPFACTORY_KEY_STORE_LOCATION, GitBlitConstants.APPFACTORY_KEY_STORE_DEFAULT_LOCATION); String keystoreCredential = gitBlitConfiguration.getProperty( GitBlitConstants.APPFACTORY_KEY_STORE_PASSWORD, GitBlitConstants.APPFACTORY_KEY_STORE_DEFAULT_PASSWORD); KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(new FileInputStream(keystoreName), keystoreCredential.toCharArray()); PrivateKey key = (PrivateKey) keyStore.getKey(keystoreCredential, keystoreCredential.toCharArray()); JWSSigner signer = new RSASSASigner((RSAPrivateKey) key); JWTClaimsSet claimsSet = new JWTClaimsSet(); claimsSet.setClaim(AppFactoryConstants.SIGNED_JWT_AUTH_USERNAME, username); SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS512), claimsSet); signedJWT.sign(signer); // generate authorization header value return "Bearer " + Base64Utils.encode(signedJWT.serialize().getBytes()); } catch (Exception e) { String msg = "Failed to get primary default certificate"; log.error(msg, e); throw new AppFactoryException(msg, e); } }
From source file:Manifest.java
/** * This method creates a manifest file with the specified name, for the * specified vector of files, using the named message digest algorithm. If * signername is non-null, it adds a digital signature to the manifest, * using the named signature algorithm. This method can throw a bunch of * exceptions./*from www . j a va 2s.c o m*/ */ public static void create(String manifestfile, String digestAlgorithm, String signername, String signatureAlgorithm, KeyStore keystore, String password, List filelist) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException, UnrecoverableKeyException, IOException { // For computing a signature, we have to process the files in a fixed, // repeatable order, so sort them alphabetically. Collections.sort(filelist); int numfiles = filelist.size(); Properties manifest = new Properties(), metadata = new Properties(); MessageDigest md = MessageDigest.getInstance(digestAlgorithm); Signature signature = null; byte[] digest; // If a signer name was specified, then prepare to sign the manifest if (signername != null) { // Get a Signature object signature = Signature.getInstance(signatureAlgorithm); // Look up the private key of the signer from the keystore PrivateKey key = (PrivateKey) keystore.getKey(signername, password.toCharArray()); // No prepare to create a signature for the specified signer signature.initSign(key); } // Now, loop through the files, in a well-known alphabetical order System.out.print("Computing message digests"); for (int i = 0; i < numfiles; i++) { String filename = (String) filelist.get(i); // Compute the digest for each, and skip files that don't exist. try { digest = getFileDigest(filename, md); } catch (IOException e) { System.err.println("\nSkipping " + filename + ": " + e); continue; } // If we're computing a signature, use the bytes of the filename // and of the digest as part of the data to sign. if (signature != null) { signature.update(filename.getBytes()); signature.update(digest); } // Store the filename and the encoded digest bytes in the manifest manifest.put(filename, hexEncode(digest)); System.out.print('.'); System.out.flush(); } // If a signer was specified, compute signature for the manifest byte[] signaturebytes = null; if (signature != null) { System.out.print("done\nComputing digital signature..."); System.out.flush(); // Compute the digital signature by encrypting a message digest of // all the bytes passed to the update() method using the private // key of the signer. This is a time consuming operation. signaturebytes = signature.sign(); } // Tell the user what comes next System.out.print("done\nWriting manifest..."); System.out.flush(); // Store some metadata about this manifest, including the name of the // message digest algorithm it uses metadata.put("__META.DIGESTALGORITHM", digestAlgorithm); // If we're signing the manifest, store some more metadata if (signername != null) { // Store the name of the signer metadata.put("__META.SIGNER", signername); // Store the name of the algorithm metadata.put("__META.SIGNATUREALGORITHM", signatureAlgorithm); // And generate the signature, encode it, and store it metadata.put("__META.SIGNATURE", hexEncode(signaturebytes)); } // Now, save the manifest data and the metadata to the manifest file FileOutputStream f = new FileOutputStream(manifestfile); manifest.store(f, "Manifest message digests"); metadata.store(f, "Manifest metadata"); System.out.println("done"); }
From source file:org.apache.hadoop.gateway.services.security.impl.BaseKeystoreService.java
protected char[] getCredential(String alias, char[] credential, KeyStore ks) { if (ks != null) { try {/* w w w . j ava 2s . c o m*/ credential = new String(ks.getKey(alias, masterService.getMasterSecret()).getEncoded()) .toCharArray(); } catch (UnrecoverableKeyException e) { LOG.failedToGetCredential(e); } catch (KeyStoreException e) { LOG.failedToGetCredential(e); } catch (NoSuchAlgorithmException e) { LOG.failedToGetCredential(e); } } return credential; }
From source file:com.gnut3ll4.android.basicandroidkeystore.MainActivity.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.edittext); button = (Button) findViewById(R.id.button); mKeyStoreHelper = new KeyStoreHelper(); mKeyStoreHelper.setAlias(ALIAS);/*from w ww . j av a 2 s .c o m*/ initializeLogging(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { //Encrypt KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); Key key = ks.getKey(ALIAS, null); if (key instanceof PrivateKey) { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); cipher.init(Cipher.ENCRYPT_MODE, ks.getCertificate(ALIAS).getPublicKey()); encryptedBytes = cipher.doFinal(editText.getText().toString().getBytes()); Log.d(TAG, "Encrypted bytes : " + Base64.encodeToString(encryptedBytes, Base64.DEFAULT)); } //Decrypt PrivateKey privateKey = loadPrivateKey(ALIAS); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytes = cipher.doFinal(encryptedBytes); Log.d(TAG, "Decrypted string : " + new String(bytes, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:org.apache.james.jmap.crypto.JamesSignatureHandler.java
@Override public void init() throws Exception { KeyStore keystore = KeyStore.getInstance(JKS); InputStream fis = fileSystem.getResource(jmapConfiguration.getKeystore()); keystore.load(fis, jmapConfiguration.getSecret().toCharArray()); publicKey = keystore.getCertificate(ALIAS).getPublicKey(); Key key = keystore.getKey(ALIAS, jmapConfiguration.getSecret().toCharArray()); if (!(key instanceof PrivateKey)) { throw new Exception("Provided key is not a PrivateKey"); }//from w ww . j a v a2s . c o m privateKey = (PrivateKey) key; }