有没有简单的方法来加密一个Java对象?

我想将一个序列化的对象存储到一个文件中,但是我想将其加密。 它不需要非常强大的加密。 我只想要一些简单的东西(最好是几行代码),这会让其他人加载时更加困难。 我已经看过SealedObject,但是关键在阻止我。 理想情况下,我想仅传递一个字符串作为加密/解密对象的密钥。

有什么建议么?


试试这个代码:

String fileName = "result.dat"; //some result file

//You may use any combination, but you should use the same for writing and reading
SecretKey key64 = new SecretKeySpec( new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }, "Blowfish" );
Cipher cipher = Cipher.getInstance( "Blowfish" );

//Code to write your object to file
cipher.init( Cipher.ENCRYPT_MODE, key64 );
Person person = new Person(); //some object to serialise
SealedObject sealedObject = new SealedObject( person, cipher);
CipherOutputStream cipherOutputStream = new CipherOutputStream( new BufferedOutputStream( new FileOutputStream( fileName ) ), cipher );
ObjectOutputStream outputStream = new ObjectOutputStream( cipherOutputStream );
outputStream.writeObject( sealedObject );
outputStream.close();

//Code to read your object from file
cipher.init( Cipher.DECRYPT_MODE, key64 );
CipherInputStream cipherInputStream = new CipherInputStream( new BufferedInputStream( new FileInputStream( fileName ) ), cipher );
ObjectInputStream inputStream = new ObjectInputStream( cipherInputStream );
SealedObject sealedObject = (SealedObject) inputStream.readObject();
Person person1 = (Person) sealedObject.getObject( cipher );

使用CipherOutPutStream (http://docs.oracle.com/javase/6/docs/api/javax/crypto/CipherOutputStream.html)将对象写入ObjectOutputStream中可能是一种简单而好用的方法。


你应该看看Jasypt。 它有一堆实用功能可以使这一切变得简单。

...
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(myEncryptionPassword);
...
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);
...
链接地址: http://www.djcxy.com/p/78443.html

上一篇: Is there an easy way to encrypt a java object?

下一篇: How can I normalize the EOL character in Java?