import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256Test {
public static final String ALGORITHM = "SHA-256";
public static String SHA256Encrypt(String orignal) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance(ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if (null != md) {
byte[] origBytes = orignal.getBytes();
md.update(origBytes);
byte[] digestRes = md.digest();
String digestStr = getDigestStr(digestRes);
return digestStr;
}
return null;
}
private static String getDigestStr(byte[] origBytes) {
String tempStr = null;
StringBuilder stb = new StringBuilder();
for (int i = 0; i < origBytes.length; i++) {
// System.out.println("and by bit: " + (origBytes[i] & 0xff));
// System.out.println("no and: " + origBytes[i]);
// System.out.println("---------------------------------------------");
// 這里按位與是為了把字節轉整時候取其正確的整數,java中一個int是4個字節
// 如果origBytes[i]最高位為1,則轉為int時,int的前三個字節都被1填充了
tempStr = Integer.toHexString(origBytes[i] & 0xff);
if (tempStr.length() == 1) {
stb.append("0");
}
stb.append(tempStr);
}
return stb.toString();
}
public static void main(String[] args) {
System.out.println(SHA256Encrypt("AAaa11"));
}
}