0
我有一個應該寫入文件系統的'javax.mail.Message'對象。我使用版本爲1.5.5的javax.mail(com.sun.mail)安全性:將javax.mail.Message寫入帶加密的文件
javax.mail.Message message = buildMessage(...);
message.writeTo(new FileOutputStream("message.plain"));
現在將消息寫入文件。但是我怎麼能加密&解密這個文件?我在下面發表我的例子,但是這段代碼失敗了。
我的示例代碼:
static byte[] salt = new byte[8];
static {
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
}
public final void test() throws Exception {
Message message = buildTestMessage(...);
SecretKey secret = encode(message, new FileOutputStream("test.encrypted"), "".toCharArray());
Message message2 = decode(new FileInputStream("test.encrypted"), "".toCharArray());
// out sth. like [email protected] <--> null
System.out.println(message.getFrom()[0] + " <--> " + message2.getFrom());
}
private Message decode(
InputStream mailFileInputStream, char[] password) throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, MessagingException, IOException, InvalidKeySpecException {
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "PBEWithHmacSHA256AndAES_128");
Cipher cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
cipher.init(Cipher.DECRYPT_MODE, secret);
InputStream is = new CipherInputStream(mailFileInputStream, cipher);
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session, is);
return message;
}
static SecretKey encode(
Message message,
FileOutputStream out,
char[] password) throws Exception {
/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "PBEWithHmacSHA256AndAES_128");
Cipher cipher = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
cipher.init(Cipher.ENCRYPT_MODE, secret);
OutputStream cos = new CipherOutputStream(out, cipher);
message.writeTo(cos);
cos.close();
return secret;
}
附加:給予好評,我的問題,我紀念你的答案被接受。我有一個問題禁令,沒有任何問題留在我的問題上或沒有留意!
沒有人有任何想法嗎?是......不清楚?如果這個問題沒有得到解答或者投票結果,我無法創建新的問題,因爲我有個問題ban @ stackoverflow ... – hiaclibe