Java SHA256 sha256(InputStream data)

Here you can find the source of sha256(InputStream data)

Description

sha

License

Apache License

Declaration

private static String sha256(InputStream data) throws IOException 

Method Source Code

//package com.java2s;
/*//from  w ww  .  j  a  va 2 s  .com
 * Copyright 2010-2012, CloudBees Inc.
 *
 * 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.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final int STREAM_BUFFER_LENGTH = 1024;
    private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();

    private static String sha256(InputStream data) throws IOException {
        MessageDigest digest = getDigest("SHA-256");
        byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
        int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);

        while (read > -1) {
            digest.update(buffer, 0, read);
            read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
        }

        return asHex(digest.digest());
    }

    static MessageDigest getDigest(String algorithm) {
        try {
            return MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private static String asHex(byte[] buf) {
        char[] chars = new char[2 * buf.length];
        for (int i = 0; i < buf.length; ++i) {
            chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
            chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
        }
        return new String(chars);
    }
}

Related

  1. SHA256(byte[] P)
  2. SHA256(byte[] src)
  3. SHA256(ByteBuffer buf, int off, int length)
  4. sha256(final InputStream inputStream)
  5. sha256(final String string)
  6. sha256(String base)
  7. sha256(String base)
  8. sha256(String data)
  9. sha256(String Input)