Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright (C) 2014 SCVNGR, Inc. d/b/a LevelUp
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**
     * @param data the data to hash
     * @param byteDelimiter an optional delimiter between bytes.
     * @return a sha1 digest of the data, as a string with bytes delimited by byteDelimiter
     */
    private static String getHexHash(final byte[] data, final Character byteDelimiter) {
        try {
            final byte[] hash = MessageDigest.getInstance("SHA1").digest(data);

            return convertBytesToHex(hash, byteDelimiter);
        } catch (final NoSuchAlgorithmException e) {
            // this should never occur
            throw new RuntimeException(e);
        }
    }

    /**
     * @param data the input data.
     * @param byteDelimiter a character to separate bytes or null if none is desired.
     * @return the data as a hex string, optionally delimited by the byteDelimiter.
     */
    /* package */
    static String convertBytesToHex(final byte[] data, final Character byteDelimiter) {
        final StringBuilder sb = new StringBuilder();
        boolean needsSeparator = false;

        for (final byte datum : data) {
            if (needsSeparator && byteDelimiter != null) {
                sb.append(byteDelimiter);
            }

            // get the unsigned portion
            final int v = datum & 0xFF;

            if (v < 0x10) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
            needsSeparator = true;
        }

        return sb.toString();
    }
}