Example usage for java.security MessageDigest getInstance

List of usage examples for java.security MessageDigest getInstance

Introduction

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

Prototype

public static MessageDigest getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a MessageDigest object that implements the specified digest algorithm.

Usage

From source file:com.skilrock.lms.common.utility.MD5Encoder.java

public static String encode(String value) {

    try {//from w  ww .  ja v  a  2 s  . c  o m

        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] hashMD5 = md5.digest(value.getBytes());
        return (new BASE64Encoder()).encode(hashMD5);

    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();
    }

    return null;
}

From source file:org.sharetask.utility.HashCodeUtil.java

public static String getHashCode(final String data) {
    try {//from  w  w  w .ja v  a  2s .  c  o  m
        final MessageDigest mda = MessageDigest.getInstance("SHA-512");
        final String baseSalt = String.valueOf(System.currentTimeMillis());
        final byte[] digest = mda.digest(baseSalt.getBytes(Charset.forName("UTF-8")));
        return new String(Hex.encode(digest));
    } catch (final NoSuchAlgorithmException e) {
        throw new UnsupportedOperationException(e);
    }
}

From source file:Main.java

public static byte[] getMD5Digest(String str) {
    if (str != null) {
        try {//from   w w  w  .j  a  v  a2 s .c o  m
            if (sMD5Digest == null) {
                sMD5Digest = MessageDigest.getInstance("MD5");
            }
            synchronized (sMD5Digest) {
                sMD5Digest.reset();
                return sMD5Digest.digest(str.getBytes("UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    return null;
}

From source file:Main.java

public static String getMd5Hash(File file) {
    try {/*from  w  w  w . j  av  a 2  s .  com*/
        // CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
        MessageDigest md = MessageDigest.getInstance("MD5");
        int chunkSize = 256;

        byte[] chunk = new byte[chunkSize];

        // Get the size of the file
        long lLength = file.length();

        if (lLength > Integer.MAX_VALUE) {
            Log.e(t, "File " + file.getName() + "is too large");
            return null;
        }

        int length = (int) lLength;

        InputStream is = null;
        is = new FileInputStream(file);

        int l = 0;
        for (l = 0; l + chunkSize < length; l += chunkSize) {
            is.read(chunk, 0, chunkSize);
            md.update(chunk, 0, chunkSize);
        }

        int remaining = length - l;
        if (remaining > 0) {
            is.read(chunk, 0, remaining);
            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) {
        Log.e("MD5", e.getMessage());
        return null;

    } catch (FileNotFoundException e) {
        Log.e("No Cache File", e.getMessage());
        return null;
    } catch (IOException e) {
        Log.e("Problem reading from file", e.getMessage());
        return null;
    }

}

From source file:com.gmu.uav.RadioSecurity.java

public static String computeSHA256(String password) {
    MessageDigest messagDigest = null;
    String saltedPassword = null;

    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[SALT_BYTES];
    random.nextBytes(salt);//from  www.ja v  a 2  s .c o m

    saltedPassword = salt + password;

    try {

        messagDigest = MessageDigest.getInstance("SHA-256");

    } catch (NoSuchAlgorithmException e) {

        e.printStackTrace();
    }

    messagDigest.update(saltedPassword.getBytes());

    byte finalHash[] = messagDigest.digest();

    return HASH_ITERATIONS + ":" + toHex(salt) + ":" + toHex(finalHash);
}

From source file:com.google.api.ads.adwords.awreporting.model.util.UrlHashUtil.java

/**
 * Creates a SHA-1 Hash of the url// ww  w.  j  ava 2s.c o  m
 * 
 * @param url the url that needs to be hashed
 * @return a Stri g with a SHA-1 hash of the URL
 */
public static String createUrlHash(String url) {
    String hash = null;
    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.reset();
        messageDigest.update(url.getBytes("UTF-8"));
        final byte[] resultByte = messageDigest.digest();
        hash = new String(Hex.encodeHex(resultByte));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return hash;
}

From source file:Main.java

/**
 * Returns the {@link Certificate} fingerprint as returned by <code>keytool</code>.
 *
 * @param certificate//ww w .  ja va  2  s . com
 * @param hashAlgorithm
 */
public static String getFingerprint(Certificate cert, String hashAlgorithm) {
    if (cert == null) {
        return null;
    }
    try {
        MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
        return toHexadecimalString(digest.digest(cert.getEncoded()));
    } catch (NoSuchAlgorithmException e) {
        // ignore
    } catch (CertificateEncodingException e) {
        // ignore
    }
    return null;
}

From source file:it.paolorendano.clm.util.Utils.java

/**
 * Hash password./*from www.  j  a v  a 2s.  c  o m*/
 *
 * @param password the password
 * @return the string
 */
public static String hashPassword(String password) {
    MessageDigest mdigest;
    try {
        mdigest = MessageDigest.getInstance("SHA-256");
        mdigest.update(password.getBytes("UTF-8"));
        return Base64.encodeBase64String(mdigest.digest());
    } catch (NoSuchAlgorithmException e) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.destroystokyo.paperclip.Paperclip.java

static void run(final String[] args) {
    try {//from  w w w.  j a  v a  2  s .c  o m
        digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        System.err.println("Could not create hashing instance");
        e.printStackTrace();
        System.exit(1);
    }

    final PatchData patchInfo;
    try (final InputStream is = getConfig()) {
        patchInfo = PatchData.parse(is);
    } catch (final IllegalArgumentException e) {
        System.err.println("Invalid patch file");
        e.printStackTrace();
        System.exit(1);
        return;
    } catch (final IOException e) {
        System.err.println("Error reading patch file");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    final File vanillaJar = new File(cache, "mojang_" + patchInfo.getVersion() + ".jar");
    paperJar = new File(cache, "patched_" + patchInfo.getVersion() + ".jar");

    final boolean vanillaValid;
    final boolean paperValid;
    try {
        vanillaValid = checkJar(vanillaJar, patchInfo.getOriginalHash());
        paperValid = checkJar(paperJar, patchInfo.getPatchedHash());
    } catch (final IOException e) {
        System.err.println("Error reading jar");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    if (!paperValid) {
        if (!vanillaValid) {
            System.out.println("Downloading original jar...");
            //noinspection ResultOfMethodCallIgnored
            cache.mkdirs();
            //noinspection ResultOfMethodCallIgnored
            vanillaJar.delete();

            try (final InputStream stream = patchInfo.getOriginalUrl().openStream()) {
                final ReadableByteChannel rbc = Channels.newChannel(stream);
                try (final FileOutputStream fos = new FileOutputStream(vanillaJar)) {
                    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
                }
            } catch (final IOException e) {
                System.err.println("Error downloading original jar");
                e.printStackTrace();
                System.exit(1);
            }

            // Only continue from here if the downloaded jar is correct
            try {
                if (!checkJar(vanillaJar, patchInfo.getOriginalHash())) {
                    System.err.println("Invalid original jar, quitting.");
                    System.exit(1);
                }
            } catch (final IOException e) {
                System.err.println("Error reading jar");
                e.printStackTrace();
                System.exit(1);
            }
        }

        if (paperJar.exists()) {
            if (!paperJar.delete()) {
                System.err.println("Error deleting invalid jar");
                System.exit(1);
            }
        }

        System.out.println("Patching original jar...");
        final byte[] vanillaJarBytes;
        final byte[] patch;
        try {
            vanillaJarBytes = getBytes(vanillaJar);
            patch = Utils.readFully(patchInfo.getPatchFile().openStream());
        } catch (final IOException e) {
            System.err.println("Error patching original jar");
            e.printStackTrace();
            System.exit(1);
            return;
        }

        // Patch the jar to create the final jar to run
        try (final FileOutputStream jarOutput = new FileOutputStream(paperJar)) {
            Patch.patch(vanillaJarBytes, patch, jarOutput);
        } catch (final CompressorException | InvalidHeaderException | IOException e) {
            System.err.println("Error patching origin jar");
            e.printStackTrace();
            System.exit(1);
        }
    }

    // Exit if user has set `paperclip.patchonly` system property to `true`
    if (Boolean.getBoolean("paperclip.patchonly")) {
        System.exit(0);
    }

    // Get main class info from jar
    final String main;
    try (final FileInputStream fs = new FileInputStream(paperJar);
            final JarInputStream js = new JarInputStream(fs)) {
        main = js.getManifest().getMainAttributes().getValue("Main-Class");
    } catch (final IOException e) {
        System.err.println("Error reading from patched jar");
        e.printStackTrace();
        System.exit(1);
        return;
    }

    // Run the jar
    Utils.invoke(main, args);
}

From source file:Main.java

private static String computeHash(InputStream dataStream) throws IOException, NoSuchAlgorithmException {
    MessageDigest messageDigest = null;
    DigestInputStream digestInputStream = null;
    try {/* w  w  w. j a  v a  2 s.  c  om*/
        messageDigest = MessageDigest.getInstance("SHA-256");
        digestInputStream = new DigestInputStream(dataStream, messageDigest);
        byte[] byteBuffer = new byte[1024 * 8];
        while (digestInputStream.read(byteBuffer) != -1)
            ;
    } finally {
        try {
            if (digestInputStream != null)
                digestInputStream.close();
            if (dataStream != null)
                dataStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    byte[] hash = messageDigest.digest();
    return String.format("%064x", new java.math.BigInteger(1, hash));
}