Example usage for java.security.spec InvalidKeySpecException getMessage

List of usage examples for java.security.spec InvalidKeySpecException getMessage

Introduction

In this page you can find the example usage for java.security.spec InvalidKeySpecException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.kitodo.data.encryption.DesEncrypter.java

private void initialise(String passPhrase) {
    int iterationCount = 19;

    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), defaultSalt, iterationCount);

    try {/*  w  w w.jav  a 2  s  . c  om*/
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        encryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        decryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(defaultSalt, iterationCount);
        encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
        decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
    } catch (InvalidKeySpecException e) {
        logger.info("Catched InvalidKeySpecException with message: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.info("Catched NoSuchAlgorithmException with message: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        logger.info("Catched NoSuchPaddingException with message: " + e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        logger.info("Catched InvalidAlgorithmParameterException with message: " + e.getMessage());
    } catch (InvalidKeyException e) {
        logger.info("Catched InvalidKeyException with message: " + e.getMessage());
    }
}

From source file:org.kitodo.production.security.password.SecurityPasswordEncoder.java

private void initialize(String passPhrase) {
    int iterationCount = 19;
    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), defaultSalt, iterationCount);
    try {/*www.  j a  v  a 2s.  com*/
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        encryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        decryptionCipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(defaultSalt, iterationCount);
        encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
        decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
    } catch (InvalidKeySpecException e) {
        logger.info("Catched InvalidKeySpecException with message: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        logger.info("Catched NoSuchAlgorithmException with message: " + e.getMessage());
    } catch (NoSuchPaddingException e) {
        logger.info("Catched NoSuchPaddingException with message: " + e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        logger.info("Catched InvalidAlgorithmParameterException with message: " + e.getMessage());
    } catch (InvalidKeyException e) {
        logger.info("Catched InvalidKeyException with message: " + e.getMessage());
    }
}

From source file:com.tasktop.c2c.server.internal.profile.crypto.Rfc4716PublicKeyReader.java

/**
 * read a public key from the given text
 * //from  w w  w.  j  av  a2s  .c  om
 * @param keySpec
 *            the key specification.
 * @return the key or null if no key was found
 */
public SshPublicKey readPublicKey(String keySpec) {
    BufferedReader reader = new BufferedReader(new StringReader(keySpec));
    String line;
    SshPublicKey key = null;
    boolean endFound = false;
    boolean dataStarted = false;
    boolean continueHeader = false;
    String base64Data = "";
    try {
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            // skip blank lines. They shouldn't really be in there, but if they are we can ignore them.
            if (line.length() != 0) {
                if (key == null) {
                    if (line.equals(START_MARKER)) {
                        key = new SshPublicKey();
                    }
                } else {
                    if (line.equals(END_MARKER)) {
                        endFound = true;
                        break;
                    } else if (!dataStarted && (continueHeader || HEADER_PATTERN.matcher(line).matches())) {
                        // skip headers
                        continueHeader = line.endsWith("\"");
                    } else {
                        dataStarted = true;

                        base64Data += line;
                    }
                }
            }
        }
        if (!endFound) {
            key = null;
        } else {
            if (base64Data.length() > 0) {
                byte[] keyData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data));

                Rfc4253Reader keyReader = new Rfc4253Reader(keyData, 0);
                String algorithm = keyReader.readString();
                if ("ssh-rsa".equals(algorithm)) {
                    key.setAlgorithm("RSA");

                    BigInteger exponent = keyReader.readMpint();
                    BigInteger modulus = keyReader.readMpint();

                    try {
                        KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
                        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

                        byte[] encoded = publicKey.getEncoded();

                        key.setKeyData(encoded);

                    } catch (InvalidKeySpecException t) {
                        getLogger().warn("Invalid key spec: " + t.getMessage(), t);
                    } catch (NoSuchAlgorithmException t) {
                        getLogger().warn("Invalid algorithm: " + t.getMessage(), t);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (key == null || key.getAlgorithm() == null || key.getKeyData() == null) {
        key = null;
    }
    return key;
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#returnKeys(java.lang.String)
 *//*from   w  w w  .j a  va2s . com*/
public synchronized KeyPair returnKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#returnKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    KeyPair keyPair = null;
    InputStream pubStream = null;
    InputStream privStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            throw new KeyManagementException("Configured key directory does not exist and unable to create it");
        }

        File publicFile = FileUtils
                .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);
        File privateFile = FileUtils
                .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

        if ((publicFile.exists()) && (privateFile.exists())) {
            privStream = new FileInputStream(privateFile);
            byte[] privKeyBytes = IOUtils.toByteArray(privStream);

            pubStream = new FileInputStream(publicFile);
            byte[] pubKeyBytes = IOUtils.toByteArray(pubStream);

            // files exist
            KeyFactory keyFactory = KeyFactory.getInstance(keyConfig.getKeyAlgorithm());

            // generate private key
            PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privKeyBytes);
            PrivateKey privKey = keyFactory.generatePrivate(privateSpec);

            // generate pubkey
            X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(pubKeyBytes);
            PublicKey pubKey = keyFactory.generatePublic(publicSpec);

            // make the keypair
            keyPair = new KeyPair(pubKey, privKey);
        } else {
            // files dont exist
            throw new KeyManagementException("Failed to locate user keys");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeySpecException iksx) {
        throw new KeyManagementException(iksx.getMessage(), iksx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (privStream != null) {
            IOUtils.closeQuietly(privStream);
        }

        if (pubStream != null) {
            IOUtils.closeQuietly(pubStream);
        }
    }

    return keyPair;
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */// w  ww.j  a va  2  s  .  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:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarAddDeviceHtml.java

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

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

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

    ICFAstSecUserObj secUser = null;
    ICFAstClusterObj secCluster = null;
    String clusterDescription = "";

    ICFAstSchema dbSchema = null;
    try {
        dbSchema = CFAstSchemaPool.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=\"CFAstSMWarAddDeviceHtml\">");
            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='CFAstSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

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

        ICFAstClusterObj systemCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system");
        ICFAstTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFAstSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

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

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

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

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

        schemaObj.commit();

        schemaObj.setAuthorization(auth);

        response.sendRedirect("CFAstSMWarSecurityMainHtml");

    } 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=\"CFAstSMWarAddDeviceHtml\">");
        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='CFAstSMWarSecurityMainHtml'\">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);
            CFAstSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:org.ejbca.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage, String provider)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchProviderException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be 
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;/*  w  w w .  j av  a2  s .  co  m*/
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);
    certgen.setSerialNumber(new java.math.BigInteger(serno).abs());
    certgen.setNotBefore(firstDate);
    certgen.setNotAfter(lastDate);
    certgen.setSignatureAlgorithm(sigAlg);
    certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));
    certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));
    certgen.setPublicKey(publicKey);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku);
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);

            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                    (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(publicKey.getEncoded()))
                            .readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certgen.addExtension(X509Extensions.CertificatePolicies.getId(), false, seq);
    }

    X509Certificate selfcert = certgen.generate(privKey, provider);

    return selfcert;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWS.java

/** Method that gets the public key from a CV certificate, possibly enriching it with domain parameters from the CVCA certificate if it is an EC public key.
 * @param ejbhelper/*from   www . j  av a  2s .c  om*/
 * @param admin
 * @param cert
 * @return
 * @throws CADoesntExistsException
 * @throws AuthorizationDeniedException 
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
private PublicKey getCVPublicKey(AuthenticationToken admin, java.security.cert.Certificate cert)
        throws CADoesntExistsException, AuthorizationDeniedException {
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof PublicKeyEC) {
        // The public key of IS and DV certificate do not have any EC parameters so we have to do some magic to get a complete EC public key
        // First get to the CVCA certificate that has the parameters
        CAInfo info = caSession.getCAInfo(admin, CertTools.getIssuerDN(cert).hashCode());
        Collection<java.security.cert.Certificate> cacerts = info.getCertificateChain();
        if (cacerts != null) {
            log.debug("Found CA certificate chain of length: " + cacerts.size());
            // Get the last cert in the chain, it is the CVCA cert
            Iterator<java.security.cert.Certificate> i = cacerts.iterator();
            java.security.cert.Certificate cvcacert = null;
            while (i.hasNext()) {
                cvcacert = i.next();
            }
            if (cvcacert != null) {
                // Do the magic adding of parameters, if they don't exist in the pk
                try {
                    pk = KeyTools.getECPublicKeyWithParams(pk, cvcacert.getPublicKey());
                } catch (InvalidKeySpecException e) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                            CertTools.getSubjectDN(cert), e.getMessage());
                    log.warn(msg, e);
                }
            }
        }
    }
    return pk;
}

From source file:org.cesecore.util.CertTools.java

public static X509Certificate genSelfCertForPurpose(String dn, long validity, String policyId,
        PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, int keyusage,
        Date privateKeyNotBefore, Date privateKeyNotAfter, String provider, boolean ldapOrder,
        List<Extension> additionalExtensions)
        throws CertificateParsingException, IOException, OperatorCreationException {
    // Create self signed certificate
    Date firstDate = new Date();

    // Set back startdate ten minutes to avoid some problems with wrongly set clocks.
    firstDate.setTime(firstDate.getTime() - (10 * 60 * 1000));

    Date lastDate = new Date();

    // validity in days = validity*24*60*60*1000 milliseconds
    lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//  www.j  ava 2  s  .  c  o m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            log.error("Error creating RSAPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("RSA was not a known algorithm", e);
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            final String algo = ecpk.getAlgorithm();
            if (algo.equals(AlgorithmConstants.KEYALGORITHM_ECGOST3410)) {
                try {
                    publicKey = KeyFactory.getInstance("ECGOST3410").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECGOST3410 was not a known algorithm", e);
                }
            } else if (algo.equals(AlgorithmConstants.KEYALGORITHM_DSTU4145)) {
                try {
                    publicKey = KeyFactory.getInstance("DSTU4145").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("DSTU4145 was not a known algorithm", e);
                }
            } else {
                try {
                    publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("EC was not a known algorithm", e);
                }
            }
        } catch (InvalidKeySpecException e) {
            log.error("Error creating ECPublicKey from spec: ", e);
            publicKey = pubKey;
        } catch (NullPointerException e) {
            log.debug("NullPointerException, probably it is implicitlyCA generated keys: " + e.getMessage());
            publicKey = pubKey;
        }
    } else {
        log.debug("Not converting key of class. " + pubKey.getClass().getName());
        publicKey = pubKey;
    }

    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random;
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("SHA1PRNG was not a known algorithm", e);
    }
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    SubjectPublicKeyInfo pkinfo;
    try {
        pkinfo = new SubjectPublicKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    } catch (IOException e) {
        throw new IllegalArgumentException("Provided public key could not be read to ASN1Primitive", e);
    }
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(dn, ldapOrder), new BigInteger(serno).abs(), firstDate, lastDate,
            CertTools.stringToBcX500Name(dn, ldapOrder), pkinfo);

    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA || keyusage != 0) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }

    if ((privateKeyNotBefore != null) || (privateKeyNotAfter != null)) {
        final ASN1EncodableVector v = new ASN1EncodableVector();
        if (privateKeyNotBefore != null) {
            v.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(privateKeyNotBefore)));
        }
        if (privateKeyNotAfter != null) {
            v.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(privateKeyNotAfter)));
        }
        certbuilder.addExtension(Extension.privateKeyUsagePeriod, false, new DERSequence(v));
    }

    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {

            ASN1InputStream sAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream aAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) sAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) aAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                sAsn1InputStream.close();
                aAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }

    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    // Add any additional
    if (additionalExtensions != null) {
        for (final Extension extension : additionalExtensions) {
            certbuilder.addExtension(extension.getExtnId(), extension.isCritical(), extension.getParsedValue());
        }
    }
    final ContentSigner signer = new BufferingContentSigner(
            new JcaContentSignerBuilder(sigAlg).setProvider(provider).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void receiveResponse(AuthenticationToken authenticationToken, int caid, ResponseMessage responsemessage,
        Collection<?> cachain, String nextKeyAlias)
        throws AuthorizationDeniedException, CertPathValidatorException, EjbcaException, CesecoreException {
    if (log.isTraceEnabled()) {
        log.trace(">receiveResponse: " + caid);
    }/*from www .j a v a  2  s  .  c o m*/
    if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp",
                Integer.valueOf(caid));
        auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
    }
    try {
        final CA ca = caSession.getCAForEdit(authenticationToken, caid);
        if (!(responsemessage instanceof X509ResponseMessage)) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg",
                    responsemessage != null ? responsemessage.getClass().getName() : "null");
            log.info(msg);
            throw new EjbcaException(msg);
        }
        final Certificate cacert = ((X509ResponseMessage) responsemessage).getCertificate();
        // Receiving a certificate for an internal CA will transform it into an externally signed CA
        if (ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA) {
            ca.setSignedBy(CAInfo.SIGNEDBYEXTERNALCA);
        }
        // Check that CA DN is equal to the certificate response.
        if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn",
                    CertTools.getSubjectDN(cacert), ca.getSubjectDN());
            log.info(msg);
            throw new EjbcaException(msg);
        }
        List<Certificate> tmpchain = new ArrayList<Certificate>();
        tmpchain.add(cacert);

        Collection<Certificate> reqchain = null;
        if (cachain != null && cachain.size() > 0) {
            //  1. If we have a chain given as parameter, we will use that.
            reqchain = CertTools.createCertChain(cachain);
            log.debug("Using CA certificate chain from parameter of size: " + reqchain.size());
        } else {
            // 2. If no parameter is given we assume that the request chain was stored when the request was created.
            reqchain = ca.getRequestCertificateChain();
            if (reqchain == null) {
                // 3. Lastly, if that failed we'll check if the certificate chain in it's entirety already exists in the database. 
                reqchain = new ArrayList<Certificate>();
                Certificate issuer = certificateStoreSession
                        .findLatestX509CertificateBySubject(CertTools.getIssuerDN(cacert));
                if (issuer != null) {
                    reqchain.add(issuer);
                    while (!CertTools.isSelfSigned(issuer)) {
                        issuer = certificateStoreSession
                                .findLatestX509CertificateBySubject(CertTools.getIssuerDN(issuer));
                        if (issuer != null) {
                            reqchain.add(issuer);
                        } else {
                            String msg = intres.getLocalizedMessage("caadmin.errorincompleterequestchain", caid,
                                    ca.getSubjectDN());
                            log.info(msg);
                            throw new CertPathValidatorException(msg);
                        }
                    }
                }
                if (reqchain.size() == 0) {
                    String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid,
                            ca.getSubjectDN());
                    log.info(msg);
                    throw new CertPathValidatorException(msg);
                }

            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using pre-stored CA certificate chain.");
                }
            }
        }
        log.debug("Picked up request certificate chain of size: " + reqchain.size());
        tmpchain.addAll(reqchain);
        final List<Certificate> chain = CertTools.createCertChain(tmpchain);
        log.debug("Storing certificate chain of size: " + chain.size());
        // Before importing the certificate we want to make sure that the public key matches the CAs private key
        PublicKey caCertPublicKey = cacert.getPublicKey();
        // If it is a DV certificate signed by a CVCA, enrich the public key for EC parameters from the CVCA's certificate
        if (StringUtils.equals(cacert.getType(), "CVC")) {
            if (caCertPublicKey.getAlgorithm().equals("ECDSA")) {
                CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert;
                try {
                    if (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate()
                            .getAuthorizationField().getAuthRole().isDV()) {
                        log.debug("Enriching DV public key with EC parameters from CVCA");
                        Certificate cvcacert = (Certificate) reqchain.iterator().next();
                        caCertPublicKey = KeyTools.getECPublicKeyWithParams(caCertPublicKey,
                                cvcacert.getPublicKey());
                    }
                } catch (InvalidKeySpecException e) {
                    log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...",
                            e);
                } catch (NoSuchFieldException e) {
                    log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e);
                }
            } else {
                log.debug("Key is not ECDSA, don't try to enrich with EC parameters.");
            }
        } else {
            log.debug("Cert is not CVC, no need to enrich with EC parameters.");
        }

        final CAToken catoken = ca.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId());
        boolean activatedNextSignKey = false;
        if (nextKeyAlias != null) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("SubjectKeyId for CA cert public key: " + new String(
                            Hex.encode(KeyTools.createSubjectKeyId(caCertPublicKey).getKeyIdentifier())));
                    log.debug("SubjectKeyId for CA next public key: " + new String(Hex.encode(KeyTools
                            .createSubjectKeyId(cryptoToken.getPublicKey(nextKeyAlias)).getKeyIdentifier())));
                }
                KeyTools.testKey(cryptoToken.getPrivateKey(nextKeyAlias), caCertPublicKey,
                        cryptoToken.getSignProviderName());
            } catch (InvalidKeyException e) {
                throw new EjbcaException(ErrorCode.INVALID_KEY, e);
            }
            catoken.setNextCertSignKey(nextKeyAlias);
            catoken.activateNextSignKey();
            activatedNextSignKey = true;
        } else {
            // Since we don't specified the nextSignKey, we will just try the current or next CA sign key
            try {
                KeyTools.testKey(
                        cryptoToken.getPrivateKey(
                                catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)),
                        caCertPublicKey, cryptoToken.getSignProviderName());
            } catch (Exception e1) {
                log.debug(
                        "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT...");
                if (e1 instanceof InvalidKeyException) {
                    log.trace(e1);
                } else {
                    // If it's not invalid key, we want to see more of the error
                    log.debug("Error: ", e1);
                }
                try {
                    KeyTools.testKey(
                            cryptoToken.getPrivateKey(
                                    catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT)),
                            caCertPublicKey, cryptoToken.getSignProviderName());
                    // This was OK, so we must also activate the next signing key when importing this certificate
                    catoken.activateNextSignKey();
                    activatedNextSignKey = true;
                } catch (Exception e2) {
                    log.debug(
                            "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up.");
                    if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) {
                        log.trace(e2);
                    } else {
                        // If it's not invalid key or missing authentication code, we want to see more of the error
                        log.debug("Error: ", e2);
                    }
                    throw new EjbcaException(ErrorCode.INVALID_KEY, e2);
                }
            }
        }
        if (activatedNextSignKey) {
            // Activated the next signing key(s) so generate audit log
            final Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", intres.getLocalizedMessage("catoken.activatednextkey", caid));
            details.put("certSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
            details.put("crlSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
            details.put("sequence", catoken.getKeySequence());
            auditSession.log(EventTypes.CA_KEYACTIVATE, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), String.valueOf(caid), null, null, details);
        }
        ca.setCAToken(catoken);
        ca.setCertificateChain(chain);

        // Set status to active, so we can sign certificates for the external services below.
        ca.setStatus(CAConstants.CA_ACTIVE);

        // activate External CA Services
        for (int type : ca.getExternalCAServiceTypes()) {
            try {
                ca.initExtendedService(cryptoToken, type, ca);
                final ExtendedCAServiceInfo info = ca.getExtendedCAServiceInfo(type);
                if (info instanceof BaseSigningCAServiceInfo) {
                    // Publish the extended service certificate, but only for active services
                    if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) {
                        final List<Certificate> extcacertificate = new ArrayList<Certificate>();
                        extcacertificate.add(((BaseSigningCAServiceInfo) info).getCertificatePath().get(0));
                        publishCACertificate(authenticationToken, extcacertificate, ca.getCRLPublishers(),
                                ca.getSubjectDN());
                    }
                }
            } catch (Exception fe) {
                final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcreatecaservice",
                        Integer.valueOf(caid));
                auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                        authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
                throw new EJBException(fe);
            }
        }
        // Set expire time
        ca.setExpireTime(CertTools.getNotAfter(cacert));
        // Save CA
        caSession.editCA(authenticationToken, ca, true);
        // Publish CA Certificate
        publishCACertificate(authenticationToken, chain, ca.getCRLPublishers(), ca.getSubjectDN());
        // Create initial CRL
        publishingCrlSession.forceCRL(authenticationToken, caid);
        publishingCrlSession.forceDeltaCRL(authenticationToken, caid);
        // All OK
        String detailsMsg = intres.getLocalizedMessage("caadmin.certrespreceived", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
    } catch (CryptoTokenOfflineException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CADoesntExistsException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CertificateEncodingException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (CertificateException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (NoSuchProviderException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    }
    if (log.isTraceEnabled()) {
        log.trace("<receiveResponse: " + caid);
    }
}