Skip to content

Instantly share code, notes, and snippets.

@hongry18
Last active July 20, 2020 18:20
Show Gist options
  • Save hongry18/f19f770763e60026149800874fc71a2e to your computer and use it in GitHub Desktop.
Save hongry18/f19f770763e60026149800874fc71a2e to your computer and use it in GitHub Desktop.
java BCrypt

JAVA Spring Framework BCrypt Sample

dependency

https://mvnrepository.com/artifact/org.springframework.security/spring-security-crypto

example

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import org.springframework.security.crypto.bcrypt.BCrypt;

public class BCryptTest {
    
    public static void main(String[] ar) {
        BCryptTest bcTest = new BCryptTest();
        String hashed = bcTest.generateHash("test");
        boolean verify = bcTest.verifyHash("test", hashed);
        System.out.println(hashed);
        System.out.println(verify);
    }
    
    /*
     * generate BCrypt hash
     */
    public String generateHash(String plainText) {
        try {
            
            String salt = BCrypt.gensalt(10, SecureRandom.getInstance("SHA1PRNG"));
            return BCrypt.hashpw(plainText, salt);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return null;
    }
    
    /*
     * BCrypt check
     */
    public boolean verifyHash(String plainText, String cipher) {
        return BCrypt.checkpw(plainText, cipher);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment