如何在Java中比较sha1 encripted password?

时间:2016-12-15 11:00:46

标签: java encryption sha1

假设我已经输入了像这样的SHA1密码

String pass = "f6ce584e7b4ff5253eed4a2ea2b44247";

我希望制造这样的条件:

 if (pass.equals("userinput")){
        System.out.println("success");
    }

请有人帮我制作正确的条件/功能,比较用户输入和输入密码之间的值。我们将非常感谢您的帮助。感谢

2 个答案:

答案 0 :(得分:1)

SHA1是一种哈希算法,这意味着它是单向的。在对其进行散列后,您无法获得原始消息。与双向加密(允许加密和解密)不同。

这意味着如果您想比较哈希,则不要尝试获取原始邮件。相反,您也要对要比较的消息进行哈希处理,然后执行匹配:

因此,如果散列的pw存储为:

String pass = "f6ce584e7b4ff5253eed4a2ea2b44247";

要匹配后续输入的密码,请执行以下操作:

//check if hashed userInput is also "f6ce584e7b4ff5253eed4a2ea2b44247"
if(pass.equals(sha1(userInput))){          
    //do whatever
}

要实现sha1()哈希函数,请参阅:Java String to SHA1

答案 1 :(得分:0)

获取您的哈希码:

public static byte[] sha1(byte[] data)
Calculates the SHA-1 digest and returns the value as a byte[].
Parameters:
data - Data to digest
Returns:
SHA-1 digest

发现这些 https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html#sha1Hex(java.lang.String)

这有助于您的流程。

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jcajce.provider.asymmetric.rsa.DigestSignatureSpi.SHA1;

public class SHA1_test {

    public static String sha1(String s, String keyString)
            throws UnsupportedEncodingException, NoSuchAlgorithmException,
            InvalidKeyException {

        SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"),
                "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);

        byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));

        return new String(Base64.encodeBase64(bytes));

    }

    public static void main(String[] args) throws InvalidKeyException,
            UnsupportedEncodingException, NoSuchAlgorithmException {
        Boolean validate = false;
        String code = sha1("admin", "123456");
        String your_user_inputString = "testpassword";

        if (code.equals(sha1(your_user_inputString, "123456"))) {
            System.out.println("Correct");
        } else {
            System.out.println("Bad password");
        }

    }

}

这有效!!!

相关问题