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:org.sipfoundry.sipxconfig.phone.grandstream.ResetPacket.java

ResetPacket(String password, String macAddress) {
    m_message = new byte[MESSAGE_LEN];
    MessageDigest mymd;

    try {/*  w  w  w . jav a2 s  . c o  m*/
        mymd = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException blaa) {
        throw new IllegalArgumentException("MD5 unknown");
    }

    m_message[0] = 0;
    m_message[1] = 1;
    m_message[2] = 0;
    m_message[3] = 0;

    int timeCode = getTimeCode();
    m_message[4] = (byte) ((timeCode >> 24) & 0xff);
    m_message[5] = (byte) ((timeCode >> 16) & 0xff);
    m_message[6] = (byte) ((timeCode >> 8) & 0xff);
    m_message[7] = (byte) (timeCode & 0xff);

    mymd.reset();
    try {
        mymd.update(Hex.decodeHex(macAddress.toCharArray()));
    } catch (DecoderException e) {
        throw new RuntimeException("hex string must be multiples of 2", e);
    }
    byte[] colon = new byte[] { ':' };
    mymd.update(colon);
    mymd.update(password.getBytes());
    mymd.update(colon);
    mymd.update(m_message, 4, 4);
    System.arraycopy(mymd.digest(), 0, m_message, 8, 16);
}

From source file:nl.surfnet.coin.janus.JanusRestClient.java

/**
 * Sign the given method call.//from  w  w  w . j  a  va 2  s.  c  o  m
 * 
 * @param method
 *          the name of the method to call
 * @param parameters
 *          additional parameters that need to be passed to Janus
 * @return URI with parameters janus_sig and janus_key
 * @throws IOException
 */
private URI sign(String method, Map<String, String> parameters) throws IOException {
    Map<String, String> keys = new TreeMap<String, String>();
    keys.put("janus_key", user);
    keys.put("method", method);

    keys.putAll(parameters);

    keys.put("rest", "1");
    keys.put("userid", user);
    Set<String> keySet = keys.keySet();
    StringBuilder toSign = new StringBuilder(secret);
    for (String key : keySet) {
        toSign.append(key);
        toSign.append(keys.get(key));
    }

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("SHA-512");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Cannot use algorithm SHA-512", e);
    }
    digest.reset();
    final String charsetName = "UTF-8";
    byte[] input = digest.digest(toSign.toString().getBytes(charsetName));
    char[] value = Hex.encodeHex(input);
    String janus_sig = new String(value);
    keys.put("janus_sig", janus_sig);

    StringBuilder url = new StringBuilder();
    keySet = keys.keySet();
    for (String key : keySet) {
        if (url.length() > 0) {
            url.append('&');
        }
        url.append(key).append('=').append(URLEncoder.encode(keys.get(key), charsetName));
    }
    String uri = url.toString();
    return URI.create(janusUri + "?" + uri);
}

From source file:com.yobidrive.diskmap.needles.Needle.java

public byte[] hashMD5() throws Exception {

    MessageDigest md = null;
    md = MessageDigest.getInstance("MD5");
    md.update(keyBytes);/*from w  w  w  . j ava 2 s.c  o m*/
    if (version != null)
        md.update(version.toBytes());
    md.update(flags);
    if (data != null && data.length > 0)
        md.update(data);
    byte[] v = md.digest();
    md.reset();
    return v;
}

From source file:org.apache.syncope.core.persistence.beans.user.SyncopeUser.java

private String encodePassword(final String password, final CipherAlgorithm cipherAlgoritm)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    String encodedPassword = null;

    if (password != null) {
        if (cipherAlgoritm == null || cipherAlgoritm == CipherAlgorithm.AES) {

            final byte[] cleartext = password.getBytes("UTF8");

            final Cipher cipher = Cipher.getInstance(CipherAlgorithm.AES.getAlgorithm());

            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            byte[] encoded = cipher.doFinal(cleartext);

            encodedPassword = new String(Base64.encode(encoded));
        } else {//from  w  w  w . j a  v a 2  s.  com
            MessageDigest algorithm = MessageDigest.getInstance(cipherAlgoritm.getAlgorithm());

            algorithm.reset();
            algorithm.update(password.getBytes());

            byte[] messageDigest = algorithm.digest();

            StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < messageDigest.length; i++) {
                String hex = Integer.toHexString(0xff & messageDigest[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            encodedPassword = hexString.toString();
        }
    }

    return encodedPassword;
}

From source file:org.sakaiproject.tool.impl.SessionComponent.java

public String makeSessionId(HttpServletRequest req, Principal principal) {
    MessageDigest sha;
    String sessionId;/*w  ww. jav  a  2 s .  c  o  m*/

    try {
        sha = MessageDigest.getInstance("SHA-1");

        sha.reset();
        sha.update(principal.getName().getBytes("UTF-8"));
        sha.update((byte) 0x0a);
        String ua = req.getHeader("user-agent");
        if (ua != null) {
            sha.update(ua.getBytes("UTF-8"));
        }
        sha.update(salt);

        sessionId = byteArrayToHexStr(sha.digest());
    } catch (NoSuchAlgorithmException e) {
        // Fallback to new uuid rather than a non-hashed id
        sessionId = idManager().createUuid();
        //This may need to be changed to a debug
        M_log.warn("makeSessionId fallback to Uuid!", e);

    } catch (UnsupportedEncodingException e) {
        sessionId = idManager().createUuid();
        //This may need to be changed to a debug
        M_log.warn("makeSessionId fallback to Uuid!", e);
    }

    return sessionId;
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java

/**
 * Produce a hash for the storage descriptor
 * @param sd storage descriptor to hash/*from ww  w. jav  a 2  s. c  o m*/
 * @param md message descriptor to use to generate the hash
 * @return the hash as a byte array
 */
public static synchronized byte[] hashStorageDescriptor(StorageDescriptor sd, MessageDigest md) {
    // Note all maps and lists have to be absolutely sorted.  Otherwise we'll produce different
    // results for hashes based on the OS or JVM being used.
    md.reset();
    // In case cols are null
    if (sd.getCols() != null) {
        for (FieldSchema fs : sd.getCols()) {
            md.update(fs.getName().getBytes(ENCODING));
            md.update(fs.getType().getBytes(ENCODING));
            if (fs.getComment() != null) {
                md.update(fs.getComment().getBytes(ENCODING));
            }
        }
    }
    if (sd.getInputFormat() != null) {
        md.update(sd.getInputFormat().getBytes(ENCODING));
    }
    if (sd.getOutputFormat() != null) {
        md.update(sd.getOutputFormat().getBytes(ENCODING));
    }
    md.update(sd.isCompressed() ? "true".getBytes(ENCODING) : "false".getBytes(ENCODING));
    md.update(Integer.toString(sd.getNumBuckets()).getBytes(ENCODING));
    if (sd.getSerdeInfo() != null) {
        SerDeInfo serde = sd.getSerdeInfo();
        if (serde.getName() != null) {
            md.update(serde.getName().getBytes(ENCODING));
        }
        if (serde.getSerializationLib() != null) {
            md.update(serde.getSerializationLib().getBytes(ENCODING));
        }
        if (serde.getParameters() != null) {
            SortedMap<String, String> params = new TreeMap<>(serde.getParameters());
            for (Map.Entry<String, String> param : params.entrySet()) {
                md.update(param.getKey().getBytes(ENCODING));
                md.update(param.getValue().getBytes(ENCODING));
            }
        }
    }
    if (sd.getBucketCols() != null) {
        List<String> bucketCols = new ArrayList<>(sd.getBucketCols());
        for (String bucket : bucketCols) {
            md.update(bucket.getBytes(ENCODING));
        }
    }
    if (sd.getSortCols() != null) {
        SortedSet<Order> orders = new TreeSet<>(sd.getSortCols());
        for (Order order : orders) {
            md.update(order.getCol().getBytes(ENCODING));
            md.update(Integer.toString(order.getOrder()).getBytes(ENCODING));
        }
    }
    if (sd.getSkewedInfo() != null) {
        SkewedInfo skewed = sd.getSkewedInfo();
        if (skewed.getSkewedColNames() != null) {
            SortedSet<String> colnames = new TreeSet<>(skewed.getSkewedColNames());
            for (String colname : colnames) {
                md.update(colname.getBytes(ENCODING));
            }
        }
        if (skewed.getSkewedColValues() != null) {
            SortedSet<String> sortedOuterList = new TreeSet<>();
            for (List<String> innerList : skewed.getSkewedColValues()) {
                SortedSet<String> sortedInnerList = new TreeSet<>(innerList);
                sortedOuterList.add(org.apache.commons.lang.StringUtils.join(sortedInnerList, "."));
            }
            for (String colval : sortedOuterList) {
                md.update(colval.getBytes(ENCODING));
            }
        }
        if (skewed.getSkewedColValueLocationMaps() != null) {
            SortedMap<String, String> sortedMap = new TreeMap<>();
            for (Map.Entry<List<String>, String> smap : skewed.getSkewedColValueLocationMaps().entrySet()) {
                SortedSet<String> sortedKey = new TreeSet<>(smap.getKey());
                sortedMap.put(org.apache.commons.lang.StringUtils.join(sortedKey, "."), smap.getValue());
            }
            for (Map.Entry<String, String> e : sortedMap.entrySet()) {
                md.update(e.getKey().getBytes(ENCODING));
                md.update(e.getValue().getBytes(ENCODING));
            }
        }
        md.update(sd.isStoredAsSubDirectories() ? "true".getBytes(ENCODING) : "false".getBytes(ENCODING));
    }

    return md.digest();
}

From source file:nya.miku.wishmaster.api.AbstractLynxChanModule.java

private String computeFileMD5(File file) throws NoSuchAlgorithmException, IOException {
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    messageDigest.reset();

    FileInputStream fis = new FileInputStream(file);
    byte[] byteArray = new byte[1024];
    int bytesCount;
    while ((bytesCount = fis.read(byteArray)) != -1) {
        messageDigest.update(byteArray, 0, bytesCount);
    }/* w  w  w.j a  v a  2s .c o  m*/
    fis.close();

    byte[] digest = messageDigest.digest();
    BigInteger bigInt = new BigInteger(1, digest);
    String md5Hex = bigInt.toString(16);
    if (md5Hex.length() < 32) {
        char[] head = new char[32 - md5Hex.length()];
        Arrays.fill(head, '0');
        md5Hex = new StringBuilder(32).append(head).append(md5Hex).toString();
    }
    return md5Hex;
}

From source file:com.ooyala.api.OoyalaAPI.java

/**
 * Generates the signature for a request, using a body in the request.
 * If the method is a GET, then it does not need the body. On the other hand
 * if it is a POST, PUT or PATCH, the body is a string with the parameters that
 * are going to be modified, or assigned to the resource.
 * This should be later added to the query parameters,
 * as the signature parameter of the desired requested URI.
 *
 * @param HTTPMethod The method of the request (GET, POST, PUT, PATCH).
 * @param requestPath The path of the request (i.e. /v2/players).
 * @param parameters The query parameters.
 * @param requestBody The body of the request, used for POST, PUT and PATCH.
 * @return The signature that should be added to the request URI as the signature parameter.
 * @throws NoSuchAlgorithmException if the SHA256 algorithm is not available.
 * @throws IOException //from   w w w. j  ava2  s .c om
 * @throws JsonMappingException 
 * @throws JsonGenerationException 
 */

public String generateSignature(String HTTPMethod, String requestPath, HashMap<String, String> parameters,
        String requestBody) throws NoSuchAlgorithmException, IOException {
    String stringToSign = secretKey + HTTPMethod + "/v2/" + requestPath;
    stringToSign += concatenateParams(parameters, "");
    stringToSign += requestBody;
    log.d("String to sign: " + stringToSign);
    MessageDigest digestProvider = MessageDigest.getInstance("SHA-256");
    digestProvider.reset();
    byte[] digest = digestProvider.digest(stringToSign.getBytes(apiCharset));
    String signedInput = Base64.encodeBase64String(digest);

    return encodeURI(signedInput.substring(0, 43));
}

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

public void update() throws Exception {
    StringBuilder builder = new StringBuilder(32);
    MessageDigest digest = DIGESTS.get();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    InputStream inputStream = resource.getInputStream();

    try {/*from ww w.j  a va 2s.c  o m*/
        lastModified = resource.lastModified();
        IOUtils.copyLarge(inputStream, outputStream);
        compressedFile = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
    } finally {
        inputStream.close();
    }

    if (minify) {
        compressedFile = minifier.minify(compressedFile);
    }

    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();
    bytes = null;
}

From source file:wssec.TestWSSecurityNew5.java

/**
 * Test that adds a UserNameToken with a digested password but with type of
 * password test./*ww  w .j  a  va 2s  .  c om*/
 */
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 = unsignedEnvelope.getAsDocument();
    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);
    }
}