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:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

private DSAPublicKey decodeDsaPublicKeyFromBitString(DERBitString der, BigInteger p, BigInteger q, BigInteger g)
        throws SpkacException {
    try {// w w  w . jav  a 2 s.  c  om
        BigInteger y = ASN1Integer.getInstance(der.getBytes()).getValue();

        KeyFactory keyFact = KeyFactory.getInstance("DSA");

        return (DSAPublicKey) keyFact.generatePublic(new DSAPublicKeySpec(y, p, q, g));
    } catch (GeneralSecurityException ex) {
        throw new SpkacException(res.getString("NoGenerateDsaPublicKeyFromSpkac.exception.message"), ex);
    } catch (Exception ex) {
        throw new SpkacException(res.getString("NoGenerateDsaPublicKeyFromSpkac.exception.message"), ex);
    }
}

From source file:com.hpe.elderberry.TaxiiConnection.java

/**
 * a convenient way to externally cache the key store is to create it from PEMs using
 * {@link #setPrivateKeyPem(String)} and {@link #setClientCertificatePemChain(List)} then obtaining it with this method and
 * storing it for future use.<p>/*from  w  w w.j  av a2 s .c o  m*/
 * This method attempts to retrieve the key store in the following algorithm:
 * <ul>
 * <li>When it was already loaded or constructed it's returned</li>
 * <li>When it was directly set by {@link #setKeyStore(KeyStore, String)} then this key store is returned</li>
 * <li>When a key store file and password was set by {@link #setKeyStoreFile(File)} and
 * {@link #setKeyStorePassword(String)}, then the key store is loaded from the file and returned</li>
 * <li>When a private key was set by {@link #setPrivateKeyPem(String)} and its certificate chain was set by
 * {@link #setClientCertificatePemChain(List)} then a new key store is created, the private key material and the
 * client certificates are loaded into it, then this new key store is returned</li>
 * </ul>
 *
 * @return the key store
 */
public KeyStore getKeyStore() {
    if (keyStore != null) {
        return keyStore;
    }

    if (keyStoreFile != null) {
        try {
            keyStore = getInstance("JKS");
            keyStore.load(newInputStream(keyStoreFile.toPath()),
                    keyStorePassword == null ? "".toCharArray() : keyStorePassword.toCharArray());
        } catch (Exception e) {
            throw new RuntimeException("a key store file was set, but it could not be read, " + e.getMessage(),
                    e);
        }
    } else if (!isEmpty(privateKeyPem)) {
        try {
            // initialize an empty key store
            keyStore = getInstance("JKS");
            keyStore.load(null);

            // generate a random password for the private key
            keyPassword = randomUUID().toString().toCharArray();

            // load the private key
            byte[] key = parseBase64Binary(privateKeyPem.replaceAll("-+.*-+", ""));
            PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(key));
            if (clientCertificatePemChain != null) {
                List<Certificate> chain = addPemsToStore(keyStore, clientCertificatePemChain);
                keyStore.setKeyEntry(randomUUID().toString(), privateKey, keyPassword,
                        chain.toArray(new Certificate[chain.size()]));
            } else {
                keyStore.setKeyEntry(randomUUID().toString(), privateKey, keyPassword, new Certificate[] {});
            }
        } catch (Exception e) {
            throw new RuntimeException("unable to create key store, " + e.getMessage(), e);
        }
    }

    return keyStore;
}

From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

private Cipher getRsaCipher(String key) {
    try {//  w  ww.ja  v  a 2 s .co  m
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        String keyString = key.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----",
                "");
        byte[] keyData = Base64.getDecoder().decode(keyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        logger.debug("[{}] Miniserver public key: {}", debugId, publicKey);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.PUBLIC_KEY, publicKey);
        logger.debug("[{}] Initialized RSA public key cipher", debugId);
        return cipher;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeySpecException e) {
        setError(LxOfflineReason.INTERNAL_ERROR, "Exception enabling RSA cipher: " + e.getMessage());
        return null;
    }
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Derives the public key from either a DSA or RSA private key.
 * /*  w  ww.j a  v a  2  s .  c om*/
 * @param key the private key to derive the public key from
 * 
 * @return the derived public key
 * 
 * @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the
 *             public key
 */
public static PublicKey derivePublicKey(PrivateKey key) throws KeyException {
    KeyFactory factory;
    if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        DSAParams keyParams = dsaKey.getParams();
        BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP());
        DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(),
                keyParams.getG());

        try {
            factory = KeyFactory.getInstance("DSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from DSA private key", e);
        }
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());

        try {
            factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from RSA private key", e);
        }
    } else {
        throw new KeyException("Private key was not a DSA or RSA key");
    }
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * PKCS8//from   w ww. j  a  v a  2  s  .c o  m
 * 
 * @param f
 * @param algom
 *            
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadPKCS8Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java

/**
 * Decodes the encoded password using the _privateKey
 * @param encodedPassword//w ww. j a v  a2s.  c  o m
 * @param _privateKey
 * @return The decoded password
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
private String decodeHeadlessChallenge(String encodedPassword, File _privateKey)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    final String RSA = "RSA";
    final String ASCII = "US-ASCII";

    // Read private key from file
    FileInputStream fstream = new FileInputStream(_privateKey);
    byte[] sshPrivateKey = IOUtils.toByteArray(fstream);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(sshPrivateKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = kf.generatePrivate(keySpec);

    // Init RSA decrypter with private key
    Cipher decryptCipher = Cipher.getInstance(RSA);
    decryptCipher.init(2, privateKey);

    // Convert base 64 password string to raw bytes
    byte[] rawBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encodedPassword.getBytes(ASCII));

    // Decrypt the encoded raw bytes using decrypter
    byte[] decodedBytes = decryptCipher.doFinal(rawBytes);

    // Return decoded bytes as string
    return new String(decodedBytes, ASCII);
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Read a PKCS 8 format private key. */
private static PrivateKey readPrivateKey(InputStream file) throws IOException, GeneralSecurityException {
    final DataInputStream input = new DataInputStream(file);
    try {/* w ww .  jav  a 2s . co  m*/
        byte[] bytes = new byte[10000];
        int nBytesTotal = 0, nBytes;
        while ((nBytes = input.read(bytes, nBytesTotal, 10000 - nBytesTotal)) != -1) {
            nBytesTotal += nBytes;
        }

        final byte[] bytes2 = new byte[nBytesTotal];
        System.arraycopy(bytes, 0, bytes2, 0, nBytesTotal);
        bytes = bytes2;

        KeySpec spec = decryptPrivateKey(bytes);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        try {
            return KeyFactory.getInstance("RSA").generatePrivate(spec);
        } catch (final InvalidKeySpecException ex) {
            return KeyFactory.getInstance("DSA").generatePrivate(spec);
        }
    } finally {
        input.close();
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarAddDeviceHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*w  ww . j a va2s . c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAsteriskSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAsteriskSchemaPooledObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFAsteriskSMWarLoginHtml");
            return;
        }
    }

    CFSecurityAuthorization auth = schemaObj.getAuthorization();
    if (auth == null) {
        response.sendRedirect("CFAsteriskSMWarLoginHtml");
        return;
    }

    ICFSecuritySecUserObj secUser = null;
    ICFSecurityClusterObj secCluster = null;
    String clusterDescription = "";

    ICFAsteriskSchema dbSchema = null;
    try {
        dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();

        secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId());

        secCluster = schemaObj.getClusterTableObj().readClusterByIdIdx(auth.getSecClusterId());
        if (secCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "secCluster");
        }
        clusterDescription = secCluster.getRequiredDescription();

        String deviceName = request.getParameter("DeviceName");
        if ((deviceName == null) || (deviceName.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecuritySecDeviceObj secDev = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(secUser.getRequiredSecUserId(), deviceName);
        if (secDev != null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name \"" + deviceName + "\" already in use.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        String publicKey = request.getParameter("PublicKey");
        if ((publicKey == null) || (publicKey.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        byte wrapped[] = Base64.decodeBase64(publicKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (kf == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf");
        }

        PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec);
        if (decodedPublicKey == null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecurityClusterObj systemCluster = schemaObj.getClusterTableObj()
                .readClusterByUDomainNameIdx("system");
        ICFSecurityTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFSecuritySecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFSecurityAuthorization secAuth = new CFSecurityAuthorization();
        secAuth.setSecCluster(systemCluster);
        secAuth.setSecTenant(systemTenant);
        secAuth.setSecSession(systemSession);
        schemaObj.setAuthorization(secAuth);

        secDev = schemaObj.getSecDeviceTableObj().newInstance();
        ICFSecuritySecDeviceEditObj editDev = secDev.beginEdit();
        editDev.setRequiredContainerSecUser(secUser);
        editDev.setRequiredDevName(deviceName);
        editDev.setOptionalPubKey(publicKey);
        secDev = editDev.create();
        editDev.endEdit();

        if (null == secUser.getOptionalLookupDefDev()) {
            ICFSecuritySecUserEditObj editSecUser = secUser.beginEdit();
            editSecUser.setOptionalLookupDefDev(secDev);
            editSecUser.update();
            editSecUser.endEdit();
        }

        editSystemSession = (ICFSecuritySecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setOptionalFinish(Calendar.getInstance());
        editSystemSession.update();
        editSystemSession.endEdit();

        schemaObj.commit();

        schemaObj.setAuthorization(auth);

        response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");

    } catch (InvalidKeySpecException e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key.");
        out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress()
                + "</H2>");
        out.println("<p>");
        out.println("<table style=\"width:90%\">");
        out.println(
                "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
        out.println(
                "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
        out.println("</table>");
        out.println(
                "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        schemaObj.setAuthorization(auth);
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:org.opendatakit.survey.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this row.
 * //from   w  ww .j  a va 2  s. c om
 * @param appName
 * @param tableId
 * @param xmlBase64RsaPublicKey
 * @param instanceId
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(String appName, String tableId,
        String xmlBase64RsaPublicKey, String instanceId) {

    // fetch the form information
    String base64RsaPublicKey = xmlBase64RsaPublicKey;
    PublicKey pk;
    Base64Wrapper wrapper;

    if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
        return null; // this is legitimately not an encrypted form
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceId == null) {
        WebLogger.getLogger(appName).e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    int version = android.os.Build.VERSION.SDK_INT;
    if (version < 8) {
        WebLogger.getLogger(appName).e(t, "Phone does not support encryption.");
        return null; // save unencrypted
    }

    // this constructor will throw an exception if we are not
    // running on version 8 or above (if Base64 is not found).
    try {
        wrapper = new Base64Wrapper();
    } catch (ClassNotFoundException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not have Base64 class but API level is " + version);
        WebLogger.getLogger(appName).printStackTrace(e);
        return null; // save unencrypted
    }

    // OK -- Base64 decode (requires API Version 8 or higher)
    byte[] publicKey = wrapper.decode(base64RsaPublicKey);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(RSA_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not support RSA encryption.");
        WebLogger.getLogger(appName).printStackTrace(e);
        return null;
    }
    try {
        pk = kf.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t, "Invalid RSA public key.");
        return null;
    }
    return new EncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId, pk, wrapper);
}

From source file:com.trsst.Common.java

/**
 * Converts a X509-encoded EC key to a PublicKey.
 *//*w  ww  .j a va  2s  .c o  m*/
public static PublicKey toPublicKeyFromX509(String stored) throws GeneralSecurityException {
    KeyFactory factory = KeyFactory.getInstance("EC");
    byte[] data = Base64.decodeBase64(stored);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    return factory.generatePublic(spec);

}