0
我是新來的密碼存儲和Bouncy城堡。在Java中使用Bouncy Castle的SHA-256哈希和AES密碼存儲
- 加密:是否有一個理由,更喜歡Pkcs5S2ParametersGenerator 了AES加密(鹽+哈希(密碼+鹽))?
- 舉例:How to encrypt and salt the password using BouncyCastle API in Java?
- 我的Java代碼:有沒有更好的方法從密碼中取回salt比字節數組提取?
這裏是我的Java代碼:
// salt
java.security.SecureRandom rgen = new SecureRandom();
byte[] salt = rgen.generateSeed(20);
// add Bouncy Castle
java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// aes secret key
javax.crypto.KeyGenerator kgen = KeyGenerator.getInstance("AES", "BC");
Key cleSecrete = kgen.generateKey();
// aes
javax.crypto.Cipher cipher = Cipher.getInstance("AES", "BC");
// sha-256
java.security.MessageDigest sha256 = MessageDigest.getInstance("SHA-256","BC");
// hash the clear password with the salt to avoid collisions
byte[] motDePasseHash = hasherSaler(motDePasseClair.getBytes("UTF-8"),salt);
// Encrypt the hash with the salt to get the salt back
byte[] chiffreBDD = chiffrerSalerHash(salt,motDePasseHash,cleSecrete);
// Store the cipher in DB
...
// Get back the hash and the salt from DB
byte[] deChiffreBDD = deChiffrer(chiffreBDD,cleSecrete);
byte[] saltBDD = extraireOctets(deChiffreBDD,0,19);
byte[] hashBDD = extraireOctets(deChiffreBDD,20,deChiffreBDD.length-1);
// hash the user intput
byte[] motDePasseHashCandidat = hasherSaler(motDePasseClairCandidat.getBytes("UTF-8"),saltBDD);
// Compare hased user input with DB hash
boolean isMotDePasseOK = Arrays.equals(hashBDD,motDePasseHashCandidat);
private final byte[] hasherSaler(byte[] clair,byte[] salt) {
byte[] concat = concatenerOctets(clair,salt);
return sha256.digest(concat);
}
private final byte[] chiffrerSalerHash(byte[] salt,byte[] hash, Key cle) {
cipher.init(true,cle);
return cipher.doFinal(concatenerOctets(salt,hash));
}
private final byte[] deChiffrer(byte[] chiffre, Key cle) {
cipher.init(false,cle);
return cipher.doFinal(chiffre);
}
謝謝。
此代碼是否運行?我沒有看到任何'Cipher.init()'調用。或者這是一個原型? – 2014-10-02 13:07:12
它不運行,它現在在我的文本編輯器中。我想先收集必要的步驟。 – Fanilo 2014-10-02 13:46:04
你說我的aes密碼沒有啓動向量?非常感謝 ! – Fanilo 2014-10-02 13:57:52