2014-10-02 71 views
0

我是新來的密碼存儲和Bouncy城​​堡。在Java中使用Bouncy Castle的SHA-256哈希和AES密碼存儲

這裏是我的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); 
} 

謝謝。

+0

此代碼是否運行?我沒有看到任何'Cipher.init()'調用。或者這是一個原型? – 2014-10-02 13:07:12

+0

它不運行,它現在在我的文本編輯器中。我想先收集必要的步驟。 – Fanilo 2014-10-02 13:46:04

+0

你說我的aes密碼沒有啓動向量?非常感謝 ! – Fanilo 2014-10-02 13:57:52

回答

0

如果你只是想驗證密碼,你應該只使用PBKDF2(或bcrypt/scrypt)。密碼不應該是必需的。鹽可以不加密地存儲。您可能希望使用額外的祕密來附加到您保存在其中的鹽,例如源代碼。不要忘記將密碼存儲在協議中,否則您將無法再升級。

至於你的代碼,你不應該使用鹽generateSeed。你應該使用更多的update"AES"默認使用ECB模式,因此請指定其他模式。不要依賴違約。使用(可能派生的)IV。不必要時不要明確使用提供者。

好的,我可以繼續相當長一段時間,但現在必須做。