Example usage for java.security InvalidKeyException getMessage

List of usage examples for java.security InvalidKeyException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java

@Override
public boolean verify(byte[] pemCertificate, String signatureAlgorithm, byte[] signature, byte[] plainText)
        throws CryptoException {
    boolean isVerified = false;

    if (plainText == null || signature == null || pemCertificate == null) {
        return false;
    }//from   w  ww  .j  av  a 2s  . com

    if (config.extraLogLevel(10)) {
        if (null != diagnosticFileDumper) {
            StringBuilder sb = new StringBuilder(10000);
            sb.append("plaintext in hex: ").append(DatatypeConverter.printHexBinary(plainText)).append("\n")
                    .append("signature in hex: " + DatatypeConverter.printHexBinary(signature)).append("\n")
                    .append("PEM cert in hex: " + DatatypeConverter.printHexBinary(pemCertificate));
            logger.trace("verify :  " + diagnosticFileDumper.createDiagnosticFile(sb.toString()));
        }
    }

    try {

        X509Certificate certificate = getX509Certificate(pemCertificate);

        if (certificate != null) {

            isVerified = validateCertificate(certificate);
            if (isVerified) { // only proceed if cert is trusted

                Signature sig = Signature.getInstance(signatureAlgorithm);
                sig.initVerify(certificate);
                sig.update(plainText);
                isVerified = sig.verify(signature);
            }
        }
    } catch (InvalidKeyException e) {
        CryptoException ex = new CryptoException("Cannot verify signature. Error is: " + e.getMessage()
                + "\r\nCertificate: " + DatatypeConverter.printHexBinary(pemCertificate), e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (NoSuchAlgorithmException | SignatureException e) {
        CryptoException ex = new CryptoException(
                "Cannot verify. Signature algorithm is invalid. Error is: " + e.getMessage(), e);
        logger.error(ex.getMessage(), ex);
        throw ex;
    }

    return isVerified;
}

From source file:org.woltage.irssiconnectbot.ConsoleActivity.java

/**
 * @param pubkey/*from ww w. j av a  2 s  .co  m*/
 */
private void setupPublicKey(PubkeyBean pubkey) {
    Log.d(TAG, "setupPublicKey, pubKey=" + pubkey.getNickname());

    try {
        String openSSHPubkey;
        if (PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) {
            openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(new String(pubkey.getPrivateKey()),
                    pubkey.getNickname());
        } else {
            PublicKey pk = pubkey.getPublicKey();
            openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname());
        }

        final TerminalView terminal = (TerminalView) findCurrentView(R.id.console_flip);
        terminal.bridge
                .injectString("mkdir ~/.ssh -pm 700 ; echo " + openSSHPubkey + " >> ~/.ssh/authorized_keys");
    } catch (InvalidKeyException e) {
        Log.e(TAG, e.getMessage(), e);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
    }

}

From source file:eu.europa.esig.dss.x509.CertificateToken.java

@Override
public boolean isSignedBy(final CertificateToken issuerToken) {

    signatureValid = false;//from  w  w  w. j  a  va  2 s  .co  m
    signatureInvalidityReason = "";
    try {

        final PublicKey publicKey = issuerToken.getCertificate().getPublicKey();
        x509Certificate.verify(publicKey);
        signatureValid = true;
        if (!isSelfSigned()) {
            this.issuerToken = issuerToken;
        }
    } catch (InvalidKeyException e) {

        signatureInvalidityReason = "InvalidKeyException - on incorrect key.";
    } catch (CertificateException e) {

        signatureInvalidityReason = "CertificateException -  on encoding errors.";
    } catch (NoSuchAlgorithmException e) {

        signatureInvalidityReason = "NoSuchAlgorithmException - on unsupported signature algorithms.";
    } catch (SignatureException e) {

        signatureInvalidityReason = "SignatureException - on signature errors.";
        if (LOG.isDebugEnabled()) {
            LOG.debug("ERROR: {} is not signed by {}: {}",
                    new Object[] { getAbbreviation(), issuerToken.getAbbreviation(), e.getMessage() });
        }
    } catch (NoSuchProviderException e) { // if there's no default provider.
        throw new DSSException(e);
    }
    return signatureValid;
}

From source file:be.fedict.eid.idp.sp.protocol.saml2.artifact.ArtifactServiceClient.java

/**
 * If set, unilateral TLS authentication will occur, verifying the server
 * {@link X509Certificate} specified against the {@link PublicKey}.
 * /*from   w  w  w .  j  a v a2s . c o m*/
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {

    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put(JAXWSProperties.SSL_SOCKET_FACTORY, sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:be.fedict.trust.client.XKMS2Client.java

/**
 * If set, unilateral TLS authentication will occurs, verifying the server
 * {@link X509Certificate} specified {@link PublicKey}.
 * <p/>/*from  w w w.  j av a2 s .co m*/
 * WARNING: only works when using the JAX-WS RI.
 * 
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {
    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                LOG.warn("not performing any server certificate validation at all");
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put("com.sun.xml.ws.transport.https.client.SSLSocketFactory",
                sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */// w  ww.  j  a v  a  2s . c o 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.ejbca.core.protocol.ws.EjbcaWS.java

/**
 * @see org.ejbca.core.protocol.ws.common.IEjbcaWS#cvcRequest
 *///from   www  .  jav a 2 s  . c o  m
public List<Certificate> cvcRequest(String username, String password, String cvcreq)
        throws CADoesntExistsException, AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile,
        NotFoundException, EjbcaException, CesecoreException, ApprovalException, WaitingForApprovalException,
        SignRequestException, CertificateExpiredException {
    log.trace(">cvcRequest");
    EjbcaWSHelper ejbhelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession, caSession,
            certificateProfileSession, certificateStoreSession, endEntityAccessSession, endEntityProfileSession,
            hardTokenSession, endEntityManagementSession, webAuthenticationSession,
            cryptoTokenManagementSession);
    AuthenticationToken admin = ejbhelper.getAdmin();

    // If password is empty we can generate a big random one to use instead
    if (StringUtils.isEmpty(password)) {
        AllPrintableCharPasswordGenerator gen = new AllPrintableCharPasswordGenerator();
        password = gen.getNewPassword(15, 20);
        log.debug("Using a long random password");
    }
    // get and old status that we can remember so we can reset status if this fails in the last step
    int olduserStatus = EndEntityConstants.STATUS_GENERATED;
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    logAdminName(admin, logger);
    try {
        EndEntityInformation user = endEntityAccessSession.findUser(admin, username);
        // See if this user already exists.
        // We allow renewal of certificates for IS's that are not revoked
        // In that case look for it's last old certificate and try to authenticate the request using an outer signature.
        // If this verification is correct, set status to NEW and continue process the request.
        if (user != null) {
            olduserStatus = user.getStatus();
            // If user is revoked, we can not proceed
            if ((olduserStatus == EndEntityConstants.STATUS_REVOKED)
                    || (olduserStatus == EndEntityConstants.STATUS_HISTORICAL)) {
                throw new AuthorizationDeniedException("User '" + username + "' is revoked.");
            }
            CVCObject parsedObject = CertificateParser.parseCVCObject(Base64.decode(cvcreq.getBytes()));
            if (parsedObject instanceof CVCAuthenticatedRequest) {
                log.debug(
                        "Received an authenticated request, could be an initial DV request signed by CVCA or a renewal for DV or IS.");
                CVCAuthenticatedRequest authreq = (CVCAuthenticatedRequest) parsedObject;
                CVCPublicKey cvcKey = authreq.getRequest().getCertificateBody().getPublicKey();
                String algorithm = AlgorithmUtil.getAlgorithmName(cvcKey.getObjectIdentifier());
                log.debug("Received request has a public key with algorithm: " + algorithm);
                HolderReferenceField holderRef = authreq.getRequest().getCertificateBody().getHolderReference();
                CAReferenceField caRef = authreq.getAuthorityReference();

                // Check to see that the inner signature does not also verify using an old certificate
                // because that means the same keys were used, and that is not allowed according to the EU policy
                // This must be done whether it is signed by CVCA or a renewal request
                Collection<java.security.cert.Certificate> oldcerts = certificateStoreSession
                        .findCertificatesByUsername(username);
                if (oldcerts != null) {
                    log.debug("Found " + oldcerts.size() + " old certificates for user " + username);
                    Iterator<java.security.cert.Certificate> iterator = oldcerts.iterator();
                    while (iterator.hasNext()) {
                        java.security.cert.Certificate cert = iterator.next();
                        PublicKey pk = getCVPublicKey(admin, cert);
                        CVCertificate innerreq = authreq.getRequest();
                        checkInnerCollision(pk, innerreq, holderRef.getConcatenated()); // Throws AuthorizationDeniedException
                    }
                }

                boolean verifiedOuter = false; // So we can throw an error if we could not verify
                if (StringUtils.equals(holderRef.getMnemonic(), caRef.getMnemonic())
                        && StringUtils.equals(holderRef.getCountry(), caRef.getCountry())) {
                    log.debug(
                            "Authenticated request is self signed, we will try to verify it using user's old certificate.");
                    Collection<java.security.cert.Certificate> certs = certificateStoreSession
                            .findCertificatesByUsername(username);
                    // certs contains certificates ordered with last expire date first. Last expire date should be last issued cert
                    // We have to iterate over available user certificates, because we don't know which on signed the old one
                    // and cv certificates have very coarse grained validity periods so we can't really know which one is the latest one
                    // if 2 certificates are issued the same day.
                    if (certs != null) {
                        log.debug("Found " + certs.size() + " old certificates for user " + username);
                        Iterator<java.security.cert.Certificate> iterator = certs.iterator();
                        while (iterator.hasNext()) {
                            java.security.cert.Certificate cert = iterator.next();
                            try {
                                // Only allow renewal if the old certificate is valid
                                PublicKey pk = getCVPublicKey(admin, cert);
                                if (log.isDebugEnabled()) {
                                    log.debug(
                                            "Trying to verify the outer signature with an old certificate, fp: "
                                                    + CertTools.getFingerprintAsString(cert));
                                }
                                authreq.verify(pk);
                                log.debug("Verified outer signature");
                                // Yes we did it, we can move on to the next step because the outer signature was actually created with some old certificate
                                verifiedOuter = true;
                                if (ejbhelper.checkValidityAndSetUserPassword(admin, cert, username,
                                        password)) {
                                    // If we managed to verify the certificate we will break out of the loop                           
                                    break;
                                }

                                // If verification of outer signature fails because the signature is invalid we will break and deny the request...with a message
                            } catch (InvalidKeyException e) {
                                String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                        holderRef.getConcatenated(), e.getMessage());
                                log.warn(msg, e);
                            } catch (CertificateExpiredException e) { // thrown by checkValidityAndSetUserPassword
                                String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                        holderRef.getConcatenated(), e.getMessage());
                                // Only log this with DEBUG since it will be a common case that happens, nothing that should cause any alerts
                                log.debug(msg);
                                // This exception we want to throw on, because we want to give this error if there was a certificate suitable for
                                // verification, but it had expired. This is thrown by checkValidityAndSetUserPassword after the request has already been 
                                // verified using the public key of the certificate.
                                throw e;
                            } catch (CertificateException e) {
                                String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                        holderRef.getConcatenated(), e.getMessage());
                                log.warn(msg, e);
                            } catch (NoSuchAlgorithmException e) {
                                String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                        holderRef.getConcatenated(), e.getMessage());
                                log.info(msg, e);
                            } catch (NoSuchProviderException e) {
                                String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                        holderRef.getConcatenated(), e.getMessage());
                                log.warn(msg, e);
                            } catch (SignatureException e) {
                                // Failing to verify the outer signature will be normal, since we must try all old certificates
                                if (log.isDebugEnabled()) {
                                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                            holderRef.getConcatenated(), e.getMessage());
                                    log.debug(msg);
                                }
                            }
                        } // while (iterator.hasNext()) {
                          // if verification failed because the old cert was not yet valid, continue processing as usual, using the sent in username/password hoping the
                          // status is NEW and password is correct. If old certificate was expired a CertificateExpiredException is thrown above.

                    } // if (certs != null) {

                    // If there are no old certificate, continue processing as usual, using the sent in username/password hoping the
                    // status is NEW and password is correct.
                } else { // if (StringUtils.equals(holderRef, caRef))
                    // Subject and issuerDN is CN=Mnemonic,C=Country
                    String dn = "CN=" + caRef.getMnemonic() + ",C=" + caRef.getCountry();
                    log.debug(
                            "Authenticated request is not self signed, we will try to verify it using a CVCA certificate: "
                                    + dn);
                    try {
                        CAInfo info = caSession.getCAInfo(admin, CertTools.stringToBCDNString(dn).hashCode());
                        Collection<java.security.cert.Certificate> certs = info.getCertificateChain();
                        if (certs != null) {
                            log.debug("Found " + certs.size() + " certificates in chain for CA with DN: " + dn);
                            Iterator<java.security.cert.Certificate> iterator = certs.iterator();
                            if (iterator.hasNext()) {
                                // The CA certificate is first in chain
                                java.security.cert.Certificate cert = iterator.next();
                                if (log.isDebugEnabled()) {
                                    log.debug(
                                            "Trying to verify the outer signature with a CVCA certificate, fp: "
                                                    + CertTools.getFingerprintAsString(cert));
                                }
                                try {
                                    // The CVCA certificate always contains the full key parameters, no need to du any EC curve parameter magic here
                                    authreq.verify(cert.getPublicKey());
                                    log.debug("Verified outer signature");
                                    verifiedOuter = true;
                                    // Yes we did it, we can move on to the next step because the outer signature was actually created with some old certificate
                                    if (!ejbhelper.checkValidityAndSetUserPassword(admin, cert, username,
                                            password)) {
                                        // If the CA certificate was not valid, we are not happy                           
                                        String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                                holderRef.getConcatenated(),
                                                "CA certificate not valid for CA: " + info.getCAId());
                                        log.info(msg);
                                        throw new AuthorizationDeniedException(msg);
                                    }
                                } catch (InvalidKeyException e) {
                                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                            holderRef.getConcatenated(), e.getMessage());
                                    log.warn(msg, e);
                                } catch (CertificateException e) {
                                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                            holderRef.getConcatenated(), e.getMessage());
                                    log.warn(msg, e);
                                } catch (NoSuchAlgorithmException e) {
                                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                            holderRef.getConcatenated(), e.getMessage());
                                    log.warn(msg, e);
                                } catch (NoSuchProviderException e) {
                                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                            holderRef.getConcatenated(), e.getMessage());
                                    log.warn(msg, e);
                                } catch (SignatureException e) {
                                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                                            holderRef.getConcatenated(), e.getMessage());
                                    log.warn(msg, e);
                                }
                            }
                        } else {
                            log.info("No CA certificate found to authenticate request: " + dn);
                        }
                    } catch (CADoesntExistsException e) {
                        log.info("No CA found to authenticate request: " + dn);
                    }
                }
                // if verification failed because we could not verify the outer signature at all it is an error
                if (!verifiedOuter) {
                    String msg = intres.getLocalizedMessage("cvc.error.outersignature",
                            holderRef.getConcatenated(),
                            "No certificate found that could authenticate request");
                    log.info(msg);
                    throw new AuthorizationDeniedException(msg);
                }
            } // if (parsedObject instanceof CVCAuthenticatedRequest)
              // If it is not an authenticated request, with an outer signature, continue processing as usual, 
              // using the sent in username/password hoping the status is NEW and password is correct. 
        } else {
            // If there are no old user, continue processing as usual... it will fail
            log.debug("No existing user with username: " + username);
        }

        // Finally generate the certificate (assuming status is NEW and password is correct
        byte[] response = processCertReq(username, password, cvcreq, CertificateConstants.CERT_REQ_TYPE_CVC,
                null, CertificateHelper.RESPONSETYPE_CERTIFICATE, logger);
        CertificateResponse ret = new CertificateResponse(CertificateHelper.RESPONSETYPE_CERTIFICATE, response);
        byte[] b64cert = ret.getData();
        CVCertificate certObject = CertificateParser.parseCertificate(Base64.decode(b64cert));
        java.security.cert.Certificate iscert = new CardVerifiableCertificate(certObject);
        ArrayList<Certificate> retval = new ArrayList<Certificate>();
        retval.add(new Certificate((java.security.cert.Certificate) iscert));
        // Get the certificate chain
        if (user != null) {
            int caid = user.getCAId();
            caSession.verifyExistenceOfCA(caid);
            Collection<java.security.cert.Certificate> certs = signSession.getCertificateChain(admin, caid);
            Iterator<java.security.cert.Certificate> iter = certs.iterator();
            while (iter.hasNext()) {
                java.security.cert.Certificate cert = iter.next();
                retval.add(new Certificate(cert));
            }
        }
        log.trace("<cvcRequest");
        return retval;
    } catch (EjbcaException e) {
        // Have this first, if processReq throws an EjbcaException we want to reset status
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw e;
    } catch (ServiceLocatorException e) {
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (FinderException e) {
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (ParseException e) {
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (ConstructionException e) {
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (NoSuchFieldException e) {
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (CertificateEncodingException e) {
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (RuntimeException e) { // EJBException, ...
        ejbhelper.resetUserPasswordAndStatus(admin, username, olduserStatus);
        throw EjbcaWSHelper.getInternalException(e, logger);
    } finally {
        logger.writeln();
        logger.flush();
    }
}

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

@Override
public KeyStore softTokenRequest(UserDataVOWS userdata, String hardTokenSN, String keyspec, String keyalg)
        throws CADoesntExistsException, AuthorizationDeniedException, NotFoundException,
        UserDoesntFullfillEndEntityProfile, ApprovalException, WaitingForApprovalException, EjbcaException {
    final IPatternLogger logger = TransactionLogger.getPatternLogger();
    try {/*w w w .ja v a  2 s  . c o  m*/
        log.debug("Soft token req for user '" + userdata.getUsername() + "'.");
        userdata.setStatus(UserDataVOWS.STATUS_NEW);
        userdata.setClearPwd(true);
        final EjbcaWSHelper ejbcawshelper = new EjbcaWSHelper(wsContext, authorizationSession, caAdminSession,
                caSession, certificateProfileSession, certificateStoreSession, endEntityAccessSession,
                endEntityProfileSession, hardTokenSession, endEntityManagementSession, webAuthenticationSession,
                cryptoTokenManagementSession);
        final AuthenticationToken admin = ejbcawshelper.getAdmin(false);
        logAdminName(admin, logger);
        enrichUserDataWithRawSubjectDn(userdata);
        final EndEntityInformation endEntityInformation = ejbcawshelper.convertUserDataVOWS(admin, userdata);
        final boolean createJKS = userdata.getTokenType().equals(UserDataVOWS.TOKEN_TYPE_JKS);
        final byte[] encodedKeyStore = certificateRequestSession.processSoftTokenReq(admin,
                endEntityInformation, hardTokenSN, keyspec, keyalg, createJKS);
        // Convert encoded KeyStore to the proper return type
        final java.security.KeyStore ks;
        if (createJKS) {
            ks = java.security.KeyStore.getInstance("JKS");
        } else {
            ks = java.security.KeyStore.getInstance("PKCS12", "BC");
        }
        ks.load(new ByteArrayInputStream(encodedKeyStore), userdata.getPassword().toCharArray());
        return new KeyStore(ks, userdata.getPassword());
    } catch (CADoesntExistsException t) {
        logger.paramPut(TransactionTags.ERROR_MESSAGE.toString(), t.toString());
        throw t;
    } catch (AuthorizationDeniedException t) {
        logger.paramPut(TransactionTags.ERROR_MESSAGE.toString(), t.toString());
        throw t;
    } catch (NotFoundException t) {
        logger.paramPut(TransactionTags.ERROR_MESSAGE.toString(), t.toString());
        throw t;
    } catch (InvalidKeyException e) {
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.INVALID_KEY, Level.ERROR);
    } catch (AuthStatusException e) {
        // Don't log a bad error for this (user wrong status)
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.USER_WRONG_STATUS, Level.DEBUG);
    } catch (AuthLoginException e) {
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.LOGIN_ERROR, Level.ERROR);
    } catch (SignatureException e) {
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.SIGNATURE_ERROR, Level.ERROR);
    } catch (InvalidKeySpecException e) {
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.INVALID_KEY_SPEC, Level.ERROR);
    } catch (NoSuchAlgorithmException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (NoSuchProviderException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (KeyStoreException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (CertificateException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (CreateException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (IOException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (FinderException e) {
        throw new NotFoundException(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (RuntimeException e) { // EJBException, ...
        throw EjbcaWSHelper.getInternalException(e, logger);
    } catch (EndEntityExistsException e) {
        throw EjbcaWSHelper.getEjbcaException(e, logger, ErrorCode.USER_ALREADY_EXISTS, Level.INFO);
    } finally {
        logger.writeln();
        logger.flush();
    }
}