sha256 Digest String - Java Security

Java examples for Security:SHA

Description

sha256 Digest String

Demo Code


//package com.java2s;

import java.security.MessageDigest;

public class Main {
    public static void main(String[] argv) throws Exception {
        String input = "java2s.com";
        String charset = "java2s.com";
        System.out.println(sha256Digest(input, charset));
    }/*from   ww w  . jav  a  2  s  .co m*/

    public static String sha256Digest(String input, String charset) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md.digest(input.getBytes(charset));

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

            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials