Is there an easy way to encrypt a java object?
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.
Any suggestions?
试试这个代码:
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中可能是一种简单而好用的方法。
You should look into Jasypt. It has a bunch of utility functions to make this easy.
...
BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(myEncryptionPassword);
...
String myEncryptedText = textEncryptor.encrypt(myText);
...
String plainText = textEncryptor.decrypt(myEncryptedText);
...
链接地址: http://www.djcxy.com/p/78444.html
上一篇: Java DecimalFormat科学记数法问题
下一篇: 有没有简单的方法来加密一个Java对象?