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:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a private key stored in a local file
 * <p>/*from   ww  w. j  av  a  2s  .co  m*/
 * Tries to guess the algorithm used for keypair generation which
 * is not included in the file. According to <a href="http://download.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html#AppA">Java Cryptography Specification</a>,
 * the algorithm can be only one of "RSA" or "DSA", so we can just try both using the
 * <code>algorithms</code> param. If the algorithm used to generate the key is neither RSA or DSA
 * (highly unlikely), this method cannot recreate the private key, but {@link #decrypt(String)}
 * maybe will.
 * 
 * @param privPath
 *            path to the private key on the local filesystem
 * @param algorithms a list of algorithms to try for creating the PK. Recommanded value:
 *          {"RSA","DSA"}
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException
 *             the key could not be retrieved or is malformed, or the algorithm used for generation
 *             is not one of <code>algorithms</code>
 */
public static PrivateKey getPrivateKey(String privPath, String[] algorithms) throws KeyException {

    PrivateKey privKey = null;

    for (String algo : algorithms) {
        try {
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance(algo);

            // recover private key bytes
            byte[] bytes;
            try {
                File pkFile = new File(privPath);
                DataInputStream pkStream = new DataInputStream(new FileInputStream(pkFile));
                bytes = new byte[(int) pkFile.length()];
                pkStream.readFully(bytes);
                pkStream.close();
            } catch (Exception e) {
                throw new KeyException("Could not recover private key (algo=" + algo + ")", e);
            }

            // reconstruct private key
            PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(bytes);
            try {
                privKey = keyFactory.generatePrivate(privKeySpec);
            } catch (InvalidKeySpecException e) {
                throw new KeyException("Cannot re-generate private key  (algo=" + algo + ")", e);
            }
        } catch (Exception e) {
        }
    }

    if (privKey == null) {
        String str = "Could not generate Private Key (algorithms: ";
        for (String algo : algorithms) {
            str += algo + " ";
        }
        str += ")";
        throw new KeyException(str);
    }

    return privKey;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

static PrivateKey loadPrivateKey(String file, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Private Key.
    File filePrivateKey = new File(file);
    FileInputStream fis = new FileInputStream(file);
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);// w w  w. ja  v a  2s  .c  om
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return privateKey;
}

From source file:cloud.google.com.windows.example.ExampleCode.java

@SuppressWarnings("unchecked")
private JSONObject jsonEncode(KeyPair keys) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory factory = KeyFactory.getInstance("RSA");

    // Get the RSA spec for key manipulation.
    RSAPublicKeySpec pubSpec = factory.getKeySpec(keys.getPublic(), RSAPublicKeySpec.class);

    // Extract required parts of the key.
    BigInteger modulus = pubSpec.getModulus();
    BigInteger exponent = pubSpec.getPublicExponent();

    // Grab an encoder for the modulus and exponent to encode using RFC 3548;
    // Java SE 7 requires an external library (Google's Guava used here)
    // Java SE 8 has a built-in Base64 class that can be used instead. Apache also has an RFC 3548
    // encoder.//  w w w .  j a  v  a  2 s .c o m
    BaseEncoding stringEncoder = BaseEncoding.base64();

    // Strip out the leading 0 byte in the modulus.
    byte[] arr = Arrays.copyOfRange(modulus.toByteArray(), 1, modulus.toByteArray().length);

    JSONObject returnJson = new JSONObject();

    // Encode the modulus, add to returned JSON object.
    String modulusString = stringEncoder.encode(arr).replaceAll("\n", "");
    returnJson.put("modulus", modulusString);

    // Encode exponent, add to returned JSON object.
    String exponentString = stringEncoder.encode(exponent.toByteArray()).replaceAll("\n", "");
    returnJson.put("exponent", exponentString);

    return returnJson;
}

From source file:gemlite.core.util.RSAUtils.java

/**
 * <p>/*from  w w  w.j a  v a  2  s.  com*/
 * ?
 * </p>
 * 
 * @param data
 *          ??
 * @param privateKey
 *          ?(BASE64?)
 * @return
 * @throws Exception
 */
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateK);
    int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
            cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(data, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_ENCRYPT_BLOCK;
    }
    byte[] encryptedData = out.toByteArray();
    out.close();
    return encryptedData;
}

From source file:de.ub0r.android.lib.DonationHelper.java

/**
 * Check for signature updates.// w w w.ja  v a  2 s . c  o m
 * 
 * @param context
 *            {@link Context}
 * @param s
 *            signature
 * @param h
 *            hash
 * @return true if ads should be hidden
 */
public static boolean checkSig(final Context context, final String s, final String h) {
    Log.d(TAG, "checkSig(ctx, " + s + ", " + h + ")");
    boolean ret = false;
    try {
        final byte[] publicKey = Base64Coder.decode(KEY);
        final KeyFactory keyFactory = KeyFactory.getInstance(ALGO);
        PublicKey pk = keyFactory.generatePublic(new X509EncodedKeySpec(publicKey));
        Log.d(TAG, "hash: " + h);
        final String cs = s.replaceAll(" |\n|\t", "");
        Log.d(TAG, "read sig: " + cs);
        try {
            byte[] signature = Base64Coder.decode(cs);
            Signature sig = Signature.getInstance(SIGALGO);
            sig.initVerify(pk);
            sig.update(h.getBytes());
            ret = sig.verify(signature);
            Log.d(TAG, "ret: " + ret);
        } catch (IllegalArgumentException e) {
            Log.w(TAG, "error reading signature", e);
        }
    } catch (Exception e) {
        Log.e(TAG, "error reading signatures", e);
    }
    if (!ret) {
        Log.i(TAG, "sig: " + s);
    }
    return ret;
}

From source file:authorize.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Logger logger = LogManager.getLogger(authorize.class);
    logger.trace("START");
    PrintWriter out = response.getWriter();
    Connection conn = null;/*from   ww  w  .jav  a 2s .c o  m*/
    Statement stmt = null;
    ResultSet rs = null;
    HttpSession session = request.getSession(false);
    String response_type = request.getParameter("response_type");
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String prompt = request.getParameter("prompt");
    String login_hint = request.getParameter("login_hint");
    String max_age = request.getParameter("max_age");
    String client_id = request.getParameter("client_id");
    String redirect_uri = request.getParameter("redirect_uri");
    String scope = request.getParameter("scope");
    String state = request.getParameter("state");
    String nonce = request.getParameter("nonce");
    String consent = request.getParameter("consent");
    String client_scope = null;
    String access_token = null;
    String id_token = null;
    String passwd = null;
    String db_redirect_uri = null;
    String path = null;
    String sql = null;
    String uri = null;
    String issuer = null;
    String keyname = null;
    String kit = "public.key";
    boolean redirect_uri_check = true;
    int access_token_time = 60;
    if (scope == null) {
        scope = "openid";
    } else if (scope.equals("consent")) {
        scope = null;
        if (null != request.getParameter("openid")) {
            scope = "openid";
            if (null != request.getParameter("profile"))
                scope += " profile";
            if (null != request.getParameter("email"))
                scope += " email";
            if (null != request.getParameter("phone"))
                scope += " phone";
            if (null != request.getParameter("address"))
                scope += " address";
        }
    }
    logger.trace(scope);
    if (prompt != null && prompt.contains("login") && consent == null && session != null)
        session.invalidate();
    try {
        ServletContext context = this.getServletContext();
        path = context.getRealPath("/WEB-INF/oauth2");
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        conn = DriverManager.getConnection("jdbc:derby:" + path);
        stmt = conn.createStatement();
        logger.trace("connect()");
        sql = "SELECT scope,redirect_uri FROM client WHERE client_id='" + client_id + "'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            client_scope = rs.getString("scope");
            db_redirect_uri = rs.getString("redirect_uri");
        }
        logger.trace(sql);
        if (redirect_uri == null)
            redirect_uri = db_redirect_uri;
        sql = "SELECT passwd FROM profile WHERE uid='" + username + "'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            passwd = rs.getString("passwd");
        }
        logger.trace(sql);
        path = context.getRealPath("/WEB-INF/config.json");
        InputStream input = new FileInputStream(path);
        JsonParser parser = Json.createParser(input);
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch (event) {
            case KEY_NAME:
                keyname = parser.getString();
                break;
            case VALUE_NUMBER:
                access_token_time = parser.getInt();
                break;
            case VALUE_TRUE:
                redirect_uri_check = true;
                break;
            case VALUE_FALSE:
                redirect_uri_check = false;
                break;
            case VALUE_STRING:
                if (keyname.equals("issuer"))
                    issuer = parser.getString();
                if (keyname.equals("kit"))
                    kit = parser.getString();
                break;
            default:
                break;
            }
        }
        java.util.Date dt = new java.util.Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        if (client_scope != null && passwd != null) {
            byte[] cipher_byte;
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes());
            cipher_byte = md.digest();
            String sha256_password = Base64.getEncoder().withoutPadding().encodeToString(cipher_byte);
            StringTokenizer strToken = new StringTokenizer(scope, " ");
            while (strToken.hasMoreTokens()) {
                String token = strToken.nextToken().toString();
                logger.trace(token);
                if (!client_scope.contains(token))
                    throw new Exception("out of scope");
            }
            if (passwd.contains(sha256_password)
                    && (!redirect_uri_check || db_redirect_uri.equals(redirect_uri))) {
                if (prompt != null && prompt.contains("consent") && !consent.equals("false")) {
                    username = "null";
                    password = "null";
                    consent = "true";
                    throw new Exception("consent is true");
                }
                access_token = RandomStringUtils.randomAlphanumeric(32);
                logger.trace(access_token);
                sql = "insert into session(uid,access_token,issued_in,scope,client_id) values ('" + username
                        + "','" + access_token + "','" + currentTime + "','" + scope + "','" + client_id + "')";
                stmt.executeUpdate(sql);
                md.update(access_token.getBytes());
                cipher_byte = md.digest();
                byte[] half_cipher_byte = Arrays.copyOf(cipher_byte, (cipher_byte.length / 2));
                String at_hash = Base64.getEncoder().withoutPadding().encodeToString(half_cipher_byte);
                path = context.getRealPath("/WEB-INF/private.der");
                File filePrivateKey = new File(path);
                FileInputStream fis = new FileInputStream(path);
                byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
                fis.read(encodedPrivateKey);
                fis.close();
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
                PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
                Calendar exp = Calendar.getInstance();
                exp.add(Calendar.SECOND, access_token_time);
                if (nonce == null || nonce.equals("null")) {
                    if (response_type.contains("id_token")) {
                        uri = redirect_uri;
                        uri += "#error=invalid_request&error_description=nonce%20is%20not%20valid.";
                        response.sendRedirect(uri);
                        logger.info(uri);
                        return;
                    }
                } else {
                    id_token = Jwts.builder().setHeaderParam("alg", "RS256").setHeaderParam("typ", "JWT")
                            .setHeaderParam("kid", kit).setIssuer(issuer).claim("at_hash", at_hash)
                            .setSubject(username).setAudience(client_id).claim("nonce", nonce)
                            .setSubject(username).setExpiration(exp.getTime())
                            .setIssuedAt(Calendar.getInstance().getTime())
                            .claim("auth_time",
                                    String.valueOf(Calendar.getInstance().getTime().getTime()).substring(0, 10))
                            .signWith(SignatureAlgorithm.RS256, privateKey).compact();
                    logger.trace(id_token);
                }
                uri = redirect_uri;
                if (response_type.equals("token"))
                    uri += "#access_token=" + access_token + "&token_type=bearer&expires_in="
                            + access_token_time;
                if (response_type.equals("id_token"))
                    uri += "#id_token=" + id_token;
                if (response_type.equals("token id_token") || response_type.equals("id_token token"))
                    uri += "#access_token=" + access_token + "&token_type=bearer&expires_in="
                            + access_token_time + "&id_token=" + id_token;
                if (state != null && !state.equals("null"))
                    uri += "&state=" + state;
                response.sendRedirect(uri);
                logger.info(uri);
                return;
            }
        }
    } catch (Exception e) {
        logger.trace(e.getMessage());
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
            logger.trace("close()");
        } catch (SQLException e) {
            logger.trace(e.getMessage());
        }
    }
    if (redirect_uri != null || redirect_uri.equals("null"))
        uri = redirect_uri;
    else
        uri = "/myop/error";
    if (username != null && !username.equals("null") && password != null && !password.equals("null")) {
        uri += "#error=access_denied&error_description=User%20authentication%20failed.";
        session = request.getSession(false);
        if (session != null)
            session.invalidate();
    } else if (scope == null) {
        uri += "#error=invalid_scope&error_description=The%20scope%20value%20is%20not%20supported.";
    } else if (client_scope == null || client_scope.equals("null")) {
        uri += "#error=unauthorized_clienti&error_description=Client%20authentication%20failed.";
    } else if (response_type == null || response_type.equals("null")
            || !(response_type.equals("token") || response_type.equals("id_token")
                    || response_type.equals("token id_token") || response_type.equals("id_token token"))) {
        uri += "#error=unsupported_response_type&error_description==The%20response_type%20value%20%22"
                + response_type + "%22%20is%20not%20supported.";
    } else if (redirect_uri_check && !db_redirect_uri.equals(redirect_uri)) {
        uri += "#error=invalid_request&error_description=redirect_uri%20is%20not%20valid.";
    } else {
        uri = "/myop/login?response_type=" + URLEncoder.encode(response_type, "UTF-8") + "&client_id="
                + client_id + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&scope="
                + URLEncoder.encode(scope, "UTF-8");
        if (nonce != null && !nonce.equals("null"))
            uri += "&nonce=" + nonce;
        if (prompt != null && !prompt.equals("null"))
            uri += "&prompt=" + prompt;
        if (login_hint != null && !login_hint.equals("null"))
            uri += "&login_hint=" + login_hint;
        if (max_age != null && !max_age.equals("null"))
            uri += "&max_age=" + max_age;
        if (consent != null && consent.equals("true"))
            uri += "&consent=" + consent;
    }
    if (state != null && !state.equals("null"))
        uri += "&state=" + state;
    response.sendRedirect(uri);
    logger.info(uri);
    logger.trace("END");
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Given a Base64-encoded, PKCS8-formatted RSA private key, returns a PrivateKey object representing it
 *
 * @param encodedKey// w  w w  . j a v  a2 s . c om
 *
 * @return the RSA private key, or null if the RSA algorithm is not available on the system
 */
public static PrivateKey getPrivateKeyFromBASE64PKCS8Encoded(String encodedKey) {
    byte[] decoded = Base64.decodeBase64(encodedKey);

    try {
        return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:org.bedework.util.security.pki.PKITools.java

private PrivateKey makePrivateKey(final byte[] privKeyBytes) throws PKIException {
    try {/*from   w ww  . j a  v a2  s. c o  m*/
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
        KeyFactory kf;

        if (curSchema.pName == null) {
            kf = KeyFactory.getInstance(curSchema.algorithm);
        } else {
            kf = KeyFactory.getInstance(curSchema.algorithm, curSchema.pName);
        }

        return kf.generatePrivate(privateKeySpec);
    } catch (Throwable t) {
        throw new PKIException(t);
    }
}

From source file:com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.util.PublicKeyReaderUtil.java

/**
 * <p>Decode a RSA public key encoded according to the SSH standard from
 * the data <code>_buffer</code>. The values of the RSA public key
 * specification are read in the order//from   ww w .j  av  a 2  s.  c o m
 * <ul>
 * <li>public exponent</li>
 * <li>modulus</li>
 * </ul>
 * With the specification the related RSA public key is generated.</p>
 *
 * @param _buffer   key / certificate data (certificate or public key
 *                  format identifier is already read)
 * @return RSA public key instance
 * @throws PublicKeyParseException if the SSH2 public key blob could not be
 *                                 decoded
 * @see RSAPublicKeySpec
 * @see <a href="http://en.wikipedia.org/wiki/RSA">RSA on Wikipedia</a>
 * @see <a href="http://tools.ietf.org/html/rfc4253#section-6.6">RFC 4253 Section 6.6</a>
 */
private static PublicKey decodePublicKey(final SSH2DataBuffer _buffer) throws PublicKeyParseException {
    final BigInteger e = _buffer.readMPint();
    final BigInteger n = _buffer.readMPint();

    try {
        final KeyFactory rsaKeyFact = KeyFactory.getInstance("RSA");
        final RSAPublicKeySpec rsaPubSpec = new RSAPublicKeySpec(n, e);

        return rsaKeyFact.generatePublic(rsaPubSpec);

    } catch (final Exception ex) {
        throw new PublicKeyParseException(
                PublicKeyParseException.ErrorCode.SSH2RSA_ERROR_DECODING_PUBLIC_KEY_BLOB, ex);
    }
}

From source file:libcore.tzdata.update_test_app.installupdatetestapp.MainActivity.java

private static PrivateKey createKey() throws Exception {
    byte[] derKey = Base64.decode(TEST_KEY.getBytes(), Base64.DEFAULT);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(derKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}