2017-06-09 28 views
0

解密我有序列化的對象:加密和由一個序列---反序列化和由另一個

import java.io.Serializable; 

public class ConfigObject implements Serializable{ 

private String url; 
private String user; 
private String pass; 

public String getUrl() { 
    return url; 
} 

public void setUrl(String url) { 
    this.url = url; 
} 

public String getUser() { 
    return user; 
} 

public void setUser(String user) { 
    this.user = user; 
} 

public String getPass() { 
    return pass; 
} 

public void setPass(String pass) { 
    this.pass = pass; 
}   
} 

和2方法在SerializableEncryptDecrypt類:

public static void encrypt(Serializable object, OutputStream ostream, byte[] keyy, String transformationnn) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { 
     try { 
      // Length is 16 byte 
      SecretKeySpec sks = new SecretKeySpec(keyy, transformationnn); 

      // Create cipher 
      Cipher cipher = Cipher.getInstance(transformationnn); 
      cipher.init(Cipher.ENCRYPT_MODE, sks); 
      SealedObject sealedObject = new SealedObject(object, cipher); 

      // Wrap the output stream 
      CipherOutputStream cos = new CipherOutputStream(ostream, cipher); 
      ObjectOutputStream outputStream = new ObjectOutputStream(cos); 
      outputStream.writeObject(sealedObject); 
      outputStream.close(); 
     } catch (IllegalBlockSizeException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static Object decrypt(InputStream istream, byte[] keyy, String transformationnn) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { 
     SecretKeySpec sks = new SecretKeySpec(keyy, transformationnn); 
     Cipher cipher = Cipher.getInstance(transformationnn); 
     cipher.init(Cipher.DECRYPT_MODE, sks); 

     CipherInputStream cipherInputStream = new CipherInputStream(istream, cipher); 
     ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream); 
     SealedObject sealedObject; 
     try { 
      sealedObject = (SealedObject) inputStream.readObject(); 
      return sealedObject.getObject(cipher); 
     } catch (ClassNotFoundException | IllegalBlockSizeException | BadPaddingException e) { 
      e.printStackTrace(); 
      return null; 
     } 
    } 

我提出了2個軟件(SOFT1和soft2)使用這個類(SerializableEncryptDecrypt)。該軟件對輸入數據(相同的輸入數據)進行加密和串行化。當我比較輸出數據和我給出的輸入是完全不同的數據時。但我需要相同的輸出數據。

在此先感謝您的幫助。

+0

請正確格式化您的代碼。 – Badda

回答

0

使用salt(nonce,IV,...)對隨機加密進行隨機化是一種很好的做法,即使您使用相同的密鑰以相同的值進行加密,您可能(也應該)得到不同的輸出。在某些情況下,輸出相同會降低安全性。

我不能確定,但​​我敢打賭,這就是「SealedObject」的作用。如果你真的需要「相同的輸出」,你可以直接序列化對象(不使用SealedObject)。但是,你負責儲存鹽,認證標籤等。

請注意 - 如果你在一些真實的項目中使用這個代碼,你不應該存儲密碼(甚至加密),只有他們的鹽漬密碼哈希如果需要的話。