如何使用Java中的BouncyCastle API加密和加密密码?

时间:2014-02-04 23:00:22

标签: java encryption bouncycastle salt

我是加密的新手,我使用BouncyCasetle API加密密码并将其存储在数据库中。对于加密我正在使用SHA-1算法,我希望对密码加密,以防止它再次发生字典攻击。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:8)

我建议使用基于密码的密钥派生函数,而不是基本的哈希函数。像这样:

// tuning parameters

// these sizes are relatively arbitrary
int seedBytes = 20;
int hashBytes = 20;

// increase iterations as high as your performance can tolerate
// since this increases computational cost of password guessing
// which should help security
int iterations = 1000;

// to save a new password:

SecureRandom rng = new SecureRandom();
byte[] salt = rng.generateSeed(seedBytes);

Pkcs5S2ParametersGenerator kdf = new Pkcs5S2ParametersGenerator();
kdf.init(passwordToSave.getBytes("UTF-8"), salt, iterations);

byte[] hash =
    ((KeyParameter) kdf.generateDerivedMacParameters(8*hashBytes)).getKey();

// now save salt and hash

// to check a password, given the known previous salt and hash:

kdf = new Pkcs5S2ParametersGenerator();
kdf.init(passwordToCheck.getBytes("UTF-8"), salt, iterations);

byte[] hashToCheck =
    ((KeyParameter) kdf.generateDerivedMacParameters(8*hashBytes)).getKey();

// if the bytes of hashToCheck don't match the bytes of hash
// that means the password is invalid

答案 1 :(得分:1)

你能做的就是得到一个:

StringBuilder salt=new StringBuilder();
salt.append("MySuperSecretSalt");
MessageDigest md = MessageDigest.getInstance("SHA-256");
String text = "This is text to hash";
salt.append(text);    
md.update(salt.toString().getBytes("UTF-8")); // Change this to "UTF-16" if needed
byte[] digest = md.digest();

你的摘要现在包含你的字符串+ salt的哈希,所以它有助于防止彩虹表。