【发布时间】:2018-02-17 11:45:16
【问题描述】:
我在数据库中有一个加密值,我想在发送到前端之前对其进行解密。
当我第一次将值保存为加密时,它在数据库中看起来像 -kKwj477382jle34nw。但是,如果我调用我的 getClientByUsername() 函数,我在这个函数中进行解密,当我在将对象发送到前端之前在对象中设置解密值时,数据库中的值也会自动更改。
@Transactional
public ResponseEntity <Client> getClientByUsername(String username) throws Exception {
Client loggedClient = clientDAO.findByUsername(username);
String data = loggedClient.getCreditCardNo();
if (null != data) {
@SuppressWarnings("static-access")
byte[] encrypted = base64.decodeBase64(data);
SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKey.getBytes(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
decrypted = cipher.doFinal(encrypted);
loggedClient.setCreditCardNo(new String(decrypted));
}
return new ResponseEntity < Client > (loggedClient, HttpStatus.OK);
}
这是我将值保存为加密的方式:
@Transactional
public boolean clientUpdate(String client) {
str = updateclient.getCreditCardNo();
if (null != str) {
SecretKeySpec secretKeySpec = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
encrypted = cipher.doFinal(str.getBytes("UTF-8"));
updateclient.setCreditCardNo(base64.encodeToString(encrypted));
return clientDAO.updateProfileClient(updateclient);
}
调用setter时如何阻止hibernate改变值?
更新
@PersistenceContext
private EntityManager entityManager;
public Client findByUsername(String username) throws Exception {
Query query = entityManager.createNamedQuery("Client.findByUsername");
query.setParameter("username", username);
List result = query.getResultList();
return result.size() > 0 ? (Client) result.get(0) : null;
}
【问题讨论】:
-
这是一个很好的例子,说明为什么您应该将实体与 dto 分开以进行响应。编辑:以及来自事务逻辑的控制器逻辑
-
@Zeromus 没有必要。我个人讨厌这种分离,并且总是在项目中与之抗争。
-
假设它毕竟是一种偏好......但我发现在构建响应时分离逻辑并避免此类问题更加清晰
-
是的,然后在将属性从一个对象复制到另一个对象时引入大量错误。