Java Code Examples for java.security.KeyStore.PasswordProtection

The following are Jave code examples for showing how to use PasswordProtection of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sample-acmegifts   File: JWTVerifier.java   View Source Code Vote up 7 votes
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 2
Project: jetfuel   File: X509CertificateWithKey.java   View Source Code Vote up 6 votes
public void loadPfx(InputStream is, String password)
		throws NoSuchAlgorithmException,
			CertificateException,
			IOException,
			KeyStoreException,
			UnrecoverableEntryException {

	char[] pwd = password.toCharArray();
	KeyStore keyStore = KeyStore.getInstance("pkcs12");
	keyStore.load(is, pwd);
	PasswordProtection passwordProtection = new KeyStore.PasswordProtection(pwd);

	for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements();) {
		String alias = aliases.nextElement();
		KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, passwordProtection);
		Certificate cert = entry.getCertificate();
		if (cert.getType().equals("X.509")) {
			this.certificate = (X509Certificate) cert;
			this.privateKey = entry.getPrivateKey();
			return;
		}
	}
	throw new RuntimeException("Certificate of type X.509 was not found.");

}
 
Example 3
Project: javaide   File: KeyStoreFileManager.java   View Source Code Vote up 6 votes
public static KeyStore.Entry getKeyEntry( String keystorePath, String storePass, String keyName, String keyPass)
    throws Exception
{
    char[] keyPw = null;
    KeyStore.PasswordProtection passwordProtection = null;

    try {
        KeyStore ks = loadKeyStore(keystorePath, storePass);
        keyPw = PasswordObfuscator.getInstance().decodeAliasPassword( keystorePath, keyName, keyPass);
        passwordProtection = new KeyStore.PasswordProtection(keyPw);
        return ks.getEntry( keyName, passwordProtection);
    }
    finally {
        if (keyPw != null) PasswordObfuscator.flush(keyPw);
        if (passwordProtection != null) passwordProtection.destroy();
    }
}
 
Example 4
Project: xtf   File: XTFKeyStore.java   View Source Code Vote up 6 votes
/**
 * Asymmetric cryptography - only the private key from generated pair is used.
 * Pre-condition: #certificateAlias refers to existing certificate
 *
 * @throws {@link NullPointerException} when #certificateAlias is @code{null}
 */
public void addPrivateKey(String keyAlias, String certificateAlias, String password) {
	keyAlias = String.format("%s (%s)", keyAlias, certificateAlias);

	try {
		Certificate[] certChain = keystore.getCertificateChain(certificateAlias);
		if (certChain == null) {
			LoggerFactory.getLogger(getClass()).warn("Could not find certificate");
			certChain = new Certificate[0];
		}
		Entry entry = new PrivateKeyEntry(generateKeyPair().getPrivate(), certChain);
		ProtectionParameter protParam = new KeyStore.PasswordProtection(password.toCharArray());
		keystore.setEntry(keyAlias, entry, protParam);
	} catch (KeyStoreException | NoSuchAlgorithmException ex) {
		throw new RuntimeException("Unable to add new private key", ex);
	}
}
 
Example 5
Project: jdk8u-jdk   File: P12SecretKey.java   View Source Code Vote up 5 votes
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 6
Project: openjdk-jdk10   File: TestKeyStoreBasic.java   View Source Code Vote up 5 votes
private void checkSetEntry(KeyStore ks, String alias,
    KeyStore.PasswordProtection pw, KeyStore.Entry entry) throws Exception {
    try {
        ks.setEntry(alias, entry, pw);
        throw new Exception(
            "ERROR: expected KeyStore.setEntry to throw an exception");
    } catch (KeyStoreException e) {
        // ignore the expected exception
    }
}
 
Example 7
Project: iTAP-controller   File: CryptoUtil.java   View Source Code Vote up 5 votes
public static byte[] getSharedSecret(String keyStorePath,
                                     String keyStorePassword) 
                                                throws Exception {
    if (keyStorePath == null) return null;
    char[] password = keyStorePassword.toCharArray();
    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);

    KeyStore ks = readKeyStore(keyStorePath, password);

    KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)
            ks.getEntry(CHALLENGE_RESPONSE_SECRET, protParam);
    SecretKey secretKey = entry.getSecretKey();
    return secretKey.getEncoded();
}
 
Example 8
Project: openjdk-jdk10   File: P12SecretKey.java   View Source Code Vote up 5 votes
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 9
Project: Android_Code_Arbiter   File: ConstantPasswords.java   View Source Code Vote up 5 votes
public void bad7() throws Exception {
    byte[] bytes = new byte[2];
    char[] pwd = "secret7".toCharArray();
    new PBEKeySpec(pwd);
    new PBEKeySpec(pwd, bytes, 1);
    new PBEKeySpec(pwd, bytes, 1, 1);
    PasswordAuthentication auth = new PasswordAuthentication("user", pwd);
    PasswordCallback callback = new PasswordCallback("str", true);
    callback.setPassword(pwd);
    KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(pwd);
    KerberosKey key = new KerberosKey(null, pwd, "alg");
    KeyManagerFactory.getInstance("").init(null, pwd);
}
 
Example 10
Project: fresco_floodlight   File: CryptoUtil.java   View Source Code Vote up 5 votes
public static byte[] getSharedSecret(String keyStorePath,
                                     String keyStorePassword) 
                                                throws Exception {
    if (keyStorePath == null) return null;
    char[] password = keyStorePassword.toCharArray();
    KeyStore.ProtectionParameter protParam =
            new KeyStore.PasswordProtection(password);

    KeyStore ks = readKeyStore(keyStorePath, password);

    KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)
            ks.getEntry(CHALLENGE_RESPONSE_SECRET, protParam);
    SecretKey secretKey = entry.getSecretKey();
    return secretKey.getEncoded();
}
 
Example 11
Project: mi-firma-android   File: CeresKeyStoreImpl.java   View Source Code Vote up 5 votes
/** {@inheritDoc} */
 @Override
 public void engineLoad(final KeyStore.LoadStoreParameter param) throws IOException {
 	if (param != null) {
 		final ProtectionParameter pp = param.getProtectionParameter();
 		if (pp instanceof KeyStore.CallbackHandlerProtection) {
 			if (((KeyStore.CallbackHandlerProtection) pp).getCallbackHandler() == null) {
 				throw new IllegalArgumentException("El CallbackHandler no puede ser nulo"); //$NON-NLS-1$
 			}
 			this.cryptoCard = new Ceres(
 					CeresProvider.getDefaultApduConnection(),
 					new JseCryptoHelper()
 				);
 			this.cryptoCard.setCallbackHandler(((KeyStore.CallbackHandlerProtection) pp).getCallbackHandler());
 		}
 		else if (pp instanceof KeyStore.PasswordProtection) {
 			final PasswordCallback pwc = new CeresPasswordCallback((PasswordProtection) pp);
 			this.cryptoCard = new Ceres(
 					CeresProvider.getDefaultApduConnection(),
 					new JseCryptoHelper()
 				);
 			this.cryptoCard.setPasswordCallback(pwc);
 		}
 		else {
     		Logger.getLogger("es.gob.jmulticard").warning( //$NON-NLS-1$
 				"Se ha proporcionado un LoadStoreParameter de tipo no soportado, se ignorara: " + (pp != null ? pp.getClass().getName() : "NULO") //$NON-NLS-1$ //$NON-NLS-2$
	);
 		}
 	}
 	else {
  	this.cryptoCard = new Ceres(
	CeresProvider.getDefaultApduConnection(),
	new JseCryptoHelper()
);
 	}

 	userCertAliases = Arrays.asList(this.cryptoCard.getAliases());
 }
 
Example 12
Project: ipack   File: JDKPKCS12StoreParameter.java   View Source Code Vote up 4 votes
public void setPassword(char[] password)
{
    this.protectionParameter = new KeyStore.PasswordProtection(password);
}
 
Example 13
Project: ipack   File: PKCS12StoreParameter.java   View Source Code Vote up 4 votes
public PKCS12StoreParameter(OutputStream out, char[] password, boolean forDEREncoding)
{
    this(out, new KeyStore.PasswordProtection(password), forDEREncoding);
}
 
Example 14
Project: OpenJSharp   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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 15
Project: OpenJSharp   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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 16
Project: jdk8u-jdk   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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 17
Project: jdk8u-jdk   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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 18
Project: openjdk-jdk10   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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 19
Project: openjdk-jdk10   File: PKCS12KeyStore.java   View Source Code Vote up 4 votes
/**
 * 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 20
Project: fresco_floodlight   File: CryptoUtil.java   View Source Code Vote up 4 votes
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();
        }
    }
}