PBKDF2WithHmacSHA1 Java to Swift 3

2019-09-12 09:40发布

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

Here is code in 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 {[..]}

result example for keyword "test" : 2d21d1a136b22280a47499789ae4bedfb63ce900e97064

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()

result : b35a9b2a6150373b5cf81a7a616bc80f8cbe9ec25eac9b111798feb9e2fa9b1c0aa4627d0fb6c1820d2a5b432b1dd688a06692f3a8e2b2136d8c03f26d28de49bdfe4ecb76821ee4e74139f2580361405b788eab0d35d339a91dedaa566ec13d96f8c812a5ccb84a8e923fad7c9a4ecf7eaced67a37b66fb062c8043e4125c2fb68cc2f3ebe0374087b72ac8e15146e24d239ee2577fd1ef581f3ae9b7dd5d16681da114a04f182586b63ff1388e63cea96212574817426a1cd1d35dd2c22e1a

I note that the result is not the same,

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

Are there other library in swift to hash a password ?

标签: java ios swift3
2条回答
别忘想泡老子
2楼-- · 2019-09-12 10:23

Yes I have the solution the 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);

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;
}

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

查看更多
▲ chillily
3楼-- · 2019-09-12 10:36

Hi, exist IDZSwiftCommonCrypto and it has a Digest Class that containts SHA1. Here is the link. i have used this framework and it is very fast, but i used only the Cryptor class and StreamCryptor. Hope can you help!

https://github.com/iosdevzone/IDZSwiftCommonCrypto

查看更多
登录 后发表回答