JingleTransport.java

 1package eu.siacs.conversations.xmpp.jingle;
 2
 3import android.util.Log;
 4
 5import java.io.FileInputStream;
 6import java.io.FileNotFoundException;
 7import java.io.FileOutputStream;
 8import java.io.InputStream;
 9import java.io.OutputStream;
10import java.security.InvalidAlgorithmParameterException;
11import java.security.InvalidKeyException;
12import java.security.NoSuchAlgorithmException;
13
14import javax.crypto.Cipher;
15import javax.crypto.CipherInputStream;
16import javax.crypto.CipherOutputStream;
17import javax.crypto.NoSuchPaddingException;
18import javax.crypto.spec.IvParameterSpec;
19import javax.crypto.spec.SecretKeySpec;
20
21import eu.siacs.conversations.Config;
22import eu.siacs.conversations.entities.DownloadableFile;
23
24public abstract class JingleTransport {
25	public abstract void connect(final OnTransportConnected callback);
26
27	public abstract void receive(final DownloadableFile file,
28			final OnFileTransmissionStatusChanged callback);
29
30	public abstract void send(final DownloadableFile file,
31			final OnFileTransmissionStatusChanged callback);
32
33	public abstract void disconnect();
34
35	protected InputStream createInputStream(DownloadableFile file) {
36		FileInputStream is;
37		try {
38			is = new FileInputStream(file);
39			if (file.getKey() == null) {
40				return is;
41			}
42		} catch (FileNotFoundException e) {
43			return null;
44		}
45		try {
46			IvParameterSpec ips = new IvParameterSpec(file.getIv());
47			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
48			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(file.getKey(), "AES"), ips);
49			Log.d(Config.LOGTAG, "opening encrypted input stream");
50			return new CipherInputStream(is, cipher);
51		} catch (InvalidKeyException e) {
52			return null;
53		} catch (NoSuchAlgorithmException e) {
54			return null;
55		} catch (NoSuchPaddingException e) {
56			return null;
57		} catch (InvalidAlgorithmParameterException e) {
58			return null;
59		}
60	}
61
62	protected OutputStream createOutputStream(DownloadableFile file) {
63		FileOutputStream os;
64		try {
65			os = new FileOutputStream(file);
66			if (file.getKey() == null) {
67				return os;
68			}
69		} catch (FileNotFoundException e) {
70			return null;
71		}
72		try {
73			IvParameterSpec ips = new IvParameterSpec(file.getIv());
74			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
75			cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(file.getKey(), "AES"), ips);
76			Log.d(Config.LOGTAG, "opening encrypted output stream");
77			return new CipherOutputStream(os, cipher);
78		} catch (InvalidKeyException e) {
79			return null;
80		} catch (NoSuchAlgorithmException e) {
81			return null;
82		} catch (NoSuchPaddingException e) {
83			return null;
84		} catch (InvalidAlgorithmParameterException e) {
85			return null;
86		}
87	}
88}