【发布时间】:2018-07-04 13:16:38
【问题描述】:
我正在尝试实现一个更高级的密码散列算法 (PBKDF2),它使用 java util 库中的 Base64 类,但由于此类已过时,我需要获取支持更新的 Apache Codecs 库Base64 类。令人惊奇的是,在普通的 java 类上它可以完美地工作,但是当我在 android 活动中使用同一段代码时,它给了我一个错误,说我试图从 Base64 调用的方法不存在!
我认为这里的问题是,在活动中,Base64 是从具有过时版本的 Base64 的 util 库中调用的。 下面是代码示例。
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import org.apache.commons.codec.binary.Base64;
public class Password {
// The higher the number of iterations the more
// expensive computing the hash is for us and
// also for an attacker.
private final int iterations = 20 * 1000;
private final int saltLen = 32;
private final int desiredKeyLen = 256;
/**
* Computes a salted PBKDF2 hash of given plaintext password
* suitable for storing in a database.
* Empty passwords are not supported.
*/
public String getSaltedHash(String password) throws Exception {
byte[] salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLen);
// store the salt with the password
return Base64.encodeBase64String(salt) + "$" + hash(password, salt);
}
/**
* Checks whether given plaintext password corresponds
* to a stored salted hash of the password.
*/
public boolean check(String password, String stored) throws Exception {
String[] saltAndPass = stored.split("\\$");
if (saltAndPass.length != 2) {
throw new IllegalStateException(
"The stored password have the form 'salt$hash'");
}
String hashOfInput = hash(password, Base64.decodeBase64(saltAndPass[0]));
return hashOfInput.equals(saltAndPass[1]);
}
// using PBKDF2 from Sun, an alternative is https://github.com/wg/scrypt
// cf. http://www.unlimitednovelty.com/2012/03/dont-use-bcrypt.html
private String hash(String password, byte[] salt) throws Exception {
if (password == null || password.length() == 0)
throw new IllegalArgumentException("Empty passwords are not supported.");
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey key = f.generateSecret(new PBEKeySpec(
password.toCharArray(), salt, iterations, desiredKeyLen)
);
return Base64.encodeBase64String(key.getEncoded());
}
public static void main(String[] args) throws Exception {
Password passwordHash = new Password();
String password = passwordHash.getSaltedHash("password");
String password2 = passwordHash.getSaltedHash("password");
System.out.println("P1-HASH: " + password);
System.out.println("P2-HASH: " + password2);
System.out.println(passwordHash.check("password", password2));
}
}
【问题讨论】:
-
您的代码中没有任何地方使用 java Base64 类,因此您的描述没有意义。另外,您在这里似乎没有任何问题。
-
Base64 类在此代码中使用了 3 次。问题在于“encodeBase64String”方法,我猜也是解码方法。这个问题可以根据上面的解释来详细说明。
-
java util 类在 java.util 包中。它不会在您的代码中的任何地方使用。
标签: java encryption base64 apache-commons