BackupFileHeader.java

 1package eu.siacs.conversations.utils;
 2
 3import androidx.annotation.NonNull;
 4
 5import java.io.DataInputStream;
 6import java.io.DataOutputStream;
 7import java.io.IOException;
 8
 9import eu.siacs.conversations.xmpp.Jid;
10
11public class BackupFileHeader {
12
13    private static final int VERSION = 2;
14
15    private final String app;
16    private final Jid jid;
17    private final long timestamp;
18    private final byte[] iv;
19    private final byte[] salt;
20
21
22    @NonNull
23    @Override
24    public String toString() {
25        return "BackupFileHeader{" +
26                "app='" + app + '\'' +
27                ", jid=" + jid +
28                ", timestamp=" + timestamp +
29                ", iv=" + CryptoHelper.bytesToHex(iv) +
30                ", salt=" + CryptoHelper.bytesToHex(salt) +
31                '}';
32    }
33
34    public BackupFileHeader(String app, Jid jid, long timestamp, byte[] iv, byte[] salt) {
35        this.app = app;
36        this.jid = jid;
37        this.timestamp = timestamp;
38        this.iv = iv;
39        this.salt = salt;
40    }
41
42    public void write(DataOutputStream dataOutputStream) throws IOException {
43        dataOutputStream.writeInt(VERSION);
44        dataOutputStream.writeUTF(app);
45        dataOutputStream.writeUTF(jid.asBareJid().toEscapedString());
46        dataOutputStream.writeLong(timestamp);
47        dataOutputStream.write(iv);
48        dataOutputStream.write(salt);
49    }
50
51    public static BackupFileHeader read(DataInputStream inputStream) throws IOException {
52        final int version = inputStream.readInt();
53        if (version != VERSION) {
54            throw new IllegalArgumentException("Backup File version was " + version + " but app only supports version " + VERSION);
55        }
56        String app = inputStream.readUTF();
57        String jid = inputStream.readUTF();
58        long timestamp = inputStream.readLong();
59        byte[] iv = new byte[12];
60        inputStream.readFully(iv);
61        byte[] salt = new byte[16];
62        inputStream.readFully(salt);
63
64        return new BackupFileHeader(app, Jid.of(jid), timestamp, iv, salt);
65
66    }
67
68    public byte[] getSalt() {
69        return salt;
70    }
71
72    public byte[] getIv() {
73        return iv;
74    }
75
76    public Jid getJid() {
77        return jid;
78    }
79
80    public String getApp() {
81        return app;
82    }
83
84    public long getTimestamp() {
85        return timestamp;
86    }
87}