生成KEY,并保存在文件中:
KeyGenerator keyGen=KeyGenerator.getInstance("DESede");
Key key=keyGen.generateKey();
FileOutputStream out = new FileOutputStream("testsec.dat");
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(key);
os.flush();
从文件中取得KEY:
FileInputStream in = new FileInputStream("testsec.dat");
ObjectInputStream ins = new ObjectInputStream(in);
Key key = (SecretKey)ins.readObject();
用KEY进行加密:
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal("我是中国人".getBytes());
String s1 = new sun.misc.BASE64Encoder().encode(ciphertext);
用KEY进行解密:
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE,key);
String s2 = "fbpq7VuHRs/QtC1k4R0zxQ==";
byte[] b1 = new sun.misc.BASE64Decoder().decodeBuffer(s2);
byte[] b = cipher.doFinal(b1);
String s= new String(b);