在MS-SQL中存储字节数组

时间:2013-02-28 11:28:08

标签: java sql-server

我从ms sql数据库恢复字节数组有问题,有人可以帮帮我吗?

我有一个名为 sec 的数据库,它有两个属性'ID_uzivatele' - varchar(20)'salt ' - varbinary(50)。我想在此表中存储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;
    }
}

1 个答案:

答案 0 :(得分:1)

好吧,我明白了,我使用了错误的比较方法:

if (salt.equals(receivedSalt)) System.out.println("match");

所以它适用于这个:

if (Arrays.equals(salt, receivedSalt)) System.out.println("match");