Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

In this page you can find the example usage for java.security KeyFactory getInstance.

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:android.content.pm.PackageParser.java

public static final PublicKey parsePublicKey(final String encodedPublicKey) {
    if (encodedPublicKey == null) {
        Slog.w(TAG, "Could not parse null public key");
        return null;
    }/*w w w .  j ava2 s .  c om*/

    EncodedKeySpec keySpec;
    try {
        final byte[] encoded = Base64.decode(encodedPublicKey, Base64.DEFAULT);
        keySpec = new X509EncodedKeySpec(encoded);
    } catch (IllegalArgumentException e) {
        Slog.w(TAG, "Could not parse verifier public key; invalid Base64");
        return null;
    }

    /* First try the key as an RSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e) {
        Slog.wtf(TAG, "Could not parse public key: RSA KeyFactory not included in build");
    } catch (InvalidKeySpecException e) {
        // Not a RSA public key.
    }

    /* Now try it as a ECDSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("EC");
        return keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e) {
        Slog.wtf(TAG, "Could not parse public key: EC KeyFactory not included in build");
    } catch (InvalidKeySpecException e) {
        // Not a ECDSA public key.
    }

    /* Now try it as a DSA key. */
    try {
        final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        return keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e) {
        Slog.wtf(TAG, "Could not parse public key: DSA KeyFactory not included in build");
    } catch (InvalidKeySpecException e) {
        // Not a DSA public key.
    }

    /* Not a supported key type */
    return null;
}