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:swp.bibjsf.persistence.Data.java

@Override
public int addLibrarian(Reader reader) throws DataSourceException, BusinessElementAlreadyExistsException {
    logger.debug("add librarian " + reader);
    try {/*from w w  w  .j  a  v  a 2  s .c  o  m*/
        if (getReader(reader.getId()) != null) {
            // ID must be unique
            throw new BusinessElementAlreadyExistsException(
                    Messages.get("readerexists") + " " + Messages.get("id") + " = " + reader.getId());
        } else if (!reader.getUsername().isEmpty() && getReaderByUsername(reader.getUsername()) != null) {
            // user name must be unique if defined
            throw new BusinessElementAlreadyExistsException(
                    Messages.get("readerexists") + Messages.get("username") + " = " + reader.getUsername());
        } else {
            logger.debug("reader " + reader + " does not yet exist; has ID: " + reader.hasId());
            try {
                final String password = hashPassword(reader);
                Set<String> toIgnore = new HashSet<String>();
                HashMap<String, Object> replace = new HashMap<String, Object>();
                replace.put("password", password);
                int result = insertByID(reader, readerTableName, readerMinID, toIgnore, replace);
                insertLibrarian(reader.getUsername());
                return result;
            } catch (NoSuchAlgorithmException e) {
                logger.error("MD5 problem");
                throw new DataSourceException(e.getMessage());
            }
        }
    } catch (SQLException e) {
        logger.error("add librarian failure");
        throw new DataSourceException(e.getMessage());
    }
}

From source file:com.cloud.network.NetworkModelImpl.java

@Override
public List<String[]> generateVmData(String userData, String serviceOffering, String zoneName, String vmName,
        long vmId, String publicKey, String password, Boolean isWindows) {
    final List<String[]> vmData = new ArrayList<String[]>();

    if (userData != null) {
        vmData.add(new String[] { "userdata", "user-data",
                new String(Base64.decodeBase64(userData), StringUtils.getPreferredCharset()) });
    }//  w  ww  .  ja v a  2s .c om
    vmData.add(new String[] { "metadata", "service-offering", StringUtils.unicodeEscape(serviceOffering) });
    vmData.add(new String[] { "metadata", "availability-zone", StringUtils.unicodeEscape(zoneName) });
    vmData.add(new String[] { "metadata", "local-hostname", StringUtils.unicodeEscape(vmName) });
    vmData.add(new String[] { "metadata", "instance-id", vmName });
    vmData.add(new String[] { "metadata", "vm-id", String.valueOf(vmId) });
    vmData.add(new String[] { "metadata", "public-keys", publicKey });

    String cloudIdentifier = _configDao.getValue("cloud.identifier");
    if (cloudIdentifier == null) {
        cloudIdentifier = "";
    } else {
        cloudIdentifier = "CloudStack-{" + cloudIdentifier + "}";
    }
    vmData.add(new String[] { "metadata", "cloud-identifier", cloudIdentifier });

    if (password != null && !password.isEmpty() && !password.equals("saved_password")) {

        // Here we are calculating MD5 checksum to reduce the over head of calculating MD5 checksum
        // in windows VM in password reset script.

        if (isWindows) {
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                s_logger.error("Unexpected exception " + e.getMessage(), e);
                throw new CloudRuntimeException("Unable to get MD5 MessageDigest", e);
            }
            md5.reset();
            md5.update(password.getBytes(StringUtils.getPreferredCharset()));
            byte[] digest = md5.digest();
            BigInteger bigInt = new BigInteger(1, digest);
            String hashtext = bigInt.toString(16);

            vmData.add(new String[] { "password", "vm-password-md5checksum", hashtext });
        }

        vmData.add(new String[] { "password", "vm-password", password });
    }

    return vmData;
}

From source file:com.ubiLive.GameCloud.Browser.WebBrowser.java

public String ubiGCPlayerDigestMessage(String message) {
    String resultSignature = "";
    try {// w  w w  .  j a v  a  2  s . c  o  m
        byte[] sha1Bytes = Utils.SHA1(message);
        //DebugLog.d(TAG, "ubiGCPlayerDigestMessage() sha1Str = " + sha1Str);
        //DebugLog.d(TAG, "ubiGCPlayerDigestMessage() sha1Bytes = " + Arrays.toString(sha1Bytes));

        byte[] rsaEncryptedBytes = Utils.rsaEncrypt(Constants.sModulusStr, Constants.sPublicExponentStr,
                sha1Bytes);
        DebugLog.d(TAG, "ubiGCPlayerDigestMessage() rsaEncryptedBytes = " + Arrays.toString(rsaEncryptedBytes));
        resultSignature = Base64.encodeToString(rsaEncryptedBytes, Base64.NO_WRAP);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        DebugLog.d(TAG, "excepion = " + e.getMessage());
        return "";
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        DebugLog.d(TAG, "excepion = " + e.getMessage());
        return "";
    }
    return resultSignature;
}

From source file:org.rapla.storage.impl.server.LocalAbstractCachableOperator.java

public String createId(RaplaType raplaType, String seed) throws RaplaException {

    byte[] data = new byte[16];
    MessageDigest md;//from  ww  w . j  av a  2  s .c  o  m
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RaplaException(e.getMessage(), e);
    }
    data = md.digest(seed.getBytes());
    if (data.length != 16) {
        throw new RaplaException("Wrong algorithm");
    }
    data[6] &= 0x0f; /* clear version        */
    data[6] |= 0x40; /* set to version 4     */
    data[8] &= 0x3f; /* clear variant        */
    data[8] |= 0x80; /* set to IETF variant  */

    long msb = 0;
    long lsb = 0;
    for (int i = 0; i < 8; i++)
        msb = (msb << 8) | (data[i] & 0xff);
    for (int i = 8; i < 16; i++)
        lsb = (lsb << 8) | (data[i] & 0xff);
    long mostSigBits = msb;
    long leastSigBits = lsb;

    UUID uuid = new UUID(mostSigBits, leastSigBits);
    String result = replaceFirst(raplaType, uuid.toString());
    return result;
}

From source file:com.hurence.logisland.processor.ModifyId.java

@Override
public void init(ProcessContext context) {
    super.init(context);
    if (context.getPropertyValue(STRATEGY).isSet()) {
        if (context.getPropertyValue(STRATEGY).getRawValue().equals(RANDOM_UUID_STRATEGY.getValue())) {
            idBuilder = new IdBuilder() {
                @Override/*from w  w  w .jav a2 s  . co  m*/
                public void buildId(Record record) {
                    record.setId(UUID.randomUUID().toString());
                }
            };
        } else if (context.getPropertyValue(STRATEGY).getRawValue().equals(HASH_FIELDS_STRATEGY.getValue())) {
            final List<String> fieldsForHash = Lists
                    .newArrayList(context.getPropertyValue(FIELDS_TO_USE).asString().split(","));

            try {
                final MessageDigest digest = MessageDigest
                        .getInstance(context.getPropertyValue(HASH_ALGORITHM).asString());
                final Charset charset = Charset
                        .forName(context.getPropertyValue(CHARSET_TO_USE_FOR_HASH).asString());
                idBuilder = new IdBuilder() {
                    @Override
                    public void buildId(Record record) {
                        StringBuilder stb = new StringBuilder();
                        for (String fieldName : fieldsForHash) {
                            if (record.hasField(fieldName))
                                stb.append(record.getField(fieldName).asString());
                        }
                        digest.update(stb.toString().getBytes(charset));
                        byte[] digested = digest.digest();
                        record.setId(Hex.encodeHexString(digested));
                    }
                };
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                        "This error should not happen because the validator should ensure the algorythme exist",
                        e);
            }
        } else if (context.getPropertyValue(STRATEGY).getRawValue()
                .equals(JAVA_FORMAT_STRING_WITH_FIELDS_STRATEGY.getValue())) {
            final String[] fieldsForFormat = context.getPropertyValue(FIELDS_TO_USE).asString().split(",");
            final String format = context.getPropertyValue(JAVA_FORMAT_STRING).asString();
            final Locale local = Locale.forLanguageTag(context.getPropertyValue(LANGUAGE_TAG).asString());
            idBuilder = new IdBuilder() {
                @Override
                public void buildId(Record record) {
                    final Object[] valuesForFormat = new Object[fieldsForFormat.length];
                    for (int i = 0; i < valuesForFormat.length; i++) {
                        if (!record.hasField(fieldsForFormat[i])) {
                            List<String> fieldsName = Lists.newArrayList(fieldsForFormat);
                            record.addError(ProcessError.CONFIG_SETTING_ERROR.getName(),
                                    String.format(
                                            "could not build id with format : '%s' \nfields: '%s' \n because "
                                                    + "field: '%s' does not exist",
                                            format, fieldsName, fieldsForFormat[i]));
                            return;
                        }
                        valuesForFormat[i] = record.getField(fieldsForFormat[i]).getRawValue();
                    }
                    try {
                        record.setId(String.format(local, format, valuesForFormat));
                    } catch (IllegalFormatException e) {
                        // If a format string contains an illegal syntax, a format specifier that is incompatible with the given arguments,
                        // insufficient arguments given the format string, or other illegal conditions.
                        // For specification of all possible formatting errors, see the Details section of the formatter class specification.
                        record.addError(ProcessError.STRING_FORMAT_ERROR.getName(), e.getMessage());
                    } catch (NullPointerException e) {//should not happen
                        record.addError(ProcessError.CONFIG_SETTING_ERROR.getName(), e.getMessage());
                    }
                }
            };
        } else if (context.getPropertyValue(STRATEGY).getRawValue()
                .equals(TYPE_TIME_HASH_STRATEGY.getValue())) {
            final List<String> fieldsForHash = Lists
                    .newArrayList(context.getPropertyValue(FIELDS_TO_USE).asString().split(","));
            try {
                final MessageDigest digest = MessageDigest
                        .getInstance(context.getPropertyValue(HASH_ALGORITHM).asString());
                final Charset charset = Charset
                        .forName(context.getPropertyValue(CHARSET_TO_USE_FOR_HASH).asString());
                idBuilder = new IdBuilder() {
                    @Override
                    public void buildId(Record record) {
                        StringBuilder stb = new StringBuilder();
                        for (String fieldName : fieldsForHash) {
                            stb.append(record.getField(fieldName).asString());
                        }
                        digest.update(stb.toString().getBytes(charset));
                        byte[] digested = digest.digest();
                        final String hashString = new String(digested, charset);
                        final String recordType = record.getField(FieldDictionary.RECORD_TYPE).asString();
                        final String recordTime = record.getField(FieldDictionary.RECORD_TIME).asString();
                        final String newId = String.format("%s-%s-%s", recordType, recordTime, hashString);
                        record.setId(newId);
                    }
                };
            } catch (NoSuchAlgorithmException e) {
                throw new Error(
                        "This error should not happen because the validator should ensure the algorythme exist",
                        e);
            }
        }
    }
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Returns a ServerSocket object to be used for listening.
 * @since 1.4.0/* w  ww. j a v  a 2 s  .  c om*/
 */
protected void makeServerSocket() throws BindException, IOException {
    server = null;
    logger.log(Level.FINEST, "Binding {0} to IP: {1}", new Object[] { getName(), getBindAddr() });
    InetSocketAddress bindAddress = new InetSocketAddress(getBindAddr(), getPort());

    try {
        NetworkInterface ni = NetworkInterface.getByInetAddress(getBindAddr());
        if (ni != null) {
            logger.fine("NetworkInterface: " + ni);
        }
    } catch (Exception igrnore) {
        /*ignore*/} catch (Error igrnore) {
        /*ignore*/}

    if (getSecure().isEnable() == false) {
        logger.log(Level.FINE, "Making a normal ServerSocket for {0}", getName());
        setRunningSecure(false);

        if (getBlockingMode() == false) {
            //for non-blocking
            serverSocketChannel = ServerSocketChannel.open();
            server = serverSocketChannel.socket();
            server.bind(bindAddress, getBasicConfig().getAdvancedSettings().getBacklog());
        } else {
            //for blocking
            server = new ServerSocket(getPort(), getBasicConfig().getAdvancedSettings().getBacklog(),
                    getBindAddr());
        }
    } else {
        try {
            logger.log(Level.FINE, "Making a secure ServerSocket for {0}", getName());
            getSSLContext();
            setRunningSecure(true);

            if (getBlockingMode() == false) {

                logger.log(Level.FINE, "Making a secure ServerSocketChannel for {0}", getName());
                //for non-blocking
                serverSocketChannel = ServerSocketChannel.open();
                server = serverSocketChannel.socket();
                server.bind(bindAddress, getBasicConfig().getAdvancedSettings().getBacklog());
            } else {

                ServerSocketFactory ssf = getSSLContext().getServerSocketFactory();
                SSLServerSocket serversocket = (SSLServerSocket) ssf.createServerSocket(getPort(),
                        getBasicConfig().getAdvancedSettings().getBacklog(), getBindAddr());
                serversocket.setNeedClientAuth(secure.isClientAuthEnable());
                setRunningSecure(true);

                secureStoreManager.logSSLServerSocketInfo(serversocket);

                server = serversocket;
                serverSocketChannel = server.getChannel();

                if (serverSocketChannel == null && getBlockingMode() == false) {
                    logger.warning("Secure Server does not support Channel! So will run in blocking mode.");
                    blockingMode = false;
                }

            } //blocking
        } catch (NoSuchAlgorithmException e) {
            logger.log(Level.WARNING, "NoSuchAlgorithmException : {0}", e);
            throw new IOException("Error creating secure socket : " + e.getMessage());
        } catch (KeyManagementException e) {
            logger.log(Level.WARNING, "KeyManagementException : {0}", e);
            throw new IOException("Error creating secure socket : " + e.getMessage());
        }
    }

    server.setReuseAddress(true);

    int connectionTime = 0;
    int latency = 0;
    int bandwidth = 0;

    connectionTime = getBasicConfig().getAdvancedSettings().getPerformancePreferencesConnectionTime();
    latency = getBasicConfig().getAdvancedSettings().getPerformancePreferencesLatency();
    bandwidth = getBasicConfig().getAdvancedSettings().getPerformancePreferencesBandwidth();

    logger.log(Level.FINE, "getPerformancePreferencesConnectionTime : {0}", connectionTime);
    logger.log(Level.FINE, "getPerformancePreferencesLatency : {0}", latency);
    logger.log(Level.FINE, "getPerformancePreferencesBandwidth : {0}", bandwidth);

    server.setPerformancePreferences(connectionTime, latency, bandwidth);

    int clientSocketReceiveBufferSize = getBasicConfig().getAdvancedSettings()
            .getClientSocketReceiveBufferSize();
    if (clientSocketReceiveBufferSize > 0) {
        logger.log(Level.FINE, "clientSocketReceiveBufferSize: {0}", clientSocketReceiveBufferSize);
        server.setReceiveBufferSize(clientSocketReceiveBufferSize);
    }

    if (getBlockingMode() == false) {
        logger.log(Level.FINE, "Server Mode {0} - Non Blocking", getName());
        if (selector == null || selector.isOpen() == false) {
            logger.finest("Opening new selector");
            selector = Selector.open();
        } else {
            logger.log(Level.FINEST, "Reusing selector: {0}", selector);
        }
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        selector.wakeup();
    } else {
        logger.log(Level.FINE, "Server Mode {0} - Blocking", getName());
    }
}

From source file:com.netscape.ca.CertificateAuthority.java

/**
 * Signs the given certificate info using specified signing algorithm
 * If no algorithm is specified the CA's default algorithm is used.
 * <P>//  w w  w.  j  a  v a  2  s .com
 *
 * @param certInfo the certificate info to be signed.
 * @param algname the signing algorithm to use. These are names defined
 *            in JCA, such as MD5withRSA, etc. If null the CA's default
 *            signing algorithm will be used.
 * @return signed certificate
 */
public X509CertImpl sign(X509CertInfo certInfo, String algname) throws EBaseException {
    ensureReady();

    X509CertImpl signedcert = null;

    IStatsSubsystem statsSub = (IStatsSubsystem) CMS.getSubsystem("stats");
    if (statsSub != null) {
        statsSub.startTiming("signing");
    }

    try (DerOutputStream out = new DerOutputStream(); DerOutputStream tmp = new DerOutputStream()) {

        if (certInfo == null) {
            log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_NO_CERTINFO"));
            return null;
        }

        if (algname == null) {
            algname = mSigningUnit.getDefaultAlgorithm();
        }

        logger.debug("sign cert get algorithm");
        AlgorithmId alg = AlgorithmId.get(algname);

        // encode certificate info
        logger.debug("sign cert encoding cert");
        certInfo.encode(tmp);
        byte[] rawCert = tmp.toByteArray();

        // encode algorithm identifier
        logger.debug("sign cert encoding algorithm");
        alg.encode(tmp);

        logger.debug("CA cert signing: signing cert");
        byte[] signature = mSigningUnit.sign(rawCert, algname);

        tmp.putBitString(signature);

        // Wrap the signed data in a SEQUENCE { data, algorithm, sig }
        out.write(DerValue.tag_Sequence, tmp);
        //log(ILogger.LL_INFO, "CertificateAuthority: done signing");

        switch (mFastSigning) {
        case FASTSIGNING_DISABLED:
            signedcert = new X509CertImpl(out.toByteArray());
            break;

        case FASTSIGNING_ENABLED:
            signedcert = new X509CertImpl(out.toByteArray(), certInfo);
            break;

        default:
            break;
        }
    } catch (NoSuchAlgorithmException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
    } catch (IOException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
    } catch (CertificateException e) {
        log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSCORE_CA_CA_SIGN_CERT", e.toString(), e.getMessage()));
        throw new ECAException(CMS.getUserMessage("CMS_CA_SIGNING_CERT_FAILED", e.getMessage()));
    } finally {
        if (statsSub != null) {
            statsSub.endTiming("signing");
        }
    }
    return signedcert;
}

From source file:ca.sqlpower.matchmaker.enterprise.MatchMakerClientSideSession.java

/**
 * This method can update any users password on the server given the correct
 * old password and done by a user with the privileges to change the user's
 * password.//from  w w w  .j a va2  s.  c o m
 * 
 * @param session
 *            The client session that has the correct server information to
 *            post requests to the server.
 * @param username
 *            The user name of the user to update.
 * @param oldPassword
 *            The old password of the user to validate that the password can
 *            be updated correctly.
 * @param newPassword
 *            The new password to update to.
 * @param upf
 *            A user prompter to display message and error information to
 *            the user as necessary.
 */
public void updateUserPassword(User user, String oldPassword, String newPassword, UserPrompterFactory upf) {
    SPServerInfo serviceInfo = getProjectLocation().getServiceInfo();

    HttpClient client = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore);

    MessageDigest digester;
    try {
        digester = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }

    try {
        JSONObject begin = new JSONObject();
        begin.put("uuid", JSONObject.NULL);
        begin.put("method", "begin");

        JSONObject persist = new JSONObject();
        persist.put("uuid", user.getUUID());
        persist.put("propertyName", "password");
        persist.put("type", Datatype.STRING.toString());
        if (oldPassword == null) {
            persist.put("method", "persistProperty");
        } else {
            persist.put("method", "changeProperty");
            persist.put("oldValue", new String(Hex.encodeHex(digester.digest(oldPassword.getBytes()))));
        }
        persist.put("newValue", new String(Hex.encodeHex(digester.digest(newPassword.getBytes()))));

        JSONObject commit = new JSONObject();
        commit.put("uuid", JSONObject.NULL);
        commit.put("method", "commit");

        JSONArray transaction = new JSONArray();
        transaction.put(begin);
        transaction.put(persist);
        transaction.put(commit);

        URI serverURI = new URI("http", null, serviceInfo.getServerAddress(), serviceInfo.getPort(),
                serviceInfo.getPath() + "/" + ClientSideSessionUtils.REST_TAG + "/project/system",
                "currentRevision=" + getCurrentRevisionNumber(), null);
        HttpPost postRequest = new HttpPost(serverURI);
        postRequest.setEntity(new StringEntity(transaction.toString()));
        postRequest.setHeader("Content-Type", "application/json");
        HttpUriRequest request = postRequest;
        JSONMessage result = client.execute(request, new JSONResponseHandler());
        if (result.getStatusCode() != 200) {
            logger.warn("Failed password change");
            if (result.getStatusCode() == 412) {
                upf.createUserPrompter("The password you have entered is incorrect.", UserPromptType.MESSAGE,
                        UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
            } else {
                upf.createUserPrompter(
                        "Could not change the password due to the following: " + result.getBody()
                                + " See logs for more details.",
                        UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK")
                        .promptUser("");
            }
        }
    } catch (AccessDeniedException ex) {
        logger.warn("Failed password change", ex);
        upf.createUserPrompter("The password you have entered is incorrect.", UserPromptType.MESSAGE,
                UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
    } catch (Exception ex) {
        logger.warn("Failed password change", ex);
        upf.createUserPrompter(
                "Could not change the password due to the following: " + ex.getMessage()
                        + " See logs for more details.",
                UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
    }
}

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

public Object handleMessage(SignCertificatesDataMessage message, Map<String, String> httpHeaders,
        HttpServletRequest request, HttpSession session) throws ServletException {
    SignatureService signatureService = this.signatureServiceLocator.locateService();

    List<X509Certificate> signingCertificateChain = message.certificateChain;
    X509Certificate signingCertificate = signingCertificateChain.get(0);
    if (null == signingCertificate) {
        throw new ServletException("missing non-repudiation certificate");
    }/*from w ww.jav a2 s . c om*/
    LOG.debug("signing certificate: " + signingCertificateChain.get(0).getSubjectX500Principal());

    RequestContext requestContext = new RequestContext(session);
    boolean includeIdentity = requestContext.includeIdentity();
    boolean includeAddress = requestContext.includeAddress();
    boolean includePhoto = requestContext.includePhoto();

    Identity identity = null;
    Address address = null;
    if (includeIdentity || includeAddress || includePhoto) {
        /*
         * Pre-sign phase including identity data.
         */
        if (includeIdentity) {
            if (null == message.identityData) {
                throw new ServletException("identity data missing");
            }
            identity = TlvParser.parse(message.identityData, Identity.class);
        }

        if (includeAddress) {
            if (null == message.addressData) {
                throw new ServletException("address data missing");
            }
            address = TlvParser.parse(message.addressData, Address.class);
        }

        if (includePhoto) {
            if (null == message.photoData) {
                throw new ServletException("photo data missing");
            }
            if (null != identity) {
                byte[] expectedPhotoDigest = identity.photoDigest;
                byte[] actualPhotoDigest;

                try {
                    actualPhotoDigest = digestPhoto(getDigestAlgo(expectedPhotoDigest.length),
                            message.photoData);
                } catch (NoSuchAlgorithmException e) {
                    throw new ServletException("photo signed with unsupported algorithm");
                }

                if (false == Arrays.equals(expectedPhotoDigest, actualPhotoDigest)) {
                    throw new ServletException("photo digest incorrect");
                }
            }
        }

        IdentityIntegrityService identityIntegrityService = this.identityIntegrityServiceLocator
                .locateService();
        if (null != identityIntegrityService) {
            if (null == message.rrnCertificate) {
                throw new ServletException("national registry certificate not included while requested");
            }
            PublicKey rrnPublicKey = message.rrnCertificate.getPublicKey();
            if (null != message.identityData) {
                if (null == message.identitySignatureData) {
                    throw new ServletException("missing identity data signature");
                }
                verifySignature(message.rrnCertificate.getSigAlgName(), message.identitySignatureData,
                        rrnPublicKey, request, message.identityData);
                if (null != message.addressData) {
                    if (null == message.addressSignatureData) {
                        throw new ServletException("missing address data signature");
                    }
                    byte[] addressFile = trimRight(message.addressData);
                    verifySignature(message.rrnCertificate.getSigAlgName(), message.addressSignatureData,
                            rrnPublicKey, request, addressFile, message.identitySignatureData);
                }
            }

            LOG.debug("checking national registration certificate: "
                    + message.rrnCertificate.getSubjectX500Principal());
            List<X509Certificate> rrnCertificateChain = new LinkedList<X509Certificate>();
            rrnCertificateChain.add(message.rrnCertificate);
            //rrnCertificateChain.add(message.rootCertificate);
            identityIntegrityService.checkNationalRegistrationCertificate(rrnCertificateChain);
        }
    }

    signingCertificateChain.add(message.rrnCertificate); //Sabemos con certeza que el rmCert contiene el CA RAIZ
    for (X509Certificate certificate : signingCertificateChain) {
        LOG.debug("signing x509 cert: " + certificate.getSubjectX500Principal());

    }
    DigestInfo digestInfo;
    LOG.debug("signature service class: " + signatureService.getClass().getName());
    if (SignatureServiceEx.class.isAssignableFrom(signatureService.getClass())) {
        LOG.debug("SignatureServiceEx SPI implementation detected");
        /*
         * The SignatureServiceEx SPI can also receive the identity during
         * the pre-sign phase.
         */
        SignatureServiceEx signatureServiceEx = (SignatureServiceEx) signatureService;
        DTOMapper dtoMapper = new DTOMapper();
        IdentityDTO identityDTO = dtoMapper.map(identity, IdentityDTO.class);
        AddressDTO addressDTO = dtoMapper.map(address, AddressDTO.class);
        try {
            digestInfo = signatureServiceEx.preSign(null, signingCertificateChain, identityDTO, addressDTO,
                    message.photoData);
        } catch (NoSuchAlgorithmException e) {
            throw new ServletException("no such algo: " + e.getMessage(), e);
        }
    } else {
        LOG.debug("regular SignatureService SPI implementation");
        try {
            signatureService.setHttpSessionObject(request.getSession());
            digestInfo = signatureService.preSign(null, signingCertificateChain);
        } 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;
}

From source file:ca.sqlpower.architect.enterprise.ArchitectClientSideSession.java

/**
 * This method can update any users password on the server given the correct
 * old password and done by a user with the privileges to change the user's
 * password.// w  w w  .  ja  va 2s. c o  m
 * 
 * @param session
 *            The client session that has the correct server information to
 *            post requests to the server.
 * @param username
 *            The user name of the user to update.
 * @param oldPassword
 *            The old password of the user to validate that the password can
 *            be updated correctly.
 * @param newPassword
 *            The new password to update to.
 * @param upf
 *            A user prompter to display message and error information to
 *            the user as necessary.
 */
public void updateUserPassword(User user, String oldPassword, String newPassword, UserPrompterFactory upf) {
    SPServerInfo serviceInfo = getProjectLocation().getServiceInfo();

    HttpClient client = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore);

    MessageDigest digester;
    try {
        digester = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }

    try {
        JSONObject begin = new JSONObject();
        begin.put("uuid", JSONObject.NULL);
        begin.put("method", "begin");

        JSONObject persist = new JSONObject();
        persist.put("uuid", user.getUUID());
        persist.put("propertyName", "password");
        persist.put("type", Datatype.STRING.toString());
        if (oldPassword == null) {
            persist.put("method", "persistProperty");
        } else {
            persist.put("method", "changeProperty");
            persist.put("oldValue", new String(Hex.encodeHex(digester.digest(oldPassword.getBytes()))));
        }
        persist.put("newValue", new String(Hex.encodeHex(digester.digest(newPassword.getBytes()))));

        JSONObject commit = new JSONObject();
        commit.put("uuid", JSONObject.NULL);
        commit.put("method", "commit");

        JSONArray transaction = new JSONArray();
        transaction.put(begin);
        transaction.put(persist);
        transaction.put(commit);

        URI serverURI = new URI("http", null, serviceInfo.getServerAddress(), serviceInfo.getPort(),
                serviceInfo.getPath() + "/" + ClientSideSessionUtils.REST_TAG + "/project/system",
                "currentRevision=" + getCurrentRevisionNumber(), null);
        HttpPost postRequest = new HttpPost(serverURI);
        postRequest.setEntity(new StringEntity(transaction.toString()));
        postRequest.setHeader("Content-Type", "application/json");
        HttpUriRequest request = postRequest;
        JSONMessage result = client.execute(request, new JSONResponseHandler());
        if (result.getStatusCode() != 200) {
            logger.warn("Failed password change");
            if (result.getStatusCode() == 412) {
                upf.createUserPrompter("The password you have entered is incorrect.", UserPromptType.MESSAGE,
                        UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
            } else {
                upf.createUserPrompter(
                        "Could not change the password due to the following: " + result.getBody()
                                + " See logs for more details.",
                        UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK")
                        .promptUser("");
            }
        } else {
            upf.createUserPrompter(
                    "Password successfully changed. Please log into open projects" + " with your new password.",
                    UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK")
                    .promptUser("");
        }
    } catch (AccessDeniedException ex) {
        logger.warn("Failed password change", ex);
        upf.createUserPrompter("The password you have entered is incorrect.", UserPromptType.MESSAGE,
                UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
    } catch (Exception ex) {
        logger.warn("Failed password change", ex);
        upf.createUserPrompter(
                "Could not change the password due to the following: " + ex.getMessage()
                        + " See logs for more details.",
                UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
    }
}