我的SHA1代码语法错误 [英] Syntax wrong with my SHA1 code

查看:151
本文介绍了我的SHA1代码语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了以下代码:

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

不知怎的,它会发出错误。我不知道如何解决它。这是callstack

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


推荐答案

好吧,如果 MessageDigest.getInstance会发生 ()抛出 NoSuchAlgorithmException - 因为你打印出异常但随后继续进行。

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;

然后这个:

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

我怀疑你实际上并没有运行你面前的代码 - 在我面前至少机器,NPE正确指向第24行,该行包括HEX_CHARS。

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.

修复:

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

这篇关于我的SHA1代码语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆