怎么存呀,又怎么回复成SecretKey实例?

解决方案 »

  1.   

    写了一个简单的例子,文件读写部分没有写,希望对你有帮助import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.AlgorithmParameters;
    import sun.misc.*;
    public class Test {
      public Test() {
        try {
          Cipher c = Cipher.getInstance("DES");
          KeyGenerator keygen = KeyGenerator.getInstance("DES");
          SecretKey deskey = keygen.generateKey();
          c.init(Cipher.ENCRYPT_MODE, deskey);
          byte[] cipherText = c.doFinal("This is just an example".getBytes());
          BASE64Encoder base64E = new BASE64Encoder();
          String skey = base64E.encode(deskey.getEncoded());
          //you can save you key to file 
          //......
          
          
          //read keybyte from file
          //......
          
          BASE64Decoder base64D = new BASE64Decoder();
          byte[] bKey = base64D.decodeBuffer(skey);      Cipher c1 = Cipher.getInstance("DES");
          SecretKey deskey1 = new SecretKeySpec(bKey, "DES");
          c1.init(Cipher.DECRYPT_MODE, deskey1);
          byte[] test2 = c1.doFinal(cipherText);
          System.out.println("encodedAlgParams1 "+new String(test2));    }
        catch (Exception ex) {
          ex.printStackTrace();
        }  }  public static void main(String[] args) {
        Test test1 = new Test();
      }}