Java Code Examples for java.security.KeyStore.getEntry()

The following are Jave code examples for showing how to use getEntry() 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: CacheManage   File: KeyStoreHelper.java   View Source Code Vote up 6 votes
private static KeyStore.PrivateKeyEntry getPrivateKeyEntry(String alias) {
    try {
        KeyStore ks =
                KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
        ks.load(null);
        KeyStore.Entry entry = ks.getEntry(alias, null);

        if (entry == null) {
            Log.w(TAG, "No key found under alias: " + alias);
            Log.w(TAG, "Exiting signData()...");
            return null;
        }

        if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
            Log.w(TAG, "Not an instance of a PrivateKeyEntry");
            Log.w(TAG, "Exiting signData()...");
            return null;
        }
        return (KeyStore.PrivateKeyEntry) entry;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return null;
    }
}
 
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: openjdk-jdk10   File: Bug6415637.java   View Source Code Vote up 6 votes
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example 5
Project: privacyidea-authenticator   File: SecretKeyWrapper.java   View Source Code Vote up 6 votes
/**
 * Create a wrapper using the public/private key pair with the given alias.
 * If no pair with that alias exists, it will be generated.
 */
@SuppressLint("GetInstance")
public SecretKeyWrapper(Context context, String alias)
        throws GeneralSecurityException, IOException {
    mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

    final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);

    if (!keyStore.containsAlias(alias)) {
        generateKeyPair(context, alias);
    }

    // Even if we just generated the key, always read it back to ensure we
    // can read it successfully.
    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(
            alias, null);
    mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
}
 
Example 6
Project: jdk8u-jdk   File: MetadataStoreLoadTest.java   View Source Code Vote up 6 votes
private void checkAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ks = Utils.loadKeyStore(WORKING_DIRECTORY
            + File.separator
            + KESTORE_NEW, Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore.Entry keyStoreEntry = ks.getEntry(ALIAS,
            new KeyStore.PasswordProtection(KEY_PASSWORD));
    out.println("Attributes after store:");
    //print attribute values
    keyStoreEntry.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Arrays.stream(ATTR_SET).forEach((attr) -> {
        if (!keyStoreEntry.getAttributes().contains(attr)) {
            throw new RuntimeException("Entry doesn't contain attribute: ("
                    + attr.getName() + ", '" + attr.getValue() + "')");
        }
    });
}
 
Example 7
Project: jdk8u-jdk   File: Bug6415637.java   View Source Code Vote up 6 votes
private static void check(String encodedBlob) throws Exception {
    byte[] blob = new byte[encodedBlob.length() * 2];
    for (int i = 0; i < blob.length; ) {
        final char ch = encodedBlob.charAt(i / 2);
        blob[i++] = (byte) (ch >> 8);
        blob[i++] = (byte) ch;
    }
    KeyStore store = KeyStore.getInstance("PKCS12");
    store.load(new ByteArrayInputStream(blob), new char[0]);
    if (!store.aliases().nextElement().equals("test"))
        throw new Exception("test alias not found");
    KeyStore.PrivateKeyEntry e =
        (KeyStore.PrivateKeyEntry) store.getEntry("test",
                new KeyStore.PasswordProtection(new char[0]));
    X509Certificate cert = (X509Certificate) e.getCertificateChain()[0];
    if (!cert.getSubjectDN().toString().equals("CN=Test Key"))
        throw new Exception("invalid certificate subject DN");
    RSAPrivateCrtKey key = (RSAPrivateCrtKey) e.getPrivateKey();
    if (!key.getPublicExponent().equals(BigInteger.valueOf(65537)))
        throw new Exception("invalid public exponent");
}
 
Example 8
Project: openjdk-jdk10   File: MixedcaseAlias.java   View Source Code Vote up 5 votes
public static void main(String[] ignored) throws Exception {
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(null, null);

    keystore.setCertificateEntry(ALIAS, loadCertificate(CERT));
    KeyStore.Entry entry = keystore.getEntry(ALIAS, null);

    if (entry == null) {
        throw new Exception(
            "Error retrieving keystore entry using a mixed-case alias");
    }

    System.out.println("OK");
}
 
Example 9
Project: openjdk-jdk10   File: EmptyAlias.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(null, null);

    keystore.setCertificateEntry(EMPTY_ALIAS, loadCertificate(CERT));
    KeyStore.Entry entry = keystore.getEntry(EMPTY_ALIAS, null);

    if (entry == null) {
        throw new Exception(
            "Error retrieving keystore entry using its (empty) alias");
    }

    System.out.println("OK");
}
 
Example 10
Project: rebase-android   File: BlackBox.java   View Source Code Vote up 5 votes
/**
 * Decrypt the encrypted secret.
 *
 * @param encrypted the encrypted secret.
 * @return the decrypted secret.
 * @throws Exception
 */
public String decrypt(String encrypted) throws Exception {
    byte[] encryptedBytes = Base64.decode(encrypted, Base64.DEFAULT);
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry privateKeyEntry =
        (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
    Cipher output = Cipher.getInstance(RSA_ALGORITHM);
    output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
    CipherInputStream cipherInputStream = new CipherInputStream(
        new ByteArrayInputStream(encryptedBytes), output);
    ArrayList<Byte> values = new ArrayList<>();
    int nextByte;
    while ((nextByte = cipherInputStream.read()) != -1) {
        values.add((byte) nextByte);
    }

    byte[] bytes = new byte[values.size()];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = values.get(i);
    }
    return new String(bytes);
}
 
Example 11
Project: oscm   File: CopyKeyTask.java   View Source Code Vote up 5 votes
private Entry loadEntry(final EntryDescriptor descr) throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore(descr);
    final Entry entry = keystore.getEntry(descr.getAlias(),
            createProtection(descr));
    if (entry == null) {
        throw new BuildException(String.format(
                "No entry %s found in keystore %s.", descr.getAlias(),
                descr.getKeystore()));
    }
    return entry;
}
 
Example 12
Project: oscm   File: SignTask.java   View Source Code Vote up 5 votes
private PrivateKeyEntry loadCAKeyEntry() throws IOException,
        GeneralSecurityException {
    final KeyStore keystore = loadKeyStore();
    final Entry entry = keystore.getEntry(this.alias,
            new PasswordProtection(this.password.toCharArray()));
    return (PrivateKeyEntry) entry;
}
 
Example 13
Project: xrd4j   File: CryptoHelper.java   View Source Code Vote up 5 votes
/**
 * Fetches the private key matching the given alias from the defined key
 * store.
 *
 * @param path absolute path of the key store file
 * @param storePassword password of the key store
 * @param privateKeyAlias alias of the private key in the key store
 * @param keyPassword password of the private key
 * @return private key with the given alias
 */
public static PrivateKey getPrivateKey(String path, String storePassword, String privateKeyAlias, String keyPassword) {
    try (FileInputStream fis = new java.io.FileInputStream(path)) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(fis, storePassword.toCharArray());
        KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(privateKeyAlias,
                new KeyStore.PasswordProtection(keyPassword.toCharArray()));
        return pkEntry.getPrivateKey();
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
        | UnrecoverableEntryException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new XRd4JRuntimeException(ex.getMessage());
    }
}
 
Example 14
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 15
Project: react-native-caller-id-android   File: DataBase.java   View Source Code Vote up 5 votes
public static KeyStore.PrivateKeyEntry getPrivateKeyEntry (String alias) {
    KeyStore.PrivateKeyEntry privateKeyEntry = null;
    try {
        KeyStore keystore = KeyStore.getInstance(keyStoreInstance);
        keystore.load(null);

        privateKeyEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, null);
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return privateKeyEntry;
}
 
Example 16
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 17
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 18
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 19
Project: openjdk-jdk10   File: TestKeyStoreBasic.java   View Source Code Vote up 5 votes
private void checkGetEntry(KeyStore ks, String alias,
    KeyStore.PasswordProtection pw) throws Exception {
    try {
        ks.getEntry(alias, pw);
        throw new Exception(
            "ERROR: expected KeyStore.getEntry to throw an exception");
    } catch (KeyStoreException e) {
        // ignore the expected exception
    }
}
 
Example 20
Project: openjdk-jdk10   File: Main.java   View Source Code Vote up 4 votes
/**
 * Recovers entry associated with given alias.
 *
 * @return an array of objects, where the 1st element in the array is the
 * recovered entry, and the 2nd element is the password used to
 * recover it (null if no password).
 */
private Pair<Entry,char[]> recoverEntry(KeyStore ks,
                        String alias,
                        char[] pstore,
                        char[] pkey) throws Exception {

    if (ks.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat
            (rb.getString("Alias.alias.does.not.exist"));
        Object[] source = {alias};
        throw new Exception(form.format(source));
    }

    PasswordProtection pp = null;
    Entry entry;

    try {
        // First attempt to access entry without key password
        // (PKCS11 entry or trusted certificate entry, for example)

        entry = ks.getEntry(alias, pp);
        pkey = null;
    } catch (UnrecoverableEntryException une) {

        if(P11KEYSTORE.equalsIgnoreCase(ks.getType()) ||
            KeyStoreUtil.isWindowsKeyStore(ks.getType())) {
            // should not happen, but a possibility
            throw une;
        }

        // entry is protected

        if (pkey != null) {

            // try provided key password

            pp = new PasswordProtection(pkey);
            entry = ks.getEntry(alias, pp);

        } else {

            // try store pass

            try {
                pp = new PasswordProtection(pstore);
                entry = ks.getEntry(alias, pp);
                pkey = pstore;
            } catch (UnrecoverableEntryException une2) {
                if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) {

                    // P12 keystore currently does not support separate
                    // store and entry passwords

                    throw une2;
                } else {

                    // prompt for entry password

                    pkey = getKeyPasswd(alias, null, null);
                    pp = new PasswordProtection(pkey);
                    entry = ks.getEntry(alias, pp);
                }
            }
        }
    }

    return Pair.of(entry, pkey);
}