Calculates the SHA256 hash of the string. - Java Security

Java examples for Security:SHA

Description

Calculates the SHA256 hash of the string.

Demo Code

/*/*from   www  . ja  v  a  2s.  c  om*/
 * Copyright (C) 2015 the original author or authors.
 *
 * 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.
 */
//package com.java2s;

import java.nio.charset.StandardCharsets;

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

public class Main {
    /**
     * Calculates the SHA256 hash of the string.
     *
     * @param text
     * @return sha256 hash of the string
     */
    public static String getHashSHA256(String text) {
        byte[] bytes = text.getBytes(StandardCharsets.ISO_8859_1);
        return getHashSHA256(bytes);
    }

    /**
     * Calculates the SHA256 hash of the byte array.
     *
     * @param bytes
     * @return sha256 hash of the byte array
     */
    public static String getHashSHA256(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(bytes, 0, bytes.length);
            byte[] digest = md.digest();
            return toHex(digest);
        } catch (NoSuchAlgorithmException t) {
            throw new RuntimeException(t);
        }
    }

    public static String toHex(byte[] bytes) {
        StringBuilder hash = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        return hash.toString();
    }
}

Related Tutorials