【问题标题】:How to store password encrypted in database?如何将加密的密码存储在数据库中?
【发布时间】:2011-07-15 16:06:24
【问题描述】:

我试图在 JSP 和 Servlet 的帮助下以加密形式将密码存储到数据库中。我该怎么做?

【问题讨论】:

    标签: java database encryption


    【解决方案1】:

    自行编写的算法存在安全风险,维护起来很痛苦。
    MD5 是not secure

    使用bcrypt算法,由jBcrypt(开源)提供:

    // Hash a password
    String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
    
    // Check that an unencrypted password matches or not
    if (BCrypt.checkpw(candidate, hashed))
        System.out.println("It matches");
    else
        System.out.println("It does not match");
    

    如果您使用 Maven,您可以通过在 pom.xml 中插入以下依赖项来获取该库(如果有更新的版本,请告诉我)

    <dependency>
        <groupId>de.svenkubiak</groupId>
        <artifactId>jBCrypt</artifactId>
        <version>0.4.1</version>
    </dependency>
    

    【讨论】:

    • @VedPrakash:我添加了一段关于从 Maven 获取它的内容,这有帮助吗?
    • @Nicolas Raoul 谢谢先生
    【解决方案2】:

    尝试这样的方法来加密您的数据。

    MessageDigest md = MessageDigest.getInstance("MD5");
    
    
    ......
    
    
    synchronized (md) {
    
    md.reset(); 
    byte[] hash = md.digest(plainTextPassword.getBytes("CP1252"));
    
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < hash.length; ++i) {
    sb.append(Integer.toHexString((hash[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
    }
    
    String password = sb.toString();
    }
    

    【讨论】:

    【解决方案3】:

    您也可以使用以下内容。下面是一个 crypt 方法,它接受一个字符串输入并将返回和加密的字符串。您可以将密码传递给此方法。

    public static String crypt(String str) {
        if (str == null || str.length() == 0) {
            throw new IllegalArgumentException(
                    "String to encrypt cannot be null or zero length");
        }
    
        StringBuffer hexString = new StringBuffer();
    
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
    
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0"
                            + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
        } catch (NoSuchAlgorithmException e) {
    
        }
    
        return hexString.toString();
    }
    

    【讨论】:

    猜你喜欢
    • 2016-12-25
    • 2011-04-26
    • 2020-03-20
    • 2012-04-07
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    相关资源
    最近更新 更多