Example usage for java.security MessageDigest reset

List of usage examples for java.security MessageDigest reset

Introduction

In this page you can find the example usage for java.security MessageDigest reset.

Prototype

public void reset() 

Source Link

Document

Resets the digest for further use.

Usage

From source file:com.borhan.client.BorhanClientBase.java

private byte[] signInfoWithSHA1(byte[] data) throws GeneralSecurityException {
    MessageDigest algorithm = MessageDigest.getInstance("SHA1");
    algorithm.reset();
    algorithm.update(data);//from  ww w .j a  va2s .  co m
    byte infoSignature[] = algorithm.digest();
    return infoSignature;
}

From source file:org.getobjects.foundation.UString.java

/**
 * Calculates an MD5 hash on the string. To do so the String is first
 * converted to UTF-8 and then run through the appropriate MessageDigest. This
 * method is not exactly high performance, if you need to encode a lot of
 * strings you might want to do it manually.
 * /*from w  w w .j a va  2 s .c o  m*/
 * @param _p - the String which a hash shall be calculated for
 * @return the hash as a String
 */
public static String md5HashForString(final String _p) {
    if (_p == null)
        return null;

    String pwdhash = null;
    try {
        // TODO: cache digest in thread local variable?
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(getBytes(_p, null));

        byte[] bytehash = md5.digest();
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytehash.length; i++) {
            String s = Integer.toHexString(0xFF & bytehash[i]);
            if (s.length() == 1)
                s = "0" + s;
            hexString.append(s);
        }
        md5.reset();

        pwdhash = hexString.toString();
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Did not find MD5 hash generator!");
        return null;
    }

    if (pwdhash == null || pwdhash.length() == 0) {
        log.error("Could not compute an MD5 hash.");
        return null;
    }
    return pwdhash;
}

From source file:org.liquidsite.core.content.User.java

/**
 * Creates an ASCII hash value for a string. The hash value
 * calculation is irreversible, and is calculated with the MD5
 * algorithm and encoded with base-64.//from  w  w  w .  j  av a2s .  c  o m
 *
 * @param input           the input string data
 *
 * @return the encoded hash value
 */
private String createHash(String input) {
    MessageDigest digest;
    byte bytes[];

    // Compute MD5 digest
    try {
        digest = MessageDigest.getInstance("MD5");
        digest.reset();
        digest.update(input.getBytes());
        bytes = digest.digest();
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage());
        return "";
    }

    // Base-64 encode digest
    return new String(Base64.encodeBase64(bytes));
}

From source file:org.apache.ws.security.message.WSSecSignature.java

private String getSHA1(byte[] input) throws WSSecurityException {
    try {/*from   w ww. ja v  a 2s. c om*/
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.reset();
        sha.update(input);
        byte[] data = sha.digest();

        return Base64.encode(data);
    } catch (NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
    }
}

From source file:org.apache.ws.security.message.UsernameTokenTest.java

/**
 * Test that adds a UserNameToken with a digested password but with type of
 * password test.//from w w  w .  j  a  v  a2  s .c  o  m
 */
@org.junit.Test
public void testUsernameTokenDigestText() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_TEXT);
    byte[] password = "verySecret".getBytes();
    MessageDigest sha = MessageDigest.getInstance("MD5");
    sha.reset();
    sha.update(password);
    String passwdDigest = Base64.encode(sha.digest());

    builder.setUserInfo("wernerd", passwdDigest);
    LOG.info("Before adding UsernameToken PW Text....");
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document signedDoc = builder.build(doc, secHeader);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Message with UserNameToken PW Text:");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(signedDoc);
        LOG.debug(outputString);
    }
}

From source file:org.sakaiproject.search.index.impl.SegmentState.java

/**
 * @param segInfo/*  w  w  w  . ja v a 2  s.c  om*/
 */
public void analyze(SegmentInfo segInfo) {
    File[] files = segInfo.getSegmentLocation().listFiles();
    String basePath = segInfo.getSegmentLocation().getAbsolutePath();
    fileRecords = new HashMap<String, FileRecord>();
    MessageDigest md5 = null;
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        log.error("Segment (" + name + "): MD5 not available ", e);
    }
    byte[] buffer = new byte[4096];
    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            try {
                String echecksum = "none";
                if (md5 != null) {
                    InputStream fin = new FileInputStream(files[i]);
                    int len = 0;
                    md5.reset();
                    while ((len = fin.read(buffer)) > 0) {
                        md5.update(buffer, 0, len);
                    }
                    fin.close();
                    char[] encoding = "0123456789ABCDEF".toCharArray();
                    byte[] checksum = md5.digest();
                    char[] hexchecksum = new char[checksum.length * 2];
                    for (int j = 0; j < checksum.length; j++) {
                        int lo = checksum[j] & 0x0f;
                        int hi = (checksum[j] >> 4) & 0x0f;
                        hexchecksum[j * 2] = encoding[lo];
                        hexchecksum[j * 2 + 1] = encoding[hi];
                    }
                    echecksum = new String(hexchecksum);
                }
                FileRecord fr = new FileRecord();
                fr.checksum = echecksum;
                fr.path = files[i].getAbsolutePath().substring(basePath.length());
                fr.lastMod = files[i].lastModified();
                fr.length = files[i].length();
                fileRecords.put(fr.path, fr);
            } catch (Exception ex) {
                log.error(
                        "Segment (" + name + "): Failed to generate checksum of " + files[i].getAbsolutePath(),
                        ex);
            }
        }
    }

}

From source file:org.apache.cxf.maven_plugin.AbstractCodegenMoho.java

protected File getDoneFile(URI basedir, URI wsdlURI, String mojo) {
    String doneFileName = wsdlURI.toString();

    try {//from w  w  w.ja v a 2s .c  om
        MessageDigest cript = MessageDigest.getInstance("SHA-1");
        cript.reset();
        cript.update(doneFileName.getBytes("utf8"));
        doneFileName = new javax.xml.bind.annotation.adapters.HexBinaryAdapter().marshal(cript.digest());
    } catch (Exception e) {
        //ignore, we'll try and fake it based on the wsdl

        // Strip the basedir from the doneFileName
        if (doneFileName.startsWith(basedir.toString())) {
            doneFileName = doneFileName.substring(basedir.toString().length());
        }
        // If URL to WSDL, replace ? and & since they're invalid chars for file names
        // Not to mention slashes.
        doneFileName = doneFileName.replace('?', '_').replace('&', '_').replace('/', '_').replace('\\', '_')
                .replace(':', '_');
        doneFileName += ".DONE";
    }

    return new File(markerDirectory, "." + doneFileName);
}

From source file:com.qut.middleware.delegator.openid.authn.impl.AuthnProcessorImpl.java

private void verifyOpenIDAuthnResponse(AuthnProcessorData processorData, List<AttributeType> esoeAttributes)
        throws OpenIDException, NoSuchAlgorithmException {
    ParameterList response;//from ww w. j a  va 2s.  com
    DiscoveryInformation discovered;
    StringBuffer receivingURL;
    String queryString;
    VerificationResult verification;
    Identifier verified;
    AuthSuccess authSuccess;

    response = new ParameterList(processorData.getHttpRequest().getParameterMap());

    /* Retrieve the stored discovery information */
    discovered = (DiscoveryInformation) processorData.getHttpRequest().getSession()
            .getAttribute(ConfigurationConstants.OPENID_USER_SESSION_IDENTIFIER);

    /* Extract the receiving URL from the HTTP request */
    receivingURL = processorData.getHttpRequest().getRequestURL();

    /*
     * If a Layer 7 type device is offloading https change the recievingURL accordingly to ensure
     * correct verification
     */
    if (httpsOffload) {
        receivingURL.delete(0, 4);
        receivingURL.insert(0, "https");
    }

    queryString = processorData.getHttpRequest().getQueryString();
    if (queryString != null && queryString.length() > 0)
        receivingURL.append("?").append(processorData.getHttpRequest().getQueryString());

    /* Verify the response */
    this.logger.debug("About to verify response, accepted at receivingURL of " + receivingURL
            + " server set return to as " + response.toString());

    verification = manager.verify(receivingURL.toString(), response, discovered);
    verified = verification.getVerifiedId();
    if (verified != null) {
        AttributeType esoeAttribute;
        MessageDigest algorithm;
        byte messageDigest[];

        authSuccess = (AuthSuccess) verification.getAuthResponse();

        /*
         * Merge verified ID to ESOE view, OpenID identifiers aren't really compatible with most applications as an
         * identifier, so we'll md5 hash them for presentation as uid
         */
        algorithm = MessageDigest.getInstance("MD5");
        algorithm.reset();
        algorithm.update(verification.getVerifiedId().getIdentifier().getBytes());
        messageDigest = algorithm.digest();

        esoeAttribute = new AttributeType();
        esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
        esoeAttribute.setName(this.userIdentifier);
        esoeAttribute.getAttributeValues()
                .add(new String(Hex.encodeHex(messageDigest)) + ConfigurationConstants.OPENID_NAMESPACE);
        esoeAttributes.add(esoeAttribute);

        /*
         * Store openID identifier in attributes for use by applications
         */
        esoeAttribute = new AttributeType();
        esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
        esoeAttribute.setName(ConfigurationConstants.OPENID_IDENTIFIER_ATTRIBUTE);
        esoeAttribute.getAttributeValues().add(verification.getVerifiedId().getIdentifier());
        esoeAttributes.add(esoeAttribute);

        /*
         * Retrieve requested attributes (if provided, given low deployments of attribute exchange currently we
         * don't fail when this isn't presented)
         */
        if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX)) {
            FetchResponse fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);

            for (OpenIDAttribute attribute : this.requestedAttributes) {
                List<String> values = fetchResp.getAttributeValues(attribute.getLabel());

                /* Merge to ESOE view */
                esoeAttribute = new AttributeType();
                esoeAttribute.setNameFormat(AttributeFormatConstants.basic);
                esoeAttribute.setName(attribute.getEsoeAttributeName());
                for (String value : values) {
                    esoeAttribute.getAttributeValues().add(attribute.getValuePrepend() + value);
                }
                esoeAttributes.add(esoeAttribute);
            }
        }
    } else {
        throw new OpenIDException("Attempt by manager to verify result returned null");
    }
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Generates a new unique message signature. This signature is expected to be used for creating a new message
 * instance, and is intended to uniquely identify the message regardless of which application is processing it.
 * <p>//w  w w.ja v a2  s .  c o m
 * It is up to the individual stream to determine which of these attributes is available/required to uniquely
 * identify a message. In order to identify a message within two different transports, the streams for each
 * transport must provide the same values.
 *
 * @param _msgDigest
 *            message type
 * @param msgType
 *            message type
 * @param msgFormat
 *            message format
 * @param msgId
 *            message identifier
 * @param userId
 *            user that originated the message
 * @param putApplType
 *            type of application that originated the message
 * @param putApplName
 *            name of application that originated the message
 * @param putDate
 *            date (GMT) the message was originated
 * @param putTime
 *            time (GMT) the message was originated
 * @return unique message signature
 */
public static String computeSignature(MessageDigest _msgDigest, MessageType msgType, String msgFormat,
        byte[] msgId, String userId, String putApplType, String putApplName, String putDate, String putTime) {
    _msgDigest.reset();
    if (msgType != null) {
        _msgDigest.update(String.valueOf(msgType.value()).getBytes());
    }
    if (msgFormat != null) {
        _msgDigest.update(msgFormat.trim().getBytes());
    }
    if (msgId != null) {
        _msgDigest.update(msgId);
    }
    if (userId != null) {
        _msgDigest.update(userId.trim().toLowerCase().getBytes());
    }
    if (putApplType != null) {
        _msgDigest.update(putApplType.trim().getBytes());
    }
    if (putApplName != null) {
        _msgDigest.update(putApplName.trim().getBytes());
    }
    if (putDate != null) {
        _msgDigest.update(putDate.trim().getBytes());
    }
    if (putTime != null) {
        _msgDigest.update(putTime.trim().getBytes());
    }
    return base64EncodeStr(_msgDigest.digest());
}

From source file:inti.ws.spring.resource.FilteredWebResource.java

@Override
public void update() throws Exception {
    ExpressionFactory factory;//www.  j a  v  a 2 s. c o  m
    ValueExpression var;
    Object val;
    StringBuilder builder = new StringBuilder(32);
    MessageDigest digest = DIGESTS.get();

    for (WebResource dependency : dependencies) {
        dependency.updateIfNeeded();
    }

    super.update();

    factory = ExpressionFactory.newInstance();
    content = factory.createValueExpression(context, compressedFile, String.class);
    for (Map.Entry<String, Object> parameter : parameters.entrySet()) {
        var = factory.createValueExpression(context, "${" + parameter.getKey() + '}', String.class);
        val = parameter.getValue();
        if (val instanceof WebResource) {
            ((WebResource) val).updateIfNeeded();
            val = ((WebResource) val).getContent().hashCode();
        }
        var.setValue(context, val);
    }
    compressedFile = (String) content.getValue(context);

    digest.reset();
    builder.append(Hex.encodeHexString(digest.digest(compressedFile.getBytes(StandardCharsets.UTF_8))));
    messageDigest = builder.toString();
    builder.delete(0, builder.length());

    DATE_FORMATTER.formatDate(lastModified, builder);
    lastModifiedString = builder.toString();
}