如何加密一个Java对象

shibai 2006-06-30 11:40:01
public class A{
private String a;
public String getA(){
return a;
}

public void setA(String a){
this.a = a;
}
}

A aa = new A();
aa.setA("aaa");

现在需要把aa这个对象加密后写入到本地文件,请问把aa对象加密这一步怎么做?谢谢
...全文
840 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
wts173 2006-09-07
  • 打赏
  • 举报
回复
mark
jingweicool 2006-08-20
  • 打赏
  • 举报
回复
我也做个标记把
lulu123ma 2006-08-19
  • 打赏
  • 举报
回复
做个标记,以后用得着!!
忍静 2006-08-18
  • 打赏
  • 举报
回复
j2sdk里自带了,javax.crypto.*
xzf198210 2006-08-18
  • 打赏
  • 举报
回复
楼上的大哥是用什么服务器的阿。
我用的是weblogic,可是导入的包
KeyGenerator里面没有getInstance方法!
还有import javax.crypto.*;这个包是从什么地方导进来的阿

hbwhwang 2006-08-08
  • 打赏
  • 举报
回复
import java.io.*;

import javax.crypto.*;
import java.security.*;

class A
implements Serializable {
private String a;
public String getA() {
return a;
}

public void setA(String a) {
this.a = a;
}
public String toString(){
return a;
}
}

public class DESObjectToFile {
public static void main(String[] args) {
KeyGenerator kg = null;
try {
//指定算法,这里为DES
kg = KeyGenerator.getInstance("DES", "SunJCE");

//指定密钥长度,长度越高,加密强度越大
kg.init(56);

//产生密钥
Key key = kg.generateKey();

//记得把密钥保存起来
String keyfilename="d:\\key.dat";

ObjectOutputStream out = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(keyfilename)));
out.writeObject(key);
out.close();

//加密要用Cipher来实现
Cipher cipher = Cipher.getInstance("DES");

String filename = "d:\\加密的对象.dat";
//读入并加密文件
try {
//设置加密模式
cipher.init(Cipher.ENCRYPT_MODE, key);
//输出流
out = new ObjectOutputStream(new CipherOutputStream(new
BufferedOutputStream(new FileOutputStream(filename)),
cipher));
A aa = new A();
aa.setA("aaa");
out.writeObject(aa);

out.close();
System.out.println("加密完成!");
}
catch (Exception ey5) {
System.out.println("Error when encrypt the file");
System.exit(0);
}

try {
//把key从文件取出
ObjectInputStream in =new ObjectInputStream(new
BufferedInputStream(new FileInputStream(keyfilename)));
key=(Key)in.readObject();
in.close();

//设置解密模式
cipher.init(Cipher.DECRYPT_MODE, key);
//输入流
in =new ObjectInputStream(new CipherInputStream(new
BufferedInputStream(
new FileInputStream(filename)), cipher));

Object a=in.readObject();
System.out.println(a);
in.close();

System.out.println("解密完成!");
}
catch (Exception ey5) {
System.out.println("Error when encrypt the file");
System.exit(0);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
shibai 2006-08-07
  • 打赏
  • 举报
回复
有没有现成的加密类?
hbwhwang 2006-08-02
  • 打赏
  • 举报
回复
如果A实现了串行化接口就好办了。
这样就可以把aa输出到ByteArrayOutputStream,然后给它加密,然后保存到硬盘。
cold_zlq 2006-07-23
  • 打赏
  • 举报
回复
我觉得先写个加密类比较好~~
winksong 2006-07-17
  • 打赏
  • 举报
回复
可以用外壳加密实现
pshpan 2006-07-04
  • 打赏
  • 举报
回复
是加密后需要再读出么?我也想知道……
我觉得另外写个加密类然后调用返回密文吧

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧