[英]Storing a byte array in MS-SQL
I have problem with restoring byte array from ms sql database, can someone help me? 我从ms sql数据库还原字节数组时遇到问题,有人可以帮助我吗?
I have database with table called sec , that has two attributes 'ID_uzivatele' - varchar(20) and 'salt' - varbinary(50) . 我有一个名为sec的表的数据库,该表具有两个属性'ID_uzivatele'-varchar(20)和' 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: 我想在此表中存储一个
byte[] salt
,然后将其还原回byte[] receivedSalt
,但是如果我比较两个字节数组,它就不相等:
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;
}
}
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.