Example usage for javax.crypto Cipher PUBLIC_KEY

List of usage examples for javax.crypto Cipher PUBLIC_KEY

Introduction

In this page you can find the example usage for javax.crypto Cipher PUBLIC_KEY.

Prototype

int PUBLIC_KEY

To view the source code for javax.crypto Cipher PUBLIC_KEY.

Click Source Link

Document

Constant used to indicate the to-be-unwrapped key is a "public key".

Usage

From source file:net.sourceforge.msscodefactory.cfensyntax.v2_2.CFEnSyntaxSMWar.CFEnSyntaxSMWarAddDeviceHtml.java

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

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

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

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

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

    ICFEnSyntaxSchema dbSchema = null;
    try {
        dbSchema = CFEnSyntaxSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();

        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=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            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='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFEnSyntaxSecDeviceObj 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=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            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='CFEnSyntaxSMWarSecurityMainHtml'\">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=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            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='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

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

        Cipher cipher = Cipher.getInstance("AES");
        if (cipher == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "cipher");
        }

        Key key = cipher.unwrap(wrapped, "AES", Cipher.PUBLIC_KEY);
        if ((key == null) || (!(key instanceof PublicKey))) {
            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=\"CFEnSyntaxSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be a valid Client AES 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='CFEnSyntaxSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFEnSyntaxClusterObj systemCluster = schemaObj.getClusterTableObj()
                .readClusterByUDomainNameIdx("system");
        ICFEnSyntaxTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFEnSyntaxSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        ICFEnSyntaxSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFEnSyntaxSecSessionEditObj editSystemSession = (ICFEnSyntaxSecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

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

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

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

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

        schemaObj.commit();

        schemaObj.setAuthorization(auth);

        response.sendRedirect("CFEnSyntaxSMWarSecurityMainHtml");

    } catch (InvalidKeyException 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=\"CFEnSyntaxSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<p style=\"text-align:center\">Public Key must be a valid Client AES 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='CFEnSyntaxSMWarSecurityMainHtml'\">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 (NoSuchPaddingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchPaddingException -- " + 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);
            CFEnSyntaxSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

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

private Cipher getRsaCipher(String key) {
    try {/*from w w  w .ja  va  2 s .c  o  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.opentravel.schemacompiler.security.PasswordHelper.java

/**
 * Returns an encryption cipher that is based on the public encryption key file located on the
 * application's classpath./*from  w w  w  .  j a v a 2s.c  om*/
 * 
 * @return Cipher
 * @throws GeneralSecurityException
 *             thrown if encryption key is not valid
 * @throws IOException
 *             thrown if the contents of the public key file cannot be loaded
 */
private static Cipher loadEncryptionCipher() throws GeneralSecurityException, IOException {
    BigInteger[] keyComponents = loadKeyFile(PUBLIC_KEYFILE);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(keyComponents[0], keyComponents[1]);
    KeyFactory factory = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
    PublicKey publicKey = factory.generatePublic(keySpec);
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION);

    cipher.init(Cipher.PUBLIC_KEY, publicKey);
    return cipher;
}