I'm developing a login module with JSP/Servlets/MySQL with the RSA algorithm. Once I register a new user, I save the PublicKey into MySQL and encrypt a password with it.
When the user tries to log-in, I retrieve that PublicKey and encrypt the just-typed-in-password with the corresponding PublicKey and compare it with the previously saved-encrypted-password but it always returns a different cipher text.
I can't figure out why I get different encrypted passwords every time. Is there anything I'm doing wrong? Does it generate a new PublicKey everytime it runs the "keyFactory.generatePublic"?
Thanks for your help
My method to generate a public key is:
public byte[] generateBytePublicKey() throws Exception {
byte[] pk = null;
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
pk = keyGen.generateKeyPair().getPublic().getEncoded();
} (...... etc etc)
return pk;
My method to encrypt a password:
public byte[] encryptBytes(String pwd, byte[] key) throws Exception {
byte[] cipherText = null;
PublicKey pk;
try {
byte[] dataBytes = pwd.getBytes();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
pk = keyFactory.generatePublic(new X509EncodedKeySpec(key));
final Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
cipherText = cipher.doFinal(dataBytes);
} (..... etc etc)
return cipherText;
My method to store encrypted password and Public Key into a MySQL table:
(.....................)
try {
Statement stmt = null;
ResultSet rs = null;
byte[] bytePublicKey;
byte[] cipherPwd;
bytePublicKey = generateBytePublicKey();
cipherPwd = encryptBytes(password, bytePublicKey);
String query = "INSERT INTO Users (email, pwd, publickey) VALUES ('" + email + "', ?, ?)";
PreparedStatement ps;
ps = conn.getConexion().prepareStatement(query);
ps.setBytes(1, cipherPwd);
ps.setBytes(2, bytePublicKey);
resultSet = ps.executeUpdate();
} (............. etc etc)
My method for checking if a user is valid:
public boolean isUserValid (String email, String typedPassword) throws Exception {
byte[] storedBytesPassword;
byte[] storedBytesPublicKey;
byte[] typedPwdtoBytes;
try {
storedBytesPublicKey = getByteArrays(email, "publicKey");
storedBytesPassword = getByteArrays(email, "pwd");
typedPwdtoBytes = encryptBytes(typedPassword, storedBytesPublicKey);
return Arrays.equals(typedPwdtoBytes, storedBytesPassword);
} (............. etc etc)
My method to get the Byte Arrays from the MySQL table:
public byte[] getByteArrays (String email, String byteArray) throws SQLException {
(..............)
try {
Statement stmt=null;
ResultSet rs=null;
query = "SELECT " + byteArray + " FROM Users WHERE email = '" + email + "'";
try {
stmt = (conn.getConexion()).createStatement();
rs = stmt.executeQuery(query);
while (rs.next() ) {
bytesArr = rs.getBytes(1);
} (.................. etc etc)