有没有一种简单的方法来加密java对象?

use*_*469 2 java encryption object

我想将一个序列化的对象存储到一个文件中,但是我想将它加密.它不需要真正强大的加密.我只想要一些简单的东西(最好是几行代码),这会让其他人加载起来更加困难.我已经看过SealedObject,但关键是让我抱怨.理想情况下,我只想传递一个String作为加密/解密对象的密钥.

有什么建议?

Mic*_*hin 9

试试这段代码:

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 );
Run Code Online (Sandbox Code Playgroud)


小智 5

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