Information in Wikipedia
http://en.wikipedia.org/wiki/SHA-2
*/
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA {
private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++)
map1[i++] = c;
for (char c = 'a'; c <= 'z'; c++)
map1[i++] = c;
for (char c = '0'; c <= '9'; c++)
map1[i++] = c;
map1[i++] = '+';
map1[i++] = '/';
}
public SHA() {
}
public static String encodeBASE64(byte[] in, int iLen) {
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '=';
op++;
out[op] = op < oDataLen ? map1[o3] : '=';
op++;
}
//System.out.println("Char Len = " + out.length);
return new String(out);
}
public static String encodeSHA256(String src) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-256");
byte[] input = src.getBytes();
int len = input.length;
md.update(input, 0, len);
byte[] raw = md.digest();
//System.out.println("Byte out =" + new String(raw));
//System.out.println("Byte Len = " + raw.length);
return encodeBASE64(raw,raw.length);
} catch (NoSuchAlgorithmException noalgo) {
noalgo.printStackTrace();
}
return null;
}
public static void main(String[] argv) {
System.out.println( SHA.encodeSHA256("hello"));
System.out.println( SHA.encodeSHA256("jljdsljdglfglkdhfkgjhkjhdkgjhgkjhjhfdkhgdkjfhgk"));
}
}
댓글 없음:
댓글 쓰기