JAVA和PYTHON中的SHA256加密产生不同的结果

时间:2018-07-20 14:28:19

标签: java python sha256

感谢您的帮助,以了解为什么我在JAVA和PYTHON中的SHA256加密函数不会产生结果(1位数字的差异,Python中的差异):

要加密的哈希是:“ thisisatest”
Java结果为:a7c96262c21db9a06fd49e307d694fd95f624569f9b35bb3ffacd88044f9787
Python结果是: a7c96262c21db9a06fd49e307d694fd95f624569f9b35bb3ffacd880440f9787

Python代码:

import hashlib

def encrypt_string(hash_string):
    sha_signature = \
        hashlib.sha256(hash_string.encode()).hexdigest()
    return sha_signature


hash_string = "thisisatest"
print(encrypt_string(hash_string), end="")

Java代码:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class OpenAPIPasswordEncryptor1 {


    private static MessageDigest sha256;

    // generated password is stored encrypted (using also user name for hashing)
    public synchronized static String encrypt(String hash) {
        try {

            StringBuilder builder = new StringBuilder();
            builder.append(hash);

            // first time , encrypt user name , password and static key
            String encryptedCredentials = encryptionIterator(builder.toString());
           return encryptedCredentials;
        } 

        catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    private static String encryptionIterator(String content) {
        try {
            sha256 = MessageDigest.getInstance("SHA-256");
            // append the static key to each iteration
            byte[] passBytes = (content).getBytes();
            sha256.reset();
            byte[] digested = sha256.digest(passBytes);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < digested.length; i++) {
                sb.append(Integer.toHexString(0xff & digested[i]));
            }

            return sb.toString();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }

        return "";
    }

    // generate password for developers
    public static void main(String[] args) {
        String hash = "thisisatest";
        String encrypt = encrypt(hash);
        System.out.println("Your Password Is '" + encrypt + "'");
    }
}

1 个答案:

答案 0 :(得分:2)

问题在于,如果{unsigned}字节值小于或等于15,则Integer.toHexString(int)会丢弃前导零。作为一种快速的解决方法,您可以使用以下方法:

sb.append(String.format("%02x", 0xff & digested[i]));

当然可以实现更有效的实现。

要在Python中产生相同的错误,请使用以下代码:

def encrypt_string(hash_string):
    sha_signature = hashlib.sha256(hash_string.encode()).digest()
    return "".join(["{:x}".format(b) for b in sha_signature])