我想在Java中使用相同的算法(PBKDF2WithHmacSHA1)在swift 3中散列密码
这是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
我试着像这样使用CryptoSwift:
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
我注意到结果不一样,
你知道问题可能来自哪里吗?
swift中是否有其他库可以使用密码?
答案 0 :(得分:0)
嗨,存在IDZSwiftCommonCrypto并且它有一个包含SHA1的摘要类。链接在这里。我已经使用了这个框架并且它非常快,但我只使用了Cryptor类和StreamCryptor。希望你能帮忙!
答案 1 :(得分:0)
是的我有解决方案 问题来自Android:
SecretKeyFactory key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hashedPassword = key.generateSecret(spec).getEncoded();
DebugLog.logd("Tools","hashPassword tableau bytes = " + hashedPassword);
return toHex(hashedPassword);
使用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相同的结果: - )