本文介绍了PBKDF2WithHmacSHA1 Java 到 Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 swift 3 中使用相同的算法(PBKDF2WithHmacSHA1)在 Java 中散列密码

I would like to hash a password in swift 3 using the same algorithm(PBKDF2WithHmacSHA1) in Java

Java 代码如下:

char[] passwordChars = password.toCharArray();
byte[] saltBytes = Constantes.SALT.getBytes();
PBEKeySpec spec = new PBEKeySpec(passwordChars, saltBytes, Constantes.ITERATIONS,192);

try {
    SecretKeyFactory  key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] hashedPassword = key.generateSecret(spec).getEncoded();
    return String.format("%x", new BigInteger(hashedPassword));
} catch {[..]}

关键字test"的结果示例:2d21d1a136b22280a47499789ae4bedfb63ce900e97064

result example for keyword "test" : 2d21d1a136b22280a47499789ae4bedfb63ce900e97064

我尝试像这样使用 CryptoSwift:

I tried to use CryptoSwift like this:

let passwordArray: [UInt8] = Array(test.utf8)
let saltArray: [UInt8] = Array(salt.utf8)

let result = try! PKCS5.PBKDF2(password: passwordArray, salt: saltArray, iterations: iter, keyLength: 192, variant: .sha1).calculate()

结果:

b35a9b2a6150373b5cf81a7a616bc80f8cbe9ec25eac9b111798feb9e2fa9b1c0aa4627d0fb6c1820d2a5b432b1dd688a06692f3a8e2b2136d8c03f26d28de49bdfe4ecb76821ee4e74139f2580361405b788eab0d35d339a91dedaa566ec13d96f8c812a5ccb84a8e923fad7c9a4ecf7eaced67a37b66fb062c8043e4125c2fb68cc2f3ebe0374087b72ac8e15146e24d239ee2577fd1ef581f3ae9b7dd5d16681da114a04f182586b63ff1388e63cea96212574817426a1cd1d35dd2c22e1a

我注意到结果不一样,

您知道问题可能来自哪里吗?

Do you have any idea where the problem may come from?

推荐答案

是的,我有解决方案问题出在 Android 上:

Yes I have the solutionthe problem comes to Android :

SecretKeyFactory key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] hashedPassword = key.generateSecret(spec).getEncoded();
        DebugLog.logd("Tools","hashPassword tableau bytes = " + hashedPassword);
        return toHex(hashedPassword);

使用 toHex() :

with toHex() :

private static String toHex(byte[] array) {
    BigInteger bi = new BigInteger(1, array);
    String hex = bi.toString(16);
    int paddingLength = (array.length * 2) - hex.length();
    if(paddingLength > 0)
        return String.format("%0" + paddingLength + "d", 0) + hex;
    else
        return hex;
}

你应该找到和 Swift 一样的结果 :-)

you should find the same result as on Swift :-)

这篇关于PBKDF2WithHmacSHA1 Java 到 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:36