我创建了一个方法,允许我使用密码加密和解密对象。但是,我使用的是Java的本机加密库,但这些库并不是很安全。 (对于我尝试序列化的对象中的小变化,我在总共243个加密字节中得到208个相同的字节。)我认为Shiro有替代方案,但我似乎无法找到它们(至少在1.1.0中进行基于密码的加密)。这是我的加密代码。我将密码值注入到类中,并且我省略了任何异常处理以使事情变得更简单:
public String encryptToString(Serializable object) {
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance(ALGORITHM);
KeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKey secretKey = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATIONS);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
// Serialize map
final ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream();
CipherOutputStream cout =
new CipherOutputStream(byteArrayOutputStream, cipher);
ObjectOutputStream out = new ObjectOutputStream(cout);
out.writeObject(object);
out.close();
cout.close();
byteArrayOutputStream.close();
return new String(
Base64.encode(byteArrayOutputStream.toByteArray()));
}
我的解密代码:
public Object decryptToObject(String encodedString) {
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance(ALGORITHM);
KeySpec keySpec = new PBEKeySpec(password.toCharArray());
SecretKey secretKey = keyFactory.generateSecret(keySpec);
PBEParameterSpec paramSpec = new PBEParameterSpec(SALT, ITERATIONS);
Cipher decipher = Cipher.getInstance(ALGORITHM);
decipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
final ByteArrayInputStream byteArrayInputStream =
new ByteArrayInputStream(Base64.decode(encodedString
.getBytes()));
CipherInputStream cin =
new CipherInputStream(byteArrayInputStream, decipher);
ObjectInputStream in = new ObjectInputStream(cin);
Object result = in.readObject();
in.close();
cin.close();
byteArrayInputStream.close();
return result;
}