forked from hap-java/HAP-Java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChachaDecoder.java
52 lines (37 loc) · 1.71 KB
/
ChachaDecoder.java
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
package io.github.hapjava.server.impl.crypto;
import java.io.IOException;
import org.bouncycastle.crypto.engines.ChaChaEngine;
import org.bouncycastle.crypto.generators.Poly1305KeyGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import org.bouncycastle.util.Arrays;
public class ChachaDecoder {
private final ChaChaEngine decryptCipher;
public ChachaDecoder(byte[] key, byte[] nonce) throws IOException {
this.decryptCipher = new ChaChaEngine(20);
this.decryptCipher.init(false, new ParametersWithIV(new KeyParameter(key), nonce));
}
public byte[] decodeCiphertext(byte[] receivedMAC, byte[] additionalData, byte[] ciphertext)
throws IOException {
KeyParameter macKey = initRecordMAC(decryptCipher);
byte[] calculatedMAC = PolyKeyCreator.create(macKey, additionalData, ciphertext);
if (!Arrays.constantTimeAreEqual(calculatedMAC, receivedMAC)) {
throw new IOException("received an incorrect MAC");
}
byte[] output = new byte[ciphertext.length];
decryptCipher.processBytes(ciphertext, 0, ciphertext.length, output, 0);
return output;
}
public byte[] decodeCiphertext(byte[] receivedMAC, byte[] ciphertext) throws IOException {
return decodeCiphertext(receivedMAC, null, ciphertext);
}
private KeyParameter initRecordMAC(ChaChaEngine cipher) {
byte[] firstBlock = new byte[64];
cipher.processBytes(firstBlock, 0, firstBlock.length, firstBlock, 0);
// NOTE: The BC implementation puts 'r' after 'k'
System.arraycopy(firstBlock, 0, firstBlock, 32, 16);
KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);
Poly1305KeyGenerator.clamp(macKey.getKey());
return macKey;
}
}