SQL Server 对称密钥 - 随机获取错误密钥“my_key”未打开

问题描述

我正在使用 sql Server 作为数据库开发 Spring。要求是使用对称密钥对敏感数据进行加密并保存到数据库中。

服务的简单流程是

  1. 从 CSV 读取数据
  2. 将敏感数据加密到数据库

下面是我插入加密数据的示例格式代码

public Long userId addUser(User u) throws sqlException{
    KeyHolder key = new GeneratedKeyHolder(); 

    jdbcTemplate.execute("OPEN SYMMETRIC KEY "+key_name+" DECRYPTION BY CERTIFICATE "+cert_name+" WITH PASSWORD = '"+cert_password+"';");

    jdbcTemplate.update(new PreparedStatementCreator() {
        @Override
        public PreparedStatement createPreparedStatement(Connection connection) throws sqlException {
        String sql = "INSERT INTO .....";
        PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
        ps.setString(1,'foo');
        ...
        ... 
        return ps;
        }

    },key);

    jdbcTemplate.execute("CLOSE SYMMETRIC KEY "+key_name+";");   
    
    return key.getKey().longValue();

}

//Call a function to add a user from CSV records
try {
    addUser(u);
} catch (Exception e) {
    log.info(+e.getMessage());
}

在服务运行时,假设有 2,000 条记录。

有时调用 addUser() 函数会抛出错误。 1 次或 2 次或更多次出现相同的错误。有时不会抛出错误

语句回调; sql 的未分类 sqlException [CLOSE SYMMETRIC KEY my_key;]; sql 状态 [S0001];错误代码 [15315];钥匙 “my_key”未打开。使用前请先打开钥匙。嵌套 异常是 com.microsoft.sqlserver.jdbc.sqlServerException:关键 “my_key”未打开。使用前请先打开钥匙。

如您所见,我已经编写了 jdbcTemplate.execute("") 以在一切完成后打开钥匙并关闭钥匙。

我真的不知道为什么会随机出现这个错误。请帮忙。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)