aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/eu/siacs/conversations/crypto/axolotl/XmppAxolotlMessage.java
blob: 4b87fc5cb8c45c3ff6202bf2611ae8aeb380d8c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package eu.siacs.conversations.crypto.axolotl;

import android.util.Base64;

import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.util.HashSet;
import java.util.Set;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.xml.Element;

public class XmppAxolotlMessage {
    private byte[] innerKey;
    private byte[] ciphertext;
    private byte[] iv;
    private final Set<XmppAxolotlMessageHeader> headers;
    private final Contact contact;
    private final int sourceDeviceId;

    public static class XmppAxolotlMessageHeader {
        private final int recipientDeviceId;
        private final byte[] content;

        public XmppAxolotlMessageHeader(int deviceId, byte[] content) {
            this.recipientDeviceId = deviceId;
            this.content = content;
        }

        public XmppAxolotlMessageHeader(Element header) {
            if("header".equals(header.getName())) {
                this.recipientDeviceId = Integer.parseInt(header.getAttribute("rid"));
                this.content = Base64.decode(header.getContent(),Base64.DEFAULT);
            } else {
                throw new IllegalArgumentException("Argument not a <header> Element!");
            }
        }
        
        public int getRecipientDeviceId() {
            return recipientDeviceId;
        }

        public byte[] getContents() {
            return content;
        }

        public Element toXml() {
            Element headerElement = new Element("header");
            // TODO: generate XML
            headerElement.setAttribute("rid", getRecipientDeviceId());
            headerElement.setContent(Base64.encodeToString(getContents(), Base64.DEFAULT));
            return headerElement;
        }
    }

    public static class XmppAxolotlPlaintextMessage {
        private final AxolotlService.XmppAxolotlSession session;
        private final String plaintext;

        public XmppAxolotlPlaintextMessage(AxolotlService.XmppAxolotlSession session, String plaintext) {
            this.session = session;
            this.plaintext = plaintext;
        }

        public String getPlaintext() {
            return plaintext;
        }
    }

    public XmppAxolotlMessage(Contact contact, Element axolotlMessage) {
        this.contact = contact;
        this.sourceDeviceId = Integer.parseInt(axolotlMessage.getAttribute("id"));
        this.headers = new HashSet<>();
        for(Element child:axolotlMessage.getChildren()) {
            switch(child.getName()) {
                case "header":
                    headers.add(new XmppAxolotlMessageHeader(child));
                    break;
                case "message":
                    iv = Base64.decode(child.getAttribute("iv"),Base64.DEFAULT);
                    ciphertext = Base64.decode(child.getContent(),Base64.DEFAULT);
                    break;
                default:
                    break;
            }
        }
    }

    public XmppAxolotlMessage(Contact contact, int sourceDeviceId, String plaintext) {
        this.contact = contact;
        this.sourceDeviceId = sourceDeviceId;
        this.headers = new HashSet<>();
        this.encrypt(plaintext);
    }

    private void encrypt(String plaintext) {
        try {
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            generator.init(128);
            SecretKey secretKey = generator.generateKey();
            Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            this.innerKey = secretKey.getEncoded();
            this.iv = cipher.getIV();
            this.ciphertext = cipher.doFinal(plaintext.getBytes());
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | IllegalBlockSizeException | BadPaddingException e) {

        }
    }

    public Contact getContact() {
        return this.contact;
    }

    public int getSenderDeviceId() {
        return sourceDeviceId;
    }
    
    public byte[] getCiphertext() {
        return ciphertext;
    }

    public Set<XmppAxolotlMessageHeader> getHeaders() {
        return headers;
    }

    public void addHeader(XmppAxolotlMessageHeader header) {
        headers.add(header);
    }

    public byte[] getInnerKey(){
        return innerKey;
    }

    public byte[] getIV() {
        return this.iv;
    }

    public Element toXml() {
        // TODO: generate outer XML, add in header XML
        Element message= new Element("axolotl_message", AxolotlService.PEP_PREFIX);
        message.setAttribute("id", sourceDeviceId);
        for(XmppAxolotlMessageHeader header: headers) {
            message.addChild(header.toXml());
        }
        Element payload = message.addChild("message");
        payload.setAttribute("iv",Base64.encodeToString(iv, Base64.DEFAULT));
        payload.setContent(Base64.encodeToString(ciphertext,Base64.DEFAULT));
        return message;
    }


    public XmppAxolotlPlaintextMessage decrypt(AxolotlService.XmppAxolotlSession session, byte[] key) {
        XmppAxolotlPlaintextMessage plaintextMessage = null;
        try {

            Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
            SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

            String plaintext = new String(cipher.doFinal(ciphertext));
            plaintextMessage = new XmppAxolotlPlaintextMessage(session, plaintext);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException
                | BadPaddingException e) {
            throw new AssertionError(e);
        }
        return plaintextMessage;
    }
}