【发布时间】:2021-09-14 07:37:08
【问题描述】:
我的代码遇到了问题。
我想加密来自用户的密码并将其保存到 SQL 数据库。 我使用 AES 加密密码的代码:
String key = "1234567890123456"; // 128 bit key
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(Passwort.getBytes());
String verschlüsselt = new String(encrypted);
现在我将字符串“verschlüsselt”保存到我的数据库中。
在我的 LoginGUI 中,我从数据库中获取带有密码的字符串:
String psswd = res.getString("Passwort"); //Getting the Password from Database and saving it into String
System.out.println(psswd);
打印输出是:“!?¿[ŸÊm,r~¤u”,这是正确的加密密码。
现在我正在尝试使用以下代码解密密码:
String key = "1234567890123456"; // 128 bit key
cipher.init(Cipher.DECRYPT_MODE, aesKey);
EPasswort = new String(cipher.doFinal(bpsswd)); //Im facing the problem here
我知道我无法解密字符串,我必须将字符串转换为字节 []。 我已经通过多种方式做到了这一点:
byte[] password = psswd.getBytes();
System.out.println(password);
password = psswd.getBytes("UTF-8");
System.out.println(password);
EPasswort = new String(cipher.doFinal(password));
但输出始终是解密器无法使用的:
[B@ab33b4
[B@189090b
如何将带有密码 (!?¿[ŸÊm,r~¤u) 的字符串转换为字节[],以便我的解密器可以使用它?
感谢您的帮助。
【问题讨论】:
-
加密密码,然后匹配db密码。
-
字节到字符串的转换和返回字节将失败,因为许多“不可打印”字符,如(十六进制)x00 字节。更好的是,您正在使用 Base64 和更高版本的解码功能。其次:对于您的加密,您选择了 ECB 模式,这是一个糟糕的选择,尤其是在加密密码时(有很多更好的选择可以使用,例如 BCrypt)。如果您需要用户提供密码,您应该使用 GCM 模式 对数据进行加密。顺便说一句:最好使用不带变音符号的变量名,例如“verschlüsselt”中的“ü”。问候德国、奥地利或瑞士 :-)
-
I want to encrypt the Password from the user and save it to an SQL Database.如果是用户认证,不要加密密码,而是使用slow salted hash (bcrypt, scrypt,... pbkdf2)
标签: java arrays string encryption