/
AesCbcEncryption.java
191 lines (158 loc) · 6.72 KB
/
AesCbcEncryption.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
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
185
186
187
188
189
190
191
package at.favre.lib.armadillo;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import at.favre.lib.bytes.Bytes;
import at.favre.lib.crypto.HKDF;
/**
* Implements AES (Advanced Encryption Standard) with Cipher Block Chaining (CBC), which is a mode of
* operation for symmetric key cryptographic block ciphers. For integrity it uses HMAC with SHA-256,
* using the encrypt-then-mac schema.
* <p>
* The iv, mac and encrypted content will be encoded to the following format:
* <p>
* out = byte[] {x y y y y y y y y y y y y i j j ... z z z ...}
* <p>
* x = IV length as byte
* y = IV bytes
* i = mac length as byte
* j = mac bytes
* z = content bytes (encrypted content, auth tag)
*
* @author Patrick Favre-Bulle
* @since 27.10.2018
* @deprecated this is only meant for Kitkat backwards compatibly as this version and below does not
* support AES-GCM with JCA.
*/
@SuppressWarnings({"WeakerAccess", "DeprecatedIsStillUsed"})
@Deprecated
final class AesCbcEncryption implements AuthenticatedEncryption {
private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final int IV_LENGTH_BYTE = 16;
private final SecureRandom secureRandom;
private final Provider provider;
private Cipher cipher;
public AesCbcEncryption() {
this(new SecureRandom(), null);
}
public AesCbcEncryption(SecureRandom secureRandom) {
this(secureRandom, null);
}
public AesCbcEncryption(SecureRandom secureRandom, Provider provider) {
this.secureRandom = secureRandom;
this.provider = provider;
}
@Override
public byte[] encrypt(byte[] rawEncryptionKey, byte[] rawData, @Nullable byte[] associatedData) throws AuthenticatedEncryptionException {
if (rawEncryptionKey.length < 16) {
throw new IllegalArgumentException("key length must be longer than 16 bytes");
}
byte[] iv = null;
byte[] encrypted = null;
byte[] mac = null;
try {
iv = new byte[IV_LENGTH_BYTE];
secureRandom.nextBytes(iv);
final Cipher cipherEnc = getCipher();
cipherEnc.init(Cipher.ENCRYPT_MODE, createEncryptionKey(rawEncryptionKey), new IvParameterSpec(iv));
encrypted = cipherEnc.doFinal(rawData);
mac = macCipherText(rawEncryptionKey, encrypted, iv, associatedData);
ByteBuffer byteBuffer = ByteBuffer.allocate(1 + iv.length + 1 + mac.length + encrypted.length);
byteBuffer.put((byte) iv.length);
byteBuffer.put(iv);
byteBuffer.put((byte) mac.length);
byteBuffer.put(mac);
byteBuffer.put(encrypted);
return byteBuffer.array();
} catch (Exception e) {
throw new AuthenticatedEncryptionException("could not encrypt", e);
} finally {
Bytes.wrapNullSafe(iv).mutable().secureWipe();
Bytes.wrapNullSafe(encrypted).mutable().secureWipe();
Bytes.wrapNullSafe(mac).mutable().secureWipe();
}
}
@NonNull
private SecretKeySpec createEncryptionKey(byte[] rawEncryptionKey) {
return new SecretKeySpec(HKDF.fromHmacSha256().expand(rawEncryptionKey, Bytes.from("encKey").array(), rawEncryptionKey.length), "AES");
}
private byte[] macCipherText(byte[] rawEncryptionKey, byte[] cipherText, byte[] iv, @Nullable byte[] associatedData)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKey macKey = createMacKey(rawEncryptionKey);
Mac hmac = Mac.getInstance(HMAC_ALGORITHM);
hmac.init(macKey);
hmac.update(iv);
hmac.update(cipherText);
if (associatedData != null) {
hmac.update(associatedData);
}
return hmac.doFinal();
}
@NonNull
private SecretKey createMacKey(byte[] rawEncryptionKey) {
byte[] derivedMacKey = HKDF.fromHmacSha256().expand(rawEncryptionKey, Bytes.from("macKey").array(), 32);
return new SecretKeySpec(derivedMacKey, HMAC_ALGORITHM);
}
@Override
public byte[] decrypt(byte[] rawEncryptionKey, byte[] encryptedData, @Nullable byte[] associatedData) throws AuthenticatedEncryptionException {
byte[] iv = null;
byte[] mac = null;
byte[] encrypted = null;
try {
ByteBuffer byteBuffer = ByteBuffer.wrap(encryptedData);
int ivLength = byteBuffer.get();
iv = new byte[ivLength];
byteBuffer.get(iv);
int macLength = byteBuffer.get();
mac = new byte[macLength];
byteBuffer.get(mac);
encrypted = new byte[byteBuffer.remaining()];
byteBuffer.get(encrypted);
verifyMac(rawEncryptionKey, encrypted, iv, mac, associatedData);
final Cipher cipherDec = getCipher();
cipherDec.init(Cipher.DECRYPT_MODE, createEncryptionKey(rawEncryptionKey), new IvParameterSpec(iv));
return cipherDec.doFinal(encrypted);
} catch (Exception e) {
throw new AuthenticatedEncryptionException("could not decrypt", e);
} finally {
Bytes.wrapNullSafe(iv).mutable().secureWipe();
Bytes.wrapNullSafe(encrypted).mutable().secureWipe();
Bytes.wrapNullSafe(mac).mutable().secureWipe();
}
}
private void verifyMac(byte[] rawEncryptionKey, byte[] cipherText, byte[] iv, byte[] mac, @Nullable byte[] associatedData)
throws InvalidKeyException, NoSuchAlgorithmException {
byte[] actualMac = macCipherText(rawEncryptionKey, cipherText, iv, associatedData);
if (!Bytes.wrap(mac).equalsConstantTime(actualMac)) {
throw new SecurityException("encryption integrity exception: mac does not match");
}
}
@Override
public int byteSizeLength(@KeyStrength int keyStrengthType) {
return keyStrengthType == STRENGTH_HIGH ? 16 : 32;
}
private Cipher getCipher() {
if (cipher == null) {
try {
if (provider != null) {
cipher = Cipher.getInstance(ALGORITHM, provider);
} else {
cipher = Cipher.getInstance(ALGORITHM);
}
} catch (Exception e) {
throw new IllegalStateException("could not get cipher instance", e);
}
}
return cipher;
}
}