Reputation: 51
I have problem with restoring byte array from ms sql database, can someone help me?
I have database with table called sec, that has two attributes 'ID_uzivatele' - varchar(20) and 'salt' - varbinary(50). I would like to store a byte[] salt
in this table and then restore it back to byte[] receivedSalt
, but if I compare both byte arrays, it doesn´t equal:
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:JavaProject");
byte[] salt = generateSalt();
PreparedStatement insert = conn.prepareStatement("INSERT INTO sec VALUES ('id001', ?)");
insert.setBytes(1, salt);
insert.executeUpdate();
insert.close();
System.out.println("values are succesfully inserted to database");
Statement select = conn.createStatement();
ResultSet rs = select.executeQuery("SELECT salt FROM sec WHERE ID_uzivatele = 'id001'");
rs = select.getResultSet();
try {
while (rs.next()) {
byte[] receivedSalt = rs.getBytes("salt");
if (salt.equals(receivedSalt)) System.out.println("match");
else System.out.println("no match");
}
}
finally {
rs.close();
select.close();
}
} catch (ClassNotFoundException | SQLException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static byte[] generateSalt() throws NoSuchAlgorithmException {
// VERY important to use SecureRandom instead of just Random
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
// Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5
byte[] salt = new byte[8];
random.nextBytes(salt);
return salt;
}
}
Upvotes: 2
Views: 6321
Reputation: 51
ok, I got it, I used wrong comparison method:
if (salt.equals(receivedSalt)) System.out.println("match");
so it works with this one:
if (Arrays.equals(salt, receivedSalt)) System.out.println("match");
Upvotes: 1