2

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

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

1 回答 1

1

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

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

所以它适用于这个:

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

于 2013-03-06T10:53:23.320 回答