Java SHA sha(String source)

Here you can find the source of sha(String source)

Description

Converts a java.lang.String in to a SHA hashed String

License

LGPL

Parameter

Parameter Description
source the source String

Return

the MD5 hashed version of the string

Declaration

public static String sha(String source) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.io.*;

import java.security.MessageDigest;

public class Main {
    /**//  ww  w. java  2 s  .c  om
     * Converts a java.lang.String in to a SHA hashed String
     * @param source the source String
     * @return the MD5 hashed version of the string
     */
    public static String sha(String source) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            byte[] bytes = md.digest(source.getBytes());
            return getString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
    * Used to convert a byte array in to a java.lang.String object
    * @param bytes the bytes to be converted
    * @return the String representation
    */
    private static String getString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            sb.append(0x00FF & b);
            if (i + 1 < bytes.length) {
                sb.append("-");
            }
        }
        return sb.toString();
    }

    /**
     * Use with caution: lots of overhead
     */
    public static String printStackTrace(Throwable t) {
        StringWriter s = new StringWriter();
        PrintWriter p = new PrintWriter(s);
        t.printStackTrace(p);
        return s.toString();
    }
}

Related

  1. sha(byte data[])
  2. sha(byte[] data)
  3. SHA(String s)
  4. sha(String str)
  5. sha(String strPlain)
  6. sha(String text, String encoding)
  7. sha2(String content)