Java Code Examples for java.security.KeyStore#PasswordProtection

The following examples show how to use java.security.KeyStore#PasswordProtection . These examples are extracted from open source projects. 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
private KeyStore.ProtectionParameter getProtectionParameter(String password) {
    if (password != null && password.length() > 0) {
        // password provided: create a PasswordProtection
        return new KeyStore.PasswordProtection(password.toCharArray());
    } else {
        // request password at runtime through a callback
        return new KeyStore.CallbackHandlerProtection(callbacks -> {
            if (callbacks.length > 0 && callbacks[0] instanceof PasswordCallback) {
                if (Settings.getBooleanProperty("davmail.server") || GraphicsEnvironment.isHeadless()) {
                    // headless or server mode
                    System.out.print(((PasswordCallback) callbacks[0]).getPrompt() + ": ");
                    String password1 = new BufferedReader(new InputStreamReader(System.in)).readLine();
                    ((PasswordCallback) callbacks[0]).setPassword(password1.toCharArray());
                } else {
                    PasswordPromptDialog passwordPromptDialog = new PasswordPromptDialog(((PasswordCallback) callbacks[0]).getPrompt());
                    ((PasswordCallback) callbacks[0]).setPassword(passwordPromptDialog.getPassword());
                }
            }
        });
    }
}
 
Example 2
Source Project: j2objc   File: KSPasswordProtectionTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test for <code>KeyStore.PasswordProtection(char[] password, String protectionAlgorithm,
 * AlgorithmParameterSpec protectionParameters)</code> constructor
 * and the method <code>getProtectionAlgorithm()</code>

 * Assertions: constructor throws NullPointerException if protectionAlgorithm is null.
 * getProtectionAlgorithm() returns the protection algorithm passed in the constructor.
 */
public void testGetProtectionAlgorithm() throws DestroyFailedException {
    char [] pass = {'a', 'b', 'c'};
    String protectionAlgorithm = "ThisBeautifulAlgorithm";
    AlgorithmParameterSpec protectionParameters = new IvParameterSpec(new byte[]{});
    KeyStore.PasswordProtection ksPWP;
    try {
        ksPWP = new KeyStore.PasswordProtection(
                pass, null /* protectionAlgorithm */, protectionParameters);
        fail("Expected null pointer exception");
    } catch (NullPointerException expected) {
    }
    ksPWP = new KeyStore.PasswordProtection(
            pass, protectionAlgorithm, null /* protectionParameters */);
    assertSame(protectionAlgorithm, ksPWP.getProtectionAlgorithm());
}
 
Example 3
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
Example 4
private void run(String keystoreType) throws Exception {
    char[] pw = "password".toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(null, pw);

    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128);
    SecretKey key = kg.generateKey();

    KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);
    KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);
    ks.setEntry(ALIAS, ske, kspp);

    File ksFile = File.createTempFile("test", ".test");
    try (FileOutputStream fos = new FileOutputStream(ksFile)) {
        ks.store(fos, pw);
        fos.flush();
    }

    // now see if we can get it back
    try (FileInputStream fis = new FileInputStream(ksFile)) {
        KeyStore ks2 = KeyStore.getInstance(keystoreType);
        ks2.load(fis, pw);
        KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);
        SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();
        if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {
            System.err.println("OK: worked just fine with " + keystoreType +
                               " keystore");
        } else {
            System.err.println("ERROR: keys are NOT equal after storing in "
                               + keystoreType + " keystore");
        }
    }
}
 
Example 5
/**
 * creates a UpdateSigner
 * @throws Exception
 */
public UpdateSigner() throws Exception {
	Properties antProp = new Properties();
	InputStream is = UpdatePropUpdater.class.getClassLoader().getResourceAsStream("build.ant-private.properties");
	if (is == null) {
		throw new IOException("Loading build.ant-private.properties with parameters keystore.alias and keystore.password failed");
	}
	antProp.load(is);
	is.close();
	if ((antProp.getProperty("keystore.password") == null) || (antProp.getProperty("keystore.update-alias") == null)) {
		throw new IllegalArgumentException("build.ant-private.properties is missing parameters keystore.alias or keystore.password");
	}

	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

	// get user password and file input stream
	char[] password = antProp.getProperty("keystore.password").toCharArray();
	is = UpdatePropUpdater.class.getClassLoader().getResourceAsStream("keystore.ks");
	if (is == null) {
		throw new IOException("No keystore.ks in root folder.");
	}
	ks.load(is, password);
	is.close();

	// get my private key
	KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(password);
	KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(antProp.getProperty("keystore.update-alias"), protection);
	PrivateKey key = pkEntry.getPrivateKey();

	signer = Signature.getInstance("SHA1withRSA");
	signer.initSign(key);
}
 
Example 6
public synchronized KeyStore getAsKeyStore(File keyStore, char[] keyStorePass, String keyStoreType) throws AlertException {
    logger.debug("Get key store.");
    KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(keyStorePass);
    try {
        return KeyStore.Builder.newInstance(keyStoreType, null, keyStore, protection).getKeyStore();
    } catch (KeyStoreException e) {
        throw new AlertException("There was a problem accessing the trust store.", e);
    }
}
 
Example 7
Source Project: ripple-lib-java   File: PKCS12StoreParameter.java    License: ISC License 4 votes vote down vote up
public PKCS12StoreParameter(OutputStream out, char[] password, boolean forDEREncoding)
{
    super(out, new KeyStore.PasswordProtection(password), forDEREncoding);
}
 
Example 8
/**
 * Assigns the given key to the given alias, protecting it with the given
 * password.
 *
 * <p>If the given key is of type <code>java.security.PrivateKey</code>,
 * it must be accompanied by a certificate chain certifying the
 * corresponding public key.
 *
 * <p>If the given alias already exists, the keystore information
 * associated with it is overridden by the given key (and possibly
 * certificate chain).
 *
 * @param alias the alias name
 * @param key the key to be associated with the alias
 * @param password the password to protect the key
 * @param chain the certificate chain for the corresponding public
 * key (only required if the given key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if the given key cannot be protected, or
 * this operation fails for some other reason
 */
public synchronized void engineSetKeyEntry(String alias, Key key,
                    char[] password, Certificate[] chain)
    throws KeyStoreException
{
    KeyStore.PasswordProtection passwordProtection =
        new KeyStore.PasswordProtection(password);

    try {
        setKeyEntry(alias, key, passwordProtection, chain, null);

    } finally {
        try {
            passwordProtection.destroy();
        } catch (DestroyFailedException dfe) {
            // ignore
        }
    }
}
 
Example 9
/**
 * Assigns the given key to the given alias, protecting it with the given
 * password.
 *
 * <p>If the given key is of type <code>java.security.PrivateKey</code>,
 * it must be accompanied by a certificate chain certifying the
 * corresponding public key.
 *
 * <p>If the given alias already exists, the keystore information
 * associated with it is overridden by the given key (and possibly
 * certificate chain).
 *
 * @param alias the alias name
 * @param key the key to be associated with the alias
 * @param password the password to protect the key
 * @param chain the certificate chain for the corresponding public
 * key (only required if the given key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if the given key cannot be protected, or
 * this operation fails for some other reason
 */
public synchronized void engineSetKeyEntry(String alias, Key key,
                    char[] password, Certificate[] chain)
    throws KeyStoreException
{
    KeyStore.PasswordProtection passwordProtection =
        new KeyStore.PasswordProtection(password);

    try {
        setKeyEntry(alias, key, passwordProtection, chain, null);

    } finally {
        try {
            passwordProtection.destroy();
        } catch (DestroyFailedException dfe) {
            // ignore
        }
    }
}
 
Example 10
/**
 * Assigns the given key to the given alias, protecting it with the given
 * password.
 *
 * <p>If the given key is of type <code>java.security.PrivateKey</code>,
 * it must be accompanied by a certificate chain certifying the
 * corresponding public key.
 *
 * <p>If the given alias already exists, the keystore information
 * associated with it is overridden by the given key (and possibly
 * certificate chain).
 *
 * @param alias the alias name
 * @param key the key to be associated with the alias
 * @param password the password to protect the key
 * @param chain the certificate chain for the corresponding public
 * key (only required if the given key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if the given key cannot be protected, or
 * this operation fails for some other reason
 */
public synchronized void engineSetKeyEntry(String alias, Key key,
                    char[] password, Certificate[] chain)
    throws KeyStoreException
{
    KeyStore.PasswordProtection passwordProtection =
        new KeyStore.PasswordProtection(password);

    try {
        setKeyEntry(alias, key, passwordProtection, chain, null);

    } finally {
        try {
            passwordProtection.destroy();
        } catch (DestroyFailedException dfe) {
            // ignore
        }
    }
}
 
Example 11
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 12
/**
 * Gets a <code>KeyStore.Entry</code> for the specified alias
 * with the specified protection parameter.
 *
 * @param alias get the <code>KeyStore.Entry</code> for this alias
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @return the <code>KeyStore.Entry</code> for the specified alias,
 *          or <code>null</code> if there is no such entry
 *
 * @exception KeyStoreException if the operation failed
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 *          entry cannot be found
 * @exception UnrecoverableEntryException if the specified
 *          <code>protParam</code> were insufficient or invalid
 * @exception UnrecoverableKeyException if the entry is a
 *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
 *          and the specified <code>protParam</code> does not contain
 *          the information needed to recover the key (e.g. wrong password)
 *
 * @since 1.5
 */
@Override
public KeyStore.Entry engineGetEntry(String alias,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableEntryException {

    if (!engineContainsAlias(alias)) {
        return null;
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (protParam == null) {
        if (engineIsCertificateEntry(alias)) {
            if (entry instanceof CertEntry &&
                ((CertEntry) entry).trustedKeyUsage != null) {

                if (debug != null) {
                    debug.println("Retrieved a trusted certificate at " +
                        "alias '" + alias + "'");
                }

                return new KeyStore.TrustedCertificateEntry(
                    ((CertEntry)entry).cert, getAttributes(entry));
            }
        } else {
            throw new UnrecoverableKeyException
                    ("requested entry requires a password");
        }
    }

    if (protParam instanceof KeyStore.PasswordProtection) {
        if (engineIsCertificateEntry(alias)) {
            throw new UnsupportedOperationException
                ("trusted certificate entries are not password-protected");
        } else if (engineIsKeyEntry(alias)) {
            KeyStore.PasswordProtection pp =
                    (KeyStore.PasswordProtection)protParam;
            char[] password = pp.getPassword();

            Key key = engineGetKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate[] chain = engineGetCertificateChain(alias);

                return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                    getAttributes(entry));

            } else if (key instanceof SecretKey) {

                return new KeyStore.SecretKeyEntry((SecretKey)key,
                    getAttributes(entry));
            }
        } else if (!engineIsKeyEntry(alias)) {
            throw new UnsupportedOperationException
                ("untrusted certificate entries are not " +
                    "password-protected");
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 13
/**
 * Saves a <code>KeyStore.Entry</code> under the specified alias.
 * The specified protection parameter is used to protect the
 * <code>Entry</code>.
 *
 * <p> If an entry already exists for the specified alias,
 * it is overridden.
 *
 * @param alias save the <code>KeyStore.Entry</code> under this alias
 * @param entry the <code>Entry</code> to save
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @exception KeyStoreException if this operation fails
 *
 * @since 1.5
 */
@Override
public synchronized void engineSetEntry(String alias, KeyStore.Entry entry,
    KeyStore.ProtectionParameter protParam) throws KeyStoreException {

    // get password
    if (protParam != null &&
        !(protParam instanceof KeyStore.PasswordProtection)) {
        throw new KeyStoreException("unsupported protection parameter");
    }
    KeyStore.PasswordProtection pProtect = null;
    if (protParam != null) {
        pProtect = (KeyStore.PasswordProtection)protParam;
    }

    // set entry
    if (entry instanceof KeyStore.TrustedCertificateEntry) {
        if (protParam != null && pProtect.getPassword() != null) {
            // pre-1.5 style setCertificateEntry did not allow password
            throw new KeyStoreException
                ("trusted certificate entries are not password-protected");
        } else {
            KeyStore.TrustedCertificateEntry tce =
                    (KeyStore.TrustedCertificateEntry)entry;
            setCertEntry(alias, tce.getTrustedCertificate(),
                tce.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.PrivateKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create PrivateKeyEntry");
        } else {
            KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry)entry;
            setKeyEntry(alias, pke.getPrivateKey(), pProtect,
                pke.getCertificateChain(), pke.getAttributes());

            return;
        }
    } else if (entry instanceof KeyStore.SecretKeyEntry) {
        if (pProtect == null || pProtect.getPassword() == null) {
            // pre-1.5 style setKeyEntry required password
            throw new KeyStoreException
                ("non-null password required to create SecretKeyEntry");
        } else {
            KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry)entry;
            setKeyEntry(alias, ske.getSecretKey(), pProtect,
                (Certificate[])null, ske.getAttributes());

            return;
        }
    }

    throw new KeyStoreException
            ("unsupported entry type: " + entry.getClass().getName());
}
 
Example 14
public void setPassword(char[] password)
{
    this.protectionParameter = new KeyStore.PasswordProtection(password);
}
 
Example 15
public String createJWT(String username, Set<String> groups)
    throws GeneralSecurityException, IOException {
  // Create and Base64 encode the header portion of the JWT
  JsonObject headerObj =
      Json.createObjectBuilder()
          .add("alg", "RS256") /* Algorithm used */
          .add("typ", "JWT") /* Type of token */
          // .add("kid", "default") /* Hint about which key to use to sign, but the signature is
          // invalid when I include this. */
          .build();
  String headerEnc = Base64Utility.encode(headerObj.toString().getBytes(), true);

  // Create and Base64 encode the claims portion of the JWT
  JsonObject claimsObj =
      Json.createObjectBuilder()
          .add("exp", (System.currentTimeMillis() / 1000) + 300) /* Expire time */
          .add("iat", (System.currentTimeMillis() / 1000)) /* Issued time */
          .add("aud", "acmeGifts") /* Audience */
          .add("jti", Long.toHexString(System.nanoTime())) /* Unique value */
          .add("sub", username) /* Subject */
          .add("upn", username) /* Subject again */
          .add("iss", JWT_ISSUER) /* Issuer */
          .add("groups", getGroupArray(groups)) /* Group list */
          .build();
  String claimsEnc = Base64Utility.encode(claimsObj.toString().getBytes(), true);
  String headerClaimsEnc = headerEnc + "." + claimsEnc;

  // Open the keystore that the server will use to validate the JWT
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);

  // Get the private key to use to sign the JWT.  Normally we would not do this but
  // we are pretending to be the user service here.
  KeyStore.ProtectionParameter keyPassword = new KeyStore.PasswordProtection(password);
  KeyStore.PrivateKeyEntry privateKeyEntry =
      (KeyStore.PrivateKeyEntry) ks.getEntry("default", keyPassword);
  PrivateKey privateKey = privateKeyEntry.getPrivateKey();

  // Sign the JWT
  Signature sig = Signature.getInstance(JWT_ALGORITHM);
  sig.initSign(privateKey);
  sig.update(headerClaimsEnc.getBytes());
  String sigEnc = Base64Utility.encode(sig.sign(), true);

  // Lets just check......
  String jwtEnc = headerClaimsEnc + "." + sigEnc;
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();
  validateJWT("Bearer " + jwtEnc, publicKey);

  // Return the complete JWT (header, claims, signature).
  return jwtEnc;
}
 
Example 16
Source Project: opensoc-streaming   File: AuthToken.java    License: Apache License 2.0 4 votes vote down vote up
public static void main( String[] args ) throws Exception
{
	
   	Options options = new Options();
   	
   	options.addOption( "keystoreFile", true, "Keystore File" );
   	options.addOption( "keystorePassword", true, "Keystore Password" );
   	options.addOption( "authTokenAlias", true, "");
   	
   	CommandLineParser parser = new GnuParser();
   	CommandLine cmd = parser.parse( options, args);
	
	
	try
	{
		KeyStore ks = KeyStore.getInstance("JCEKS");

		String keystorePassword = cmd.getOptionValue("keystorePassword");
		String keystoreFile = cmd.getOptionValue("keystoreFile");
		String authTokenAlias = cmd.getOptionValue("authTokenAlias");

		ks.load(null, keystorePassword.toCharArray());

		
		// generate a key and store it in the keystore...
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		SecretKey key = keyGen.generateKey();
		
		KeyStore.ProtectionParameter protParam =
		        new KeyStore.PasswordProtection(keystorePassword.toCharArray());
		
		
		KeyStore.SecretKeyEntry skEntry =
		        new KeyStore.SecretKeyEntry(key);
		
		ks.setEntry(authTokenAlias, skEntry, protParam);
		
		java.io.FileOutputStream fos = null;
	    try {
	        
	    	fos = new java.io.FileOutputStream(keystoreFile);
	        ks.store(fos, keystorePassword.toCharArray());
	    } 
	    finally {
	        
	    	if (fos != null) {
	            fos.close();
	        }
	    }
		
	    
	    System.out.println( "done" );
	    
	}
	catch( Exception e )
	{
		e.printStackTrace();
	}
}
 
Example 17
/**
 * Gets a <code>KeyStore.Entry</code> for the specified alias
 * with the specified protection parameter.
 *
 * @param alias get the <code>KeyStore.Entry</code> for this alias
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @return the <code>KeyStore.Entry</code> for the specified alias,
 *          or <code>null</code> if there is no such entry
 *
 * @exception KeyStoreException if the operation failed
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 *          entry cannot be found
 * @exception UnrecoverableEntryException if the specified
 *          <code>protParam</code> were insufficient or invalid
 * @exception UnrecoverableKeyException if the entry is a
 *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
 *          and the specified <code>protParam</code> does not contain
 *          the information needed to recover the key (e.g. wrong password)
 *
 * @since 1.5
 */
@Override
public KeyStore.Entry engineGetEntry(String alias,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableEntryException {

    if (!engineContainsAlias(alias)) {
        return null;
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (protParam == null) {
        if (engineIsCertificateEntry(alias)) {
            if (entry instanceof CertEntry &&
                ((CertEntry) entry).trustedKeyUsage != null) {

                if (debug != null) {
                    debug.println("Retrieved a trusted certificate at " +
                        "alias '" + alias + "'");
                }

                return new KeyStore.TrustedCertificateEntry(
                    ((CertEntry)entry).cert, getAttributes(entry));
            }
        } else {
            throw new UnrecoverableKeyException
                    ("requested entry requires a password");
        }
    }

    if (protParam instanceof KeyStore.PasswordProtection) {
        if (engineIsCertificateEntry(alias)) {
            throw new UnsupportedOperationException
                ("trusted certificate entries are not password-protected");
        } else if (engineIsKeyEntry(alias)) {
            KeyStore.PasswordProtection pp =
                    (KeyStore.PasswordProtection)protParam;
            char[] password = pp.getPassword();

            Key key = engineGetKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate[] chain = engineGetCertificateChain(alias);

                return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                    getAttributes(entry));

            } else if (key instanceof SecretKey) {

                return new KeyStore.SecretKeyEntry((SecretKey)key,
                    getAttributes(entry));
            }
        } else if (!engineIsKeyEntry(alias)) {
            throw new UnsupportedOperationException
                ("untrusted certificate entries are not " +
                    "password-protected");
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 18
public static void writeSharedSecret(String keyStorePath,
                                     String keyStorePassword,
                                     byte[] sharedSecret) 
                                               throws Exception {
    char[] password = keyStorePassword.toCharArray();
    KeyStore ks;
    try {
        ks = readKeyStore(keyStorePath, password);
    } catch (FileNotFoundException e) {
        ks = KeyStore.getInstance("JCEKS");
        ks.load(null, password);
    } 

    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);
    SecretKeySpec signingKey = 
            new SecretKeySpec(sharedSecret, "HmacSHA1");
    KeyStore.SecretKeyEntry skEntry =
            new KeyStore.SecretKeyEntry(signingKey);
    ks.setEntry(CHALLENGE_RESPONSE_SECRET, skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    File keyStoreFile = new File(keyStorePath);
    File parent = keyStoreFile.getParentFile();
    if (parent != null)
        parent.mkdirs();
    try {
        fos = new java.io.FileOutputStream(keyStoreFile);
        ks.store(fos, password);
        keyStoreFile.setReadable(false, false);
        keyStoreFile.setReadable(true, true);
        keyStoreFile.setWritable(false, false);
        keyStoreFile.setWritable(true, true);
        keyStoreFile.setExecutable(false, false);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}
 
Example 19
/**
 * Gets a <code>KeyStore.Entry</code> for the specified alias
 * with the specified protection parameter.
 *
 * @param alias get the <code>KeyStore.Entry</code> for this alias
 * @param protParam the <code>ProtectionParameter</code>
 *          used to protect the <code>Entry</code>,
 *          which may be <code>null</code>
 *
 * @return the <code>KeyStore.Entry</code> for the specified alias,
 *          or <code>null</code> if there is no such entry
 *
 * @exception KeyStoreException if the operation failed
 * @exception NoSuchAlgorithmException if the algorithm for recovering the
 *          entry cannot be found
 * @exception UnrecoverableEntryException if the specified
 *          <code>protParam</code> were insufficient or invalid
 * @exception UnrecoverableKeyException if the entry is a
 *          <code>PrivateKeyEntry</code> or <code>SecretKeyEntry</code>
 *          and the specified <code>protParam</code> does not contain
 *          the information needed to recover the key (e.g. wrong password)
 *
 * @since 1.5
 */
@Override
public KeyStore.Entry engineGetEntry(String alias,
                    KeyStore.ProtectionParameter protParam)
            throws KeyStoreException, NoSuchAlgorithmException,
            UnrecoverableEntryException {

    if (!engineContainsAlias(alias)) {
        return null;
    }

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (protParam == null) {
        if (engineIsCertificateEntry(alias)) {
            if (entry instanceof CertEntry &&
                ((CertEntry) entry).trustedKeyUsage != null) {

                if (debug != null) {
                    debug.println("Retrieved a trusted certificate at " +
                        "alias '" + alias + "'");
                }

                return new KeyStore.TrustedCertificateEntry(
                    ((CertEntry)entry).cert, getAttributes(entry));
            }
        } else {
            throw new UnrecoverableKeyException
                    ("requested entry requires a password");
        }
    }

    if (protParam instanceof KeyStore.PasswordProtection) {
        if (engineIsCertificateEntry(alias)) {
            throw new UnsupportedOperationException
                ("trusted certificate entries are not password-protected");
        } else if (engineIsKeyEntry(alias)) {
            KeyStore.PasswordProtection pp =
                    (KeyStore.PasswordProtection)protParam;
            char[] password = pp.getPassword();

            Key key = engineGetKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate[] chain = engineGetCertificateChain(alias);

                return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain,
                    getAttributes(entry));

            } else if (key instanceof SecretKey) {

                return new KeyStore.SecretKeyEntry((SecretKey)key,
                    getAttributes(entry));
            }
        } else if (!engineIsKeyEntry(alias)) {
            throw new UnsupportedOperationException
                ("untrusted certificate entries are not " +
                    "password-protected");
        }
    }

    throw new UnsupportedOperationException();
}
 
Example 20
/**
 * Assigns the given key to the given alias, protecting it with the given
 * password.
 *
 * <p>If the given key is of type <code>java.security.PrivateKey</code>,
 * it must be accompanied by a certificate chain certifying the
 * corresponding public key.
 *
 * <p>If the given alias already exists, the keystore information
 * associated with it is overridden by the given key (and possibly
 * certificate chain).
 *
 * @param alias the alias name
 * @param key the key to be associated with the alias
 * @param password the password to protect the key
 * @param chain the certificate chain for the corresponding public
 * key (only required if the given key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if the given key cannot be protected, or
 * this operation fails for some other reason
 */
public synchronized void engineSetKeyEntry(String alias, Key key,
                    char[] password, Certificate[] chain)
    throws KeyStoreException
{
    KeyStore.PasswordProtection passwordProtection =
        new KeyStore.PasswordProtection(password);

    try {
        setKeyEntry(alias, key, passwordProtection, chain, null);

    } finally {
        try {
            passwordProtection.destroy();
        } catch (DestroyFailedException dfe) {
            // ignore
        }
    }
}