有没有一种简单的方法来加密Java对象? [英] Is there an easy way to encrypt a java object?

查看:65
本文介绍了有没有一种简单的方法来加密Java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将序列化的对象存储到文件中,但是我想对其进行加密.不需要真正强大的加密.我只想要一些简单的东西(最好是几行代码),这将使其他人的加载变得更加困难.我已经研究了SealedObject,但是钥匙却使我失望.理想情况下,我只想传递一个String作为加密/解密对象的密钥.

I'd like to store a serialized object to a file however I'd like to make it encrypted. It doesn't need to be really strong encryption. I just want something easy (preferably a couple lines of code max)that will make it a bit more difficult for someone else to load. I've looked into SealedObject but the key's are holding me up. Ideally I'd like to just pass a String as the key to encrypt / decrypt the object.

有什么建议吗?

推荐答案

尝试以下代码:

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 );

这篇关于有没有一种简单的方法来加密Java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆