Glassfish Security - jdbcRealm: How to configure login with SHA-256 digest

て烟熏妆下的殇ゞ 提交于 2019-11-30 10:52:01

问题


I use jdbcRealm for security in my glassfish v3.0.1 b22. It is set up so that it use the USER table inside my database for authentication by following this blog: http://blogs.oracle.com/foo/entry/mort_learns_jdbc_realm_authentication. I got it working fine, if I leave the digest algorithm as plain text. However when i try to use SHA-256 for digest algorithm, it stop working. What I did is specify in Glassfish - Security - Realm - jdbcRealm - digest that I want SHA-256 (I just type SHA-256 inside digest field). Then I wrote a simple Java program to convert password text into SHA-256 hash. I then paste that hash inside my password field in the database. By the way, password field is type varchar(30). I cant log in anymore. One thing I notice that my simple Java program generated different hash every time for the same text field.

Below are my simple java program:

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        String text = "admin";
        md.update(text.getBytes("UTF-8"));
        byte[] digest = md.digest();
        System.out.println(digest.toString());

回答1:


The jdbcRealm allows encoding values of hex or base64. You need to specify one of these in your realm configuration and in your code, convert the byte array into one of these formats:

Base64:

import com.sun.org.apache.xml.internal.security.utils.Base64;
...
byte[] digest = md.digest();
System.out.println(Base64.encode(digest));

Hex:

...
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
    String hex = Integer.toHexString(0xff & digest[i]);
    if (hex.length() == 1) sb.append('0');
    sb.append(hex);
}
System.out.println(sb.toString());

btw, password field is type varchar(30)

You'll need to increase the size of your password field. SHA-256 base64 and hex values are 45 and 64 characters in length, respectively.



来源:https://stackoverflow.com/questions/3444503/glassfish-security-jdbcrealm-how-to-configure-login-with-sha-256-digest

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