Example usage for java.security NoSuchAlgorithmException getMessage

List of usage examples for java.security NoSuchAlgorithmException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from w  w w  .  j a  va 2  s. c  o  m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":");
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from  w ww . j a  va  2  s. c  o  m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (AbLogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        " Certificate " + (c + 1) + ":");
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (AbLogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Instantiates a new jar delta jar patcher test.
 *///from   ww  w.j  a  va 2 s.  c  o  m
public JarDeltaJarPatcherTest() {
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

From source file:org.opendatakit.utilities.ODKFileUtils.java

/**
 * MD5's a file. Used in ODKDatabaseImplUtils and EncryptionUtils
 *
 * @param appName the app name/*from   ww w  . j  ava  2s .co  m*/
 * @param file    the file to hash
 * @return the md5sum of that file
 */
@SuppressWarnings("WeakerAccess")
public static String getNakedMd5Hash(String appName, Object file) {
    InputStream is = null;
    try {
        // CTS (6/15/2010) : stream file through digest instead of handing
        // it the byte[]
        MessageDigest md = MessageDigest.getInstance("MD5");
        int chunkSize = 8192;

        byte[] chunk = new byte[chunkSize];

        // Get the size of the file
        long lLength;
        if (file instanceof File) {
            lLength = ((File) file).length();
        } else if (file instanceof String) {
            lLength = ((String) file).length();
        } else {
            throw new IllegalArgumentException("Bad object to md5");
        }

        if (lLength > Integer.MAX_VALUE) {
            if (file instanceof File) {
                WebLogger.getLogger(appName).e(TAG, "File " + ((File) file).getName() + " is too large");
            } else {
                WebLogger.getLogger(appName).e(TAG, "String is too large to md5");
            }
            return null;
        }

        if (lLength > Integer.MAX_VALUE) {
            throw new RuntimeException("Refusing to cast from long to int with loss of precision");
        }
        //noinspection NumericCastThatLosesPrecision
        int length = (int) lLength;

        if (file instanceof File) {
            is = new FileInputStream((File) file);
        } else {
            is = new ByteArrayInputStream(((String) file).getBytes(CharEncoding.UTF_8));
        }

        int l;
        for (l = 0; l + chunkSize < length; l += chunkSize) {
            // TODO double check that this still works after the change
            if (is.read(chunk, 0, chunkSize) == -1)
                break;
            md.update(chunk, 0, chunkSize);
        }

        int remaining = length - l;
        if (remaining > 0) {
            // TODO double check that this still works after the change
            if (is.read(chunk, 0, remaining) != -1) {
                md.update(chunk, 0, remaining);
            }
        }
        byte[] messageDigest = md.digest();

        BigInteger number = new BigInteger(1, messageDigest);
        String md5 = number.toString(16);
        while (md5.length() < 32)
            md5 = "0" + md5;
        is.close();
        return md5;

    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(appName).e("MD5", e.getMessage());
        return null;

    } catch (FileNotFoundException e) {
        WebLogger.getLogger(appName).e("No Cache File", e.getMessage());
        return null;
    } catch (IOException e) {
        WebLogger.getLogger(appName).e("Problem reading from file", e.getMessage());
        return null;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        }
    }

}

From source file:eu.europa.ec.markt.tlmanager.core.signature.SignatureManager.java

/**
 * Do the actual signing.// w w w .j  a  v  a2  s . c om
 * 
 * @throws IOException
 */
public void sign() throws IOException {
    SignatureParameters parameters = new SignatureParameters();
    parameters.setSigningDate(new Date());
    DSSPrivateKeyEntry pk = determineCurrentPK();
    parameters.setSigningCertificate((X509Certificate) pk.getCertificate());
    parameters.setCertificateChain(Arrays.asList((X509Certificate[]) pk.getCertificateChain()));

    parameters.setSignatureFormat(SIGNATURE_FORMAT);
    parameters.setSignaturePackaging(SignaturePackaging.ENVELOPED);

    parameters.setClaimedSignerRole(null);

    parameters.setSignaturePolicyId(null);

    InputStream toBeSigned = xadesService.toBeSigned(document, parameters);

    byte[] signatureValue;
    try {
        signatureValue = signatureTokenConnection.sign(toBeSigned, SIGNATURE_DIGEST, pk);
        Document signedDocument = xadesService.signDocument(document, parameters, signatureValue);

        FileOutputStream output = new FileOutputStream(target);
        IOUtils.copy(signedDocument.openStream(), output);
        output.close();
    } catch (NoSuchAlgorithmException nsae) {
        LOG.log(Level.SEVERE, "No suited algorithm found for " + SIGNATURE_ALGO + " with " + SIGNATURE_DIGEST
                + ": " + nsae.getMessage());
    }
}

From source file:org.purl.sword.client.Client.java

/**
 * Post a file to the server. The different elements of the post are encoded
 * in the specified message./*from  w w  w.  jav a2s  . c om*/
 * 
 * @param message
 *            The message that contains the post information.
 * 
 * @throws SWORDClientException
 *             if there is an error during the post operation.
 */
public DepositResponse postFile(PostMessage message) throws SWORDClientException {
    if (message == null) {
        throw new SWORDClientException("Message cannot be null.");
    }

    PostMethod httppost = new PostMethod(message.getDestination());

    if (doAuthentication) {
        setBasicCredentials(username, password);
        httppost.setDoAuthentication(true);
    }

    DepositResponse response = null;

    String messageBody = "";

    try {
        if (message.isUseMD5()) {
            String md5 = ChecksumUtils.generateMD5(message.getFilepath());
            if (message.getChecksumError()) {
                md5 = "1234567890";
            }
            log.debug("checksum error is: " + md5);
            if (md5 != null) {
                httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_MD5, md5));
            }
        }

        String filename = message.getFilename();
        if (!"".equals(filename)) {
            httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename));
        }

        if (containsValue(message.getSlug())) {
            httppost.addRequestHeader(new Header(HttpHeaders.SLUG, message.getSlug()));
        }

        if (message.getCorruptRequest()) {
            // insert a header with an invalid boolean value
            httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, "Wibble"));
        } else {
            httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, Boolean.toString(message.isNoOp())));
        }
        httppost.addRequestHeader(new Header(HttpHeaders.X_VERBOSE, Boolean.toString(message.isVerbose())));

        String packaging = message.getPackaging();
        if (packaging != null && packaging.length() > 0) {
            httppost.addRequestHeader(new Header(HttpHeaders.X_PACKAGING, packaging));
        }

        String onBehalfOf = message.getOnBehalfOf();
        if (containsValue(onBehalfOf)) {
            httppost.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf));
        }

        String userAgent = message.getUserAgent();
        if (containsValue(userAgent)) {
            httppost.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent));
        }

        FileRequestEntity requestEntity = new FileRequestEntity(new File(message.getFilepath()),
                message.getFiletype());
        httppost.setRequestEntity(requestEntity);

        client.executeMethod(httppost);
        status = new Status(httppost.getStatusCode(), httppost.getStatusText());

        log.info("Checking the status code: " + status.getCode());

        if (status.getCode() == HttpStatus.SC_ACCEPTED || status.getCode() == HttpStatus.SC_CREATED) {
            messageBody = readResponse(httppost.getResponseBodyAsStream());
            response = new DepositResponse(status.getCode());
            response.setLocation(httppost.getResponseHeader("Location").getValue());
            // added call for the status code.
            lastUnmarshallInfo = response.unmarshall(messageBody, new Properties());
        } else {
            messageBody = readResponse(httppost.getResponseBodyAsStream());
            response = new DepositResponse(status.getCode());
            response.unmarshallErrorDocument(messageBody);
        }
        return response;

    } catch (NoSuchAlgorithmException nex) {
        throw new SWORDClientException("Unable to use MD5. " + nex.getMessage(), nex);
    } catch (HttpException ex) {
        throw new SWORDClientException(ex.getMessage(), ex);
    } catch (IOException ioex) {
        throw new SWORDClientException(ioex.getMessage(), ioex);
    } catch (UnmarshallException uex) {
        throw new SWORDClientException(uex.getMessage() + "(<pre>" + messageBody + "</pre>)", uex);
    } finally {
        httppost.releaseConnection();
    }
}

From source file:edu.vt.middleware.crypt.CryptProvider.java

/**
 * <p>This finds a <code>Cipher</code> using the known providers and the
 * supplied parameters.</p>/*from   www. j ava 2 s  . c  om*/
 *
 * @param  algorithm  <code>String</code> name
 * @param  mode  <code>String</code> name
 * @param  padding  <code>String</code> name
 *
 * @return  <code>Cipher</code>
 *
 * @throws  CryptException  if the algorithm is not available from any
 * provider or if the provider is not available in the environment
 */
public static Cipher getCipher(final String algorithm, final String mode, final String padding)
        throws CryptException {
    final Log logger = LogFactory.getLog(CryptProvider.class);
    Cipher cipher = null;
    String transformation = null;
    if (mode != null && padding != null) {
        transformation = algorithm + "/" + mode + "/" + padding;
    } else if (mode != null) {
        transformation = algorithm + "/" + mode;
    } else {
        transformation = algorithm;
    }
    for (int i = 0; i < providers.length; i++) {
        try {
            cipher = Cipher.getInstance(transformation, providers[i]);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm + " in " + providers[i]);
            }
        } catch (NoSuchProviderException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find provider " + providers[i]);
            }
        } catch (NoSuchPaddingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find padding " + padding + " in " + providers[i]);
            }
        } finally {
            if (cipher != null) {
                break;
            }
        }
    }
    if (cipher == null) {
        try {
            cipher = Cipher.getInstance(transformation);
        } catch (NoSuchAlgorithmException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find algorithm " + algorithm);
            }
            throw new CryptException(e.getMessage());
        } catch (NoSuchPaddingException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Could not find padding " + padding);
            }
            throw new CryptException(e.getMessage());
        }
    }
    return cipher;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#decryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 */// www.j  ava 2 s  . com
public synchronized FileSecurityResponse decryptFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#decryptFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Cipher cipher = Cipher.getInstance(fileSecurityConfig.getEncryptionAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());

            if (DEBUG) {
                DEBUGGER.debug("Cipher: {}", cipher);
            }

            IOUtils.write(
                    IOUtils.toByteArray(
                            new CipherInputStream(new FileInputStream(request.getEncryptedFile()), cipher)),
                    new FileOutputStream(request.getDecryptedFile()));

            if ((request.getEncryptedFile().exists()) && (request.getEncryptedFile().length() != 0)) {
                response.setSignedFile(request.getEncryptedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (NoSuchPaddingException nspx) {
        ERROR_RECORDER.error(nspx.getMessage(), nspx);

        throw new FileSecurityException(nspx.getMessage(), nspx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.DECRYPTFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#verifyFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///from  w  w w .  ja v  a  2  s .  c  om
public synchronized FileSecurityResponse verifyFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#verifyFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            // read in the file signature
            byte[] sigToVerify = IOUtils.toByteArray(new FileInputStream(request.getSignedFile()));

            if (DEBUG) {
                DEBUGGER.debug("sigToVerify: {}", sigToVerify);
            }

            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initVerify(keyPair.getPublic());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            response.setIsSignatureValid(signature.verify(sigToVerify));
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.VERIFYFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:be.fedict.eid.applet.service.impl.handler.HelloMessageHandler.java

public Object handleMessage(HelloMessage message, Map<String, String> httpHeaders, HttpServletRequest request,
        HttpSession session) throws ServletException {
    LOG.debug("hello message received");

    storeClientLanguage(message.language, session);

    if (this.diagnosticMode) {
        LOG.debug("diagnostic mode");
        DiagnosticMessage diagnosticMessage = new DiagnosticMessage();
        return diagnosticMessage;
    }/*from   www .  j  av  a 2 s  . c o m*/

    SecureClientEnvironmentService secureClientEnvService = this.secureClientEnvServiceLocator.locateService();
    if (null != secureClientEnvService) {
        CheckClientMessage checkClientMessage = new CheckClientMessage();
        return checkClientMessage;
    }
    if (this.kiosk) {
        LOG.debug("operating in Kiosk Mode");
        KioskMessage kioskMessage = new KioskMessage();
        return kioskMessage;
    }
    if (this.changePin || this.unblockPin) {
        AdministrationMessage administrationMessage = new AdministrationMessage(this.changePin, this.unblockPin,
                this.logoff, this.removeCard, this.requireSecureReader);
        return administrationMessage;
    }
    SignatureService signatureService = this.signatureServiceLocator.locateService();
    if (null != signatureService) {
        String filesDigestAlgo = signatureService.getFilesDigestAlgorithm();
        if (null != filesDigestAlgo) {
            LOG.debug("files digest algo: " + filesDigestAlgo);
            FilesDigestRequestMessage filesDigestRequestMessage = new FilesDigestRequestMessage();
            filesDigestRequestMessage.digestAlgo = filesDigestAlgo;
            return filesDigestRequestMessage;
        }
        if (true == this.includeCertificates) {
            LOG.debug("include signing certificate chain during pre-sign");
            IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                    .locateService();
            boolean includeIntegrityData = null != identityIntegrityService;
            IdentityService identityService = this.identityServiceLocator.locateService();
            boolean includeIdentity;
            boolean includeAddress;
            boolean includePhoto;
            if (null != identityService) {
                IdentityRequest identityRequest = identityService.getIdentityRequest();
                includeIdentity = identityRequest.includeIdentity();
                includeAddress = identityRequest.includeAddress();
                includePhoto = identityRequest.includePhoto();
            } else {
                includeIdentity = this.includeIdentity;
                includeAddress = this.includeAddress;
                includePhoto = this.includePhoto;
            }
            RequestContext requestContext = new RequestContext(session);
            requestContext.setIncludeIdentity(includeIdentity);
            requestContext.setIncludeAddress(includeAddress);
            requestContext.setIncludePhoto(includePhoto);
            SignCertificatesRequestMessage signCertificatesRequestMessage = new SignCertificatesRequestMessage(
                    includeIdentity, includeAddress, includePhoto, includeIntegrityData);
            return signCertificatesRequestMessage;
        }

        DigestInfo digestInfo;
        try {
            digestInfo = signatureService.preSign(null, null);
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("no such algo: " + e.getMessage(), e);
        }

        // also save it in the session for later verification
        SignatureDataMessageHandler.setDigestValue(digestInfo.digestValue, digestInfo.digestAlgo, session);

        IdentityService identityService = this.identityServiceLocator.locateService();
        boolean removeCard;
        if (null != identityService) {
            IdentityRequest identityRequest = identityService.getIdentityRequest();
            removeCard = identityRequest.removeCard();
        } else {
            removeCard = this.removeCard;
        }

        SignRequestMessage signRequestMessage = new SignRequestMessage(digestInfo.digestValue,
                digestInfo.digestAlgo, digestInfo.description, this.logoff, removeCard,
                this.requireSecureReader);
        return signRequestMessage;
    }
    AuthenticationService authenticationService = this.authenticationServiceLocator.locateService();
    if (null != authenticationService) {
        byte[] challenge = AuthenticationChallenge.generateChallenge(session);
        IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                .locateService();
        boolean includeIntegrityData = null != identityIntegrityService;
        boolean includeIdentity;
        boolean includeAddress;
        boolean includePhoto;
        boolean includeCertificates;
        boolean removeCard;
        IdentityService identityService = this.identityServiceLocator.locateService();
        if (null != identityService) {
            IdentityRequest identityRequest = identityService.getIdentityRequest();
            includeIdentity = identityRequest.includeIdentity();
            includeAddress = identityRequest.includeAddress();
            includePhoto = identityRequest.includePhoto();
            includeCertificates = identityRequest.includeCertificates();
            removeCard = identityRequest.removeCard();
        } else {
            includeIdentity = this.includeIdentity;
            includeAddress = this.includeAddress;
            includePhoto = this.includePhoto;
            includeCertificates = this.includeCertificates;
            removeCard = this.removeCard;
        }
        RequestContext requestContext = new RequestContext(session);
        requestContext.setIncludeIdentity(includeIdentity);
        requestContext.setIncludeAddress(includeAddress);
        requestContext.setIncludePhoto(includePhoto);
        requestContext.setIncludeCertificates(includeCertificates);

        String transactionMessage = null;
        SecureCardReaderService secureCardReaderService = this.secureCardReaderServiceLocator.locateService();
        if (null != secureCardReaderService) {
            transactionMessage = secureCardReaderService.getTransactionMessage();
            if (null != transactionMessage
                    && transactionMessage.length() > SecureCardReaderService.TRANSACTION_MESSAGE_MAX_SIZE) {
                transactionMessage = transactionMessage.substring(0,
                        SecureCardReaderService.TRANSACTION_MESSAGE_MAX_SIZE);
            }
            LOG.debug("transaction message: " + transactionMessage);
        }
        requestContext.setTransactionMessage(transactionMessage);

        AuthenticationRequestMessage authenticationRequestMessage = new AuthenticationRequestMessage(challenge,
                this.includeHostname, this.includeInetAddress, this.logoff, this.preLogoff, removeCard,
                this.sessionIdChannelBinding, this.serverCertificateChannelBinding, includeIdentity,
                includeCertificates, includeAddress, includePhoto, includeIntegrityData,
                this.requireSecureReader, transactionMessage);
        return authenticationRequestMessage;
    }

    IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator.locateService();
    boolean includeIntegrityData = null != identityIntegrityService;
    PrivacyService privacyService = this.privacyServiceLocator.locateService();
    String identityDataUsage;
    if (null != privacyService) {
        identityDataUsage = privacyService.getIdentityDataUsage(message.language);
    } else {
        identityDataUsage = null;
    }
    boolean includeAddress;
    boolean includePhoto;
    boolean includeCertificates;
    boolean removeCard;
    IdentityService identityService = this.identityServiceLocator.locateService();
    if (null != identityService) {
        IdentityRequest identityRequest = identityService.getIdentityRequest();
        includeAddress = identityRequest.includeAddress();
        includePhoto = identityRequest.includePhoto();
        includeCertificates = identityRequest.includeCertificates();
        removeCard = identityRequest.removeCard();
    } else {
        includeAddress = this.includeAddress;
        includePhoto = this.includePhoto;
        includeCertificates = this.includeCertificates;
        removeCard = this.removeCard;
    }
    RequestContext requestContext = new RequestContext(session);
    requestContext.setIncludeAddress(includeAddress);
    requestContext.setIncludePhoto(includePhoto);
    requestContext.setIncludeCertificates(includeCertificates);
    IdentificationRequestMessage responseMessage = new IdentificationRequestMessage(includeAddress,
            includePhoto, includeIntegrityData, includeCertificates, removeCard, identityDataUsage);
    return responseMessage;
}