【发布时间】:2011-07-06 17:23:58
【问题描述】:
我得到以下代码:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Sha1{
private static final char[] HEX_CHARS = null;
public static void main(String[] args){
String hash = toSHA1(("27"+"peojvootv").getBytes());
System.out.println(hash);
}
public static String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] buf = md.digest(convertme);
char[] chars = new char[2 * buf.length];
for (int i = 0; i < buf.length; ++i) {
chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
}
return new String(chars);
}
}
不知何故,它发出了一个错误。我不知道如何解决它。这是调用栈
Exception in thread "main" java.lang.NullPointerException
at mainClockies.Sha1.toSHA1(Sha1.java:26)//The return statement of second method
at mainClockies.Sha1.main(Sha1.java:12)//The callback of the second method
【问题讨论】:
-
不要吞下
NoSuchAlgorithmException异常。如果它被抛出,你一定会得到一个 NPE。最好将其包装在 RuntimeException 中并让它冒泡 -
你的意思是用整个方法体包裹
try{},然后包裹catch(Exception e){ e.printStackTrace();}?