Java如何使用DES解密对象?
在前面的示例中,如何使用DES加密对象?我们加密一个对象。在此示例中,我们将解密存储的对象。
package org.nhooo.example.crypto; import java.io.*; import javax.crypto.SecretKey; import javax.crypto.Cipher; import javax.crypto.SealedObject; public class ObjectDecrypt { public static void main(String[] args) throws Exception { //阅读以前存储的SecretKey。 SecretKey key = (SecretKey) readFromFile("secretkey.dat"); //读取SealedObject SealedObject sealedObject = (SealedObject) readFromFile("sealed.dat"); //从解密中准备密码对象。 if (sealedObject != null) { String algorithmName = sealedObject.getAlgorithm(); Cipher cipher = Cipher.getInstance(algorithmName); cipher.init(Cipher.DECRYPT_MODE, key); String text = (String) sealedObject.getObject(cipher); System.out.println("Text = " + text); } } //读取文件中存储的对象的方法。 private static Object readFromFile(String filename) throws Exception { try (FileInputStream fis = new FileInputStream(new File(filename)); ObjectInputStream ois = new ObjectInputStream(fis)) { return ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; } }