Skip to content

Commit 4fdc309

Browse files
Refactor JceMasterKey to extract logic to be shared by raw keyrings. (#139)
* Refactor JceMasterKey to extract logic to be shared by raw keyrings. *Issue #, if available:* #102 *Description of changes:* In anticipation of the RawAesKeyring and RawRsaKeyring needing logic currently embedded in the JceMasterKey, this change extracts that logic into the JceKeyCipher class so it may be shared. By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. - [ ] Were any files moved? Moving files changes their URL, which breaks all hyperlinks to the files.
1 parent 47fe973 commit 4fdc309

File tree

6 files changed

+403
-258
lines changed

6 files changed

+403
-258
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
/*
2+
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
5+
* in compliance with the License. A copy of the License is located at
6+
*
7+
* http://aws.amazon.com/apache2.0
8+
*
9+
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11+
* specific language governing permissions and limitations under the License.
12+
*/
13+
14+
package com.amazonaws.encryptionsdk.internal;
15+
16+
import javax.crypto.Cipher;
17+
import javax.crypto.SecretKey;
18+
import javax.crypto.spec.GCMParameterSpec;
19+
import java.nio.ByteBuffer;
20+
import java.security.GeneralSecurityException;
21+
import java.security.InvalidKeyException;
22+
import java.security.Key;
23+
import java.util.Map;
24+
25+
/**
26+
* A JceKeyCipher based on the Advanced Encryption Standard in Galois/Counter Mode.
27+
*/
28+
class AesGcmJceKeyCipher extends JceKeyCipher {
29+
private static final int NONCE_LENGTH = 12;
30+
private static final int TAG_LENGTH = 128;
31+
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
32+
private static final int SPEC_LENGTH = Integer.BYTES + Integer.BYTES + NONCE_LENGTH;
33+
34+
AesGcmJceKeyCipher(SecretKey key) {
35+
super(key, key);
36+
}
37+
38+
private static byte[] specToBytes(final GCMParameterSpec spec) {
39+
final byte[] nonce = spec.getIV();
40+
final byte[] result = new byte[SPEC_LENGTH];
41+
final ByteBuffer buffer = ByteBuffer.wrap(result);
42+
buffer.putInt(spec.getTLen());
43+
buffer.putInt(nonce.length);
44+
buffer.put(nonce);
45+
return result;
46+
}
47+
48+
private static GCMParameterSpec bytesToSpec(final byte[] data, final int offset) throws InvalidKeyException {
49+
if (data.length - offset != SPEC_LENGTH) {
50+
throw new InvalidKeyException("Algorithm specification was an invalid data size");
51+
}
52+
53+
final ByteBuffer buffer = ByteBuffer.wrap(data, offset, SPEC_LENGTH);
54+
final int tagLen = buffer.getInt();
55+
final int nonceLen = buffer.getInt();
56+
57+
if (tagLen != TAG_LENGTH) {
58+
throw new InvalidKeyException(String.format("Authentication tag length must be %s", TAG_LENGTH));
59+
}
60+
61+
if (nonceLen != NONCE_LENGTH) {
62+
throw new InvalidKeyException(String.format("Initialization vector (IV) length must be %s", NONCE_LENGTH));
63+
}
64+
65+
final byte[] nonce = new byte[nonceLen];
66+
buffer.get(nonce);
67+
68+
return new GCMParameterSpec(tagLen, nonce);
69+
}
70+
71+
@Override
72+
WrappingData buildWrappingCipher(final Key key, final Map<String, String> encryptionContext)
73+
throws GeneralSecurityException {
74+
final byte[] nonce = new byte[NONCE_LENGTH];
75+
Utils.getSecureRandom().nextBytes(nonce);
76+
final GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH, nonce);
77+
final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
78+
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
79+
final byte[] aad = EncryptionContextSerializer.serialize(encryptionContext);
80+
cipher.updateAAD(aad);
81+
return new WrappingData(cipher, specToBytes(spec));
82+
}
83+
84+
@Override
85+
Cipher buildUnwrappingCipher(final Key key, final byte[] extraInfo, final int offset,
86+
final Map<String, String> encryptionContext) throws GeneralSecurityException {
87+
final GCMParameterSpec spec = bytesToSpec(extraInfo, offset);
88+
final Cipher cipher = Cipher.getInstance(TRANSFORMATION);
89+
cipher.init(Cipher.DECRYPT_MODE, key, spec);
90+
final byte[] aad = EncryptionContextSerializer.serialize(encryptionContext);
91+
cipher.updateAAD(aad);
92+
return cipher;
93+
}
94+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
/*
2+
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
5+
* in compliance with the License. A copy of the License is located at
6+
*
7+
* http://aws.amazon.com/apache2.0
8+
*
9+
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11+
* specific language governing permissions and limitations under the License.
12+
*/
13+
14+
package com.amazonaws.encryptionsdk.internal;
15+
16+
import com.amazonaws.encryptionsdk.EncryptedDataKey;
17+
import com.amazonaws.encryptionsdk.exception.AwsCryptoException;
18+
import com.amazonaws.encryptionsdk.model.KeyBlob;
19+
import org.apache.commons.lang3.ArrayUtils;
20+
21+
import javax.crypto.Cipher;
22+
import javax.crypto.SecretKey;
23+
import java.nio.charset.Charset;
24+
import java.nio.charset.StandardCharsets;
25+
import java.security.GeneralSecurityException;
26+
import java.security.Key;
27+
import java.security.PrivateKey;
28+
import java.security.PublicKey;
29+
import java.util.Map;
30+
31+
/**
32+
* Abstract class for encrypting and decrypting JCE data keys.
33+
*/
34+
public abstract class JceKeyCipher {
35+
36+
private final Key wrappingKey;
37+
private final Key unwrappingKey;
38+
private static final Charset KEY_NAME_ENCODING = StandardCharsets.UTF_8;
39+
40+
/**
41+
* Returns a new instance of a JceKeyCipher based on the
42+
* Advanced Encryption Standard in Galois/Counter Mode.
43+
*
44+
* @param secretKey The secret key to use for encrypt/decrypt operations.
45+
* @return The JceKeyCipher.
46+
*/
47+
public static JceKeyCipher aesGcm(SecretKey secretKey) {
48+
return new AesGcmJceKeyCipher(secretKey);
49+
}
50+
51+
/**
52+
* Returns a new instance of a JceKeyCipher based on RSA.
53+
*
54+
* @param wrappingKey The public key to use for encrypting the key.
55+
* @param unwrappingKey The private key to use for decrypting the key.
56+
* @param transformation The transformation.
57+
* @return The JceKeyCipher.
58+
*/
59+
public static JceKeyCipher rsa(PublicKey wrappingKey, PrivateKey unwrappingKey, String transformation) {
60+
return new RsaJceKeyCipher(wrappingKey, unwrappingKey, transformation);
61+
}
62+
63+
JceKeyCipher(Key wrappingKey, Key unwrappingKey) {
64+
this.wrappingKey = wrappingKey;
65+
this.unwrappingKey = unwrappingKey;
66+
}
67+
68+
abstract WrappingData buildWrappingCipher(Key key, Map<String, String> encryptionContext) throws GeneralSecurityException;
69+
70+
abstract Cipher buildUnwrappingCipher(Key key, byte[] extraInfo, int offset,
71+
Map<String, String> encryptionContext) throws GeneralSecurityException;
72+
73+
74+
/**
75+
* Encrypts the given key, incorporating the given keyName and encryptionContext.
76+
* @param key The key to encrypt.
77+
* @param keyName A UTF-8 encoded representing a name for the key.
78+
* @param keyNamespace A UTF-8 encoded value that namespaces the key.
79+
* @param encryptionContext A key-value mapping of arbitrary, non-secret, UTF-8 encoded strings used
80+
* during encryption and decryption to provide additional authenticated data (AAD).
81+
* @return The encrypted data key.
82+
*/
83+
public EncryptedDataKey encryptKey(final byte[] key, final String keyName, final String keyNamespace,
84+
final Map<String, String> encryptionContext) {
85+
86+
final byte[] keyNameBytes = keyName.getBytes(KEY_NAME_ENCODING);
87+
88+
try {
89+
final JceKeyCipher.WrappingData wData = buildWrappingCipher(wrappingKey, encryptionContext);
90+
final Cipher cipher = wData.cipher;
91+
final byte[] encryptedKey = cipher.doFinal(key);
92+
93+
final byte[] provInfo;
94+
if (wData.extraInfo.length == 0) {
95+
provInfo = keyNameBytes;
96+
} else {
97+
provInfo = new byte[keyNameBytes.length + wData.extraInfo.length];
98+
System.arraycopy(keyNameBytes, 0, provInfo, 0, keyNameBytes.length);
99+
System.arraycopy(wData.extraInfo, 0, provInfo, keyNameBytes.length, wData.extraInfo.length);
100+
}
101+
102+
return new KeyBlob(keyNamespace, provInfo, encryptedKey);
103+
} catch (final GeneralSecurityException gsex) {
104+
throw new AwsCryptoException(gsex);
105+
}
106+
}
107+
108+
/**
109+
* Decrypts the given encrypted data key.
110+
*
111+
* @param edk The encrypted data key.
112+
* @param keyName A UTF-8 encoded String representing a name for the key.
113+
* @param encryptionContext A key-value mapping of arbitrary, non-secret, UTF-8 encoded strings used
114+
* during encryption and decryption to provide additional authenticated data (AAD).
115+
* @return The decrypted key.
116+
* @throws GeneralSecurityException If a problem occurred decrypting the key.
117+
*/
118+
public byte[] decryptKey(final EncryptedDataKey edk, final String keyName,
119+
final Map<String, String> encryptionContext) throws GeneralSecurityException {
120+
final byte[] keyNameBytes = keyName.getBytes(KEY_NAME_ENCODING);
121+
122+
final Cipher cipher = buildUnwrappingCipher(unwrappingKey, edk.getProviderInformation(),
123+
keyNameBytes.length, encryptionContext);
124+
return cipher.doFinal(edk.getEncryptedDataKey());
125+
}
126+
127+
static class WrappingData {
128+
public final Cipher cipher;
129+
public final byte[] extraInfo;
130+
131+
WrappingData(final Cipher cipher, final byte[] extraInfo) {
132+
this.cipher = cipher;
133+
this.extraInfo = extraInfo != null ? extraInfo : ArrayUtils.EMPTY_BYTE_ARRAY;
134+
}
135+
}
136+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*
2+
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except
5+
* in compliance with the License. A copy of the License is located at
6+
*
7+
* http://aws.amazon.com/apache2.0
8+
*
9+
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
11+
* specific language governing permissions and limitations under the License.
12+
*/
13+
14+
package com.amazonaws.encryptionsdk.internal;
15+
16+
import org.apache.commons.lang3.ArrayUtils;
17+
18+
import javax.crypto.Cipher;
19+
import javax.crypto.spec.OAEPParameterSpec;
20+
import javax.crypto.spec.PSource;
21+
import java.security.GeneralSecurityException;
22+
import java.security.Key;
23+
import java.security.PrivateKey;
24+
import java.security.PublicKey;
25+
import java.security.spec.AlgorithmParameterSpec;
26+
import java.security.spec.MGF1ParameterSpec;
27+
import java.util.Map;
28+
import java.util.logging.Logger;
29+
import java.util.regex.Matcher;
30+
import java.util.regex.Pattern;
31+
32+
/**
33+
* A JceKeyCipher based on RSA.
34+
*/
35+
class RsaJceKeyCipher extends JceKeyCipher {
36+
37+
private static final Logger LOGGER = Logger.getLogger(RsaJceKeyCipher.class.getName());
38+
// MGF1 with SHA-224 isn't really supported, but we include it in the regex because we need it
39+
// for proper handling of the algorithm.
40+
private static final Pattern SUPPORTED_TRANSFORMATIONS =
41+
Pattern.compile("RSA/ECB/(?:PKCS1Padding|OAEPWith(SHA-(?:1|224|256|384|512))AndMGF1Padding)",
42+
Pattern.CASE_INSENSITIVE);
43+
private final AlgorithmParameterSpec parameterSpec_;
44+
private final String transformation_;
45+
46+
RsaJceKeyCipher(PublicKey wrappingKey, PrivateKey unwrappingKey, String transformation) {
47+
super(wrappingKey, unwrappingKey);
48+
49+
final Matcher matcher = SUPPORTED_TRANSFORMATIONS.matcher(transformation);
50+
if (matcher.matches()) {
51+
final String hashUnknownCase = matcher.group(1);
52+
if (hashUnknownCase != null) {
53+
// OAEP mode a.k.a PKCS #1v2
54+
final String hash = hashUnknownCase.toUpperCase();
55+
transformation_ = "RSA/ECB/OAEPPadding";
56+
57+
final MGF1ParameterSpec mgf1Spec;
58+
switch (hash) {
59+
case "SHA-1":
60+
mgf1Spec = MGF1ParameterSpec.SHA1;
61+
break;
62+
case "SHA-224":
63+
LOGGER.warning(transformation + " is not officially supported by the JceMasterKey");
64+
mgf1Spec = MGF1ParameterSpec.SHA224;
65+
break;
66+
case "SHA-256":
67+
mgf1Spec = MGF1ParameterSpec.SHA256;
68+
break;
69+
case "SHA-384":
70+
mgf1Spec = MGF1ParameterSpec.SHA384;
71+
break;
72+
case "SHA-512":
73+
mgf1Spec = MGF1ParameterSpec.SHA512;
74+
break;
75+
default:
76+
throw new IllegalArgumentException("Unsupported algorithm: " + transformation);
77+
}
78+
parameterSpec_ = new OAEPParameterSpec(hash, "MGF1", mgf1Spec, PSource.PSpecified.DEFAULT);
79+
} else {
80+
// PKCS #1 v1.x
81+
transformation_ = transformation;
82+
parameterSpec_ = null;
83+
}
84+
} else {
85+
LOGGER.warning(transformation + " is not officially supported by the JceMasterKey");
86+
// Unsupported transformation, just use exactly what we are given
87+
transformation_ = transformation;
88+
parameterSpec_ = null;
89+
}
90+
}
91+
92+
@Override
93+
WrappingData buildWrappingCipher(Key key, Map<String, String> encryptionContext) throws GeneralSecurityException {
94+
final Cipher cipher = Cipher.getInstance(transformation_);
95+
cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec_);
96+
return new WrappingData(cipher, ArrayUtils.EMPTY_BYTE_ARRAY);
97+
}
98+
99+
@Override
100+
Cipher buildUnwrappingCipher(Key key, byte[] extraInfo, int offset, Map<String, String> encryptionContext) throws GeneralSecurityException {
101+
if (extraInfo.length != offset) {
102+
throw new IllegalArgumentException("Extra info must be empty for RSA keys");
103+
}
104+
105+
final Cipher cipher = Cipher.getInstance(transformation_);
106+
cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec_);
107+
return cipher;
108+
}
109+
}

src/main/java/com/amazonaws/encryptionsdk/internal/Utils.java

+21
Original file line numberDiff line numberDiff line change
@@ -311,4 +311,25 @@ public static byte[] bigIntegerToByteArray(final BigInteger bigInteger, final in
311311
System.arraycopy(rawBytes, 0, paddedResult, length - rawBytes.length, rawBytes.length);
312312
return paddedResult;
313313
}
314+
315+
/**
316+
* Returns true if the prefix of the given length for the input arrays are equal.
317+
* This method will return as soon as the first difference is found, and is thus not constant-time.
318+
*
319+
* @param a The first array.
320+
* @param b The second array.
321+
* @param length The length of the prefix to compare.
322+
* @return True if the prefixes are equal, false otherwise.
323+
*/
324+
public static boolean arrayPrefixEquals(final byte[] a, final byte[] b, final int length) {
325+
if (a == null || b == null || a.length < length || b.length < length) {
326+
return false;
327+
}
328+
for (int x = 0; x < length; x++) {
329+
if (a[x] != b[x]) {
330+
return false;
331+
}
332+
}
333+
return true;
334+
}
314335
}

0 commit comments

Comments
 (0)