1

我创建了一种方法,可以让我使用密码加密和解密对象。但是,我使用的是 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;
}
4

0 回答 0