Syntax wrong with my SHA1 code

空扰寡人 提交于 2019-12-05 07:48:33

问题


I got the following code:

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);
    }
}

Somehow it issues an error. I dont know how to fix it. this is the callstack

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

回答1:


Well, it would happen if MessageDigest.getInstance() throw NoSuchAlgorithmException - because you're printing out the exception but then carrying on regardless.

However, it's actually happening because of this:

private static final char[] HEX_CHARS = null;

and then this:

chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];

I suspect you're not actually running the code you've got in front of you - on my machine at least, the NPE correctly points to line 24, the line including HEX_CHARS.

To fix:

private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();



回答2:


Your HEX_CHARS variable is never set to anything besides null.




回答3:


Try putting something other than null in HEX_CHARS.



来源:https://stackoverflow.com/questions/5158555/syntax-wrong-with-my-sha1-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!