SHA2 password hashing in java

后端 未结 4 1077
盖世英雄少女心
盖世英雄少女心 2020-12-08 17:05

I\'m trying to hash some passwords with SHA2.

Where can I get a snippet of java code for make that?

I have seen that post but I have something missing: SHA2

4条回答
  •  盖世英雄少女心
    2020-12-08 17:38

    I modified a little rossum's code, added salt and convert returning type to String, add try/catch, maybe it will help to someone:

        public String hash(String password) {
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            String salt = "some_random_salt";
            String passWithSalt = password + salt;
            byte[] passBytes = passWithSalt.getBytes();
            byte[] passHash = sha256.digest(passBytes);             
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< passHash.length ;i++) {
                sb.append(Integer.toString((passHash[i] & 0xff) + 0x100, 16).substring(1));         
            }
            String generatedPassword = sb.toString();
            return generatedPassword;
        } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }       
        return null;
    }
    

提交回复
热议问题