[英]User Authentication in Java using 128-bit AES encryption in CBC mode with PKCS #5 padding
我正在CBC模式下使用128位AES加密,並使用PKCS#5填充將密碼保存到我的數據庫中。 但是,當我嘗試登錄時,即使我使用正確的密碼,系統也會告訴我密碼無效。
在我的UserSetup類上,以下是我的代碼,用於加密密碼並將其保存到我的數據庫中:
try {
String input = simple_text.getText();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(keyString.getBytes());
byte[] key = new byte[16];
System.arraycopy(digest.digest(), 0, key, 0, key.length);
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
// encrypt
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
System.out.println("encrypted: " + new String(encrypted));
encrypt_text .setText(new String(encrypted));
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
try {
String sql = "INSERT INTO user(username,password) VALUES(?,?) ON DUPLICATE KEY UPDATE username=VALUES(username),password=VALUES(password)";
pst=conn.prepareStatement(sql);
pst.setString(1, fLoginName.getText());
pst.setString(2, encrypt_text.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "saved");
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
在我的登錄課程中,我有以下代碼:
String sql ="select * from user where username=? and password=?";
if(loginNameField.getText().equals("me") && passwordField.getText().equals("me")){
frmLoginWindow.dispose();
new GridMain().setVisible(true);
}else{
try{
pst=conn.prepareStatement(sql);
pst.setString(1,loginNameField.getText());
pst.setString(2,passwordField.getText());
rs=pst.executeQuery();
if(rs.next()){
//JOptionPane.showMessageDialog(null, "Username and Password is correct ");
rs.close();
pst.close();
// close();
frmLoginWindow.dispose();
new GridMain().setVisible(true);
}
else{
JOptionPane.showMessageDialog(null, "Username and Password is not correct");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
} finally {
try{
rs.close();
pst.close();
}
catch(Exception e) {}
}
}
我的加密密碼已成功保存,但是我需要一種將登錄密碼與加密密碼進行匹配的方法,因為即使您對同一密碼進行加密,AES加密也不會提供相同的加密值。
AES是一種加密算法。 您嘗試將其用作密碼哈希算法。 問題在於,多次加密同一件事不會每次都產生相同的結果。 初始化向量(IV)將隨機性引入到過程中,因此不會兩次獲得相同的結果。
您將需要解密密碼以進行檢查或切換到密碼哈希算法,例如PBKDF2。 請記住,AES會生成二進制數據( byte[]
),您不能簡單地將其轉換為String
。 您需要使用Base64之類的代碼對其進行編碼。 這對於散列函數的輸出也可能是必需的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.