index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/FrameEncryptionHandlerVeryLongTest.java
package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.fail; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.model.CipherFrameHeaders; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; /* * This test exhaustively encrypts a 2^32 frame message, which takes approximately 2-3 hours on my hardware. Because of * this long test time, this test is not run as part of the normal suites. */ public class FrameEncryptionHandlerVeryLongTest { @Test public void exhaustiveIVCheck() throws Exception { CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF; FrameEncryptionHandler frameEncryptionHandler_ = new FrameEncryptionHandler( new SecretKeySpec(new byte[16], "AES"), 12, algorithm, new byte[16], 1); byte[] buf = new byte[1024]; ByteBuffer expectedNonce = ByteBuffer.allocate(12); long lastIndex = 1; // starting index for the test long lastTS = System.nanoTime(); for (long i = lastIndex; i <= Constants.MAX_FRAME_NUMBER; i++) { Utils.clear(expectedNonce); expectedNonce.order(ByteOrder.BIG_ENDIAN); expectedNonce.putInt(0); expectedNonce.putLong(i); if (i != Constants.MAX_FRAME_NUMBER) { frameEncryptionHandler_.processBytes(buf, 0, 1, buf, 0); } else { frameEncryptionHandler_.doFinal(buf, 0); } CipherFrameHeaders headers = new CipherFrameHeaders(); headers.setNonceLength(algorithm.getNonceLen()); headers.deserialize(buf, 0); byte[] nonce = headers.getNonce(); byte[] expectedArray = expectedNonce.array(); if (!Arrays.equals(nonce, expectedArray)) { fail( String.format( "Index %08x bytes %s != %s", i, new String(Hex.encode(nonce)), new String(Hex.encode(expectedArray)))); } if ((i & 0xFFFFF) == 0) { // Print progress messages, since this test takes a _very_ long time to run. System.out.print( String.format( "%05.2f%% complete", 100 * (double) i / (double) Constants.MAX_FRAME_NUMBER)); long newTS = System.nanoTime(); System.out.println( String.format( " at a rate of %f/sec\n", (i - lastIndex) / ((newTS - lastTS) / 1_000_000_000.0))); lastTS = newTS; lastIndex = i; } } } }
5,400
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunctionTest.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import com.amazonaws.util.StringUtils; import org.junit.Test; public class HmacKeyDerivationFunctionTest { private static final testCase[] testCases = new testCase[] { new testCase( "HmacSHA256", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"), fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"), fromHex( "3CB25F25FAACD57A90434F64D0362F2A2D2D0A90CF1A5A4C5DB02D56ECC4C5BF34007208D5B887185865")), new testCase( "HmacSHA256", fromCHex( "\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d" + "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b" + "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29" + "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37" + "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45" + "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"), fromCHex( "\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6a\\x6b\\x6c\\x6d" + "\\x6e\\x6f\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7a\\x7b" + "\\x7c\\x7d\\x7e\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89" + "\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97" + "\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5" + "\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf"), fromCHex( "\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd" + "\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb" + "\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9" + "\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7" + "\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5" + "\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"), fromHex( "B11E398DC80327A1C8E7F78C596A4934" + "4F012EDA2D4EFAD8A050CC4C19AFA97C" + "59045A99CAC7827271CB41C65E590E09" + "DA3275600C2F09B8367793A9ACA3DB71" + "CC30C58179EC3E87C14C01D5C1F3434F" + "1D87")), new testCase( "HmacSHA256", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), new byte[0], new byte[0], fromHex( "8DA4E775A563C18F715F802A063C5A31" + "B8A11F5C5EE1879EC3454E5F3C738D2D" + "9D201395FAA4B61A96C8")), new testCase( "HmacSHA1", fromCHex("\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"), fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"), fromHex( "085A01EA1B10F36933068B56EFA5AD81" + "A4F14B822F5B091568A9CDD4F155FDA2" + "C22E422478D305F3F896")), new testCase( "HmacSHA1", fromCHex( "\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d" + "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b" + "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29" + "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37" + "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45" + "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"), fromCHex( "\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6A\\x6B\\x6C\\x6D" + "\\x6E\\x6F\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7A\\x7B" + "\\x7C\\x7D\\x7E\\x7F\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89" + "\\x8A\\x8B\\x8C\\x8D\\x8E\\x8F\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97" + "\\x98\\x99\\x9A\\x9B\\x9C\\x9D\\x9E\\x9F\\xA0\\xA1\\xA2\\xA3\\xA4\\xA5" + "\\xA6\\xA7\\xA8\\xA9\\xAA\\xAB\\xAC\\xAD\\xAE\\xAF"), fromCHex( "\\xB0\\xB1\\xB2\\xB3\\xB4\\xB5\\xB6\\xB7\\xB8\\xB9\\xBA\\xBB\\xBC\\xBD" + "\\xBE\\xBF\\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB" + "\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD7\\xD8\\xD9" + "\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7" + "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5" + "\\xF6\\xF7\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF"), fromHex( "0BD770A74D1160F7C9F12CD5912A06EB" + "FF6ADCAE899D92191FE4305673BA2FFE" + "8FA3F1A4E5AD79F3F334B3B202B2173C" + "486EA37CE3D397ED034C7F9DFEB15C5E" + "927336D0441F4C4300E2CFF0D0900B52D3B4")), new testCase( "HmacSHA1", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), new byte[0], new byte[0], fromHex("0AC1AF7002B3D761D1E55298DA9D0506" + "B9AE52057220A306E07B6B87E8DF21D0")), new testCase( "HmacSHA1", fromCHex( "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c" + "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"), null, new byte[0], fromHex( "2C91117204D745F3500D636A62F64F0A" + "B3BAE548AA53D423B0D1F27EBBA6F5E5" + "673A081D70CCE7ACFC48")) }; @Test public void rfc5869Tests() throws Exception { for (int x = 0; x < testCases.length; x++) { testCase trial = testCases[x]; System.out.println("Test case A." + (x + 1)); HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); byte[] result = kdf.deriveKey(trial.info, trial.expected.length); assertArrayEquals("Trial A." + x, trial.expected, result); } } @Test public void nullTests() throws Exception { testCase trial = testCases[0]; HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); // Just ensuring no exceptions are thrown kdf.deriveKey(null, 16); } @Test(expected = IllegalArgumentException.class) public void invalidLength() throws Exception { testCase trial = testCases[0]; HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); kdf.deriveKey(trial.info, -1); } @Test public void defaultSalt() throws Exception { // Tests all the different ways to get the default salt testCase trial = testCases[0]; HmacKeyDerivationFunction kdf1 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf1.init(trial.ikm, null); HmacKeyDerivationFunction kdf2 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf2.init(trial.ikm, new byte[0]); HmacKeyDerivationFunction kdf3 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf3.init(trial.ikm); HmacKeyDerivationFunction kdf4 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf4.init(trial.ikm, new byte[32]); byte[] testBytes = "Test".getBytes(StringUtils.UTF8); byte[] key1 = kdf1.deriveKey(testBytes, 16); byte[] key2 = kdf2.deriveKey(testBytes, 16); byte[] key3 = kdf3.deriveKey(testBytes, 16); byte[] key4 = kdf4.deriveKey(testBytes, 16); assertArrayEquals(key1, key2); assertArrayEquals(key1, key3); assertArrayEquals(key1, key4); } private static byte[] fromHex(String data) { byte[] result = new byte[data.length() / 2]; for (int x = 0; x < result.length; x++) { result[x] = (byte) Integer.parseInt(data.substring(2 * x, 2 * x + 2), 16); } return result; } private static byte[] fromCHex(String data) { byte[] result = new byte[data.length() / 4]; for (int x = 0; x < result.length; x++) { result[x] = (byte) Integer.parseInt(data.substring(4 * x + 2, 4 * x + 4), 16); } return result; } private static class testCase { public final String algo; public final byte[] ikm; public final byte[] salt; public final byte[] info; public final byte[] expected; testCase(String algo, byte[] ikm, byte[] salt, byte[] info, byte[] expected) { super(); this.algo = algo; this.ikm = ikm; this.salt = salt; this.info = info; this.expected = expected; } } }
5,401
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/AwsKmsCmkArnInfoTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.jupiter.api.DisplayName; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class AwsKmsCmkArnInfoTest { public static class splitArn { @Test public void basic_use() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.splitArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); assertEquals(test.length, 6); } @Test public void with_fewer_elements() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.splitArn("arn:aws:kms:us-west-2"); assertEquals(test.length, 4); } @Test public void with_valid_arn_but_not_kms_valid() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.splitArn( "arn:aws:kms:us-west-2:111122223333:key:mrk-edb7fe6942894d32ac46dbb1c922d574"); assertEquals(test.length, 6); } } public static class splitResourceParts { @Test public void basic_use() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.Resource.splitResourceParts( "key/mrk-edb7fe6942894d32ac46dbb1c922d574"); assertEquals(test.length, 2); } } public static class parseInfoFromKeyArn { @Test public void basic_use() { AwsKmsCmkArnInfo test = AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); assertNotNull(test); assertEquals(test.getPartition(), "aws"); assertEquals(test.getRegion(), "us-west-2"); assertEquals(test.getAccountId(), "111122223333"); assertEquals(test.getAccountId(), "111122223333"); assertEquals(test.getResourceType(), "key"); assertEquals(test.getResource(), "mrk-edb7fe6942894d32ac46dbb1c922d574"); } @Test @DisplayName("Precondition: keyArn must be a string.") public void keyArn_must_be_string_with_content() { assertEquals(AwsKmsCmkArnInfo.parseInfoFromKeyArn(""), null); assertEquals(AwsKmsCmkArnInfo.parseInfoFromKeyArn(null), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # MUST start with string "arn" public void not_well_formed() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn("key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); assertEquals(AwsKmsCmkArnInfo.parseInfoFromKeyArn("alias/my-key"), null); assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "not-an-arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The service MUST be the string "kms" public void not_kms_service() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn("arn:aws:sqs:us-east-2:444455556666:queue1"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The partition MUST be a non-empty public void partition_non_empty() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn::kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The region MUST be a non-empty string public void region_non_empty() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms::111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The account MUST be a non-empty string public void account_non_empty() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2::key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The resource section MUST be non-empty and MUST be split by a // # single "/" any additional "/" are included in the resource id public void resource_non_empty() { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The resource id MUST be a non-empty string assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn("arn:aws:kms:us-west-2:111122223333:"), null); assertEquals( // This is a valid ARN but not valid for AWS KMS AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key:mrk-edb7fe6942894d32ac46dbb1c922d574"), null); final AwsKmsCmkArnInfo arn = AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:alias/has/slashes"); assertNotNull(arn); assertEquals(arn.getResource(), "has/slashes"); } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The resource type MUST be either "alias" or "key" public void resource_type_key_or_alias() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:not-key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } } public static class validAwsKmsIdentifier { @Test public void basic_use() { AwsKmsCmkArnInfo.validAwsKmsIdentifier("mrk-edb7fe6942894d32ac46dbb1c922d574"); AwsKmsCmkArnInfo.validAwsKmsIdentifier("alias/my-alias"); AwsKmsCmkArnInfo.validAwsKmsIdentifier( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); AwsKmsCmkArnInfo.validAwsKmsIdentifier("arn:aws:kms:us-west-2:111122223333:alias/my-alias"); } @Test @DisplayName("Exceptional Postcondition: Null or empty string is not a valid identifier.") public void must_have_content() { assertThrows( IllegalArgumentException.class, "Null or empty string is not a valid Aws KMS identifier.", () -> AwsKmsCmkArnInfo.validAwsKmsIdentifier("")); assertThrows( IllegalArgumentException.class, "Null or empty string is not a valid Aws KMS identifier.", () -> AwsKmsCmkArnInfo.validAwsKmsIdentifier(null)); } @Test @DisplayName("Exceptional Postcondition: Things that start with `arn:` MUST be ARNs.") public void arn_must_be_arn() { assertThrows( IllegalArgumentException.class, "Invalid ARN used as an identifier.", () -> AwsKmsCmkArnInfo.validAwsKmsIdentifier( "arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable")); } @Test @DisplayName("Postcondition: Raw alias starts with `alias/`.") public void alias_is_valid() { AwsKmsCmkArnInfo.validAwsKmsIdentifier("alias/some/kind/of/alias"); } @Test @DisplayName("Postcondition: There are no requirements on key ids.") public void anything_else_is_key_id() { AwsKmsCmkArnInfo.validAwsKmsIdentifier("mrk-edb7fe6942894d32ac46dbb1c922d574"); AwsKmsCmkArnInfo.validAwsKmsIdentifier("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"); } } public static class isMRK { @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # This function MUST take a single AWS KMS identifier public void basic_use() { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If the input starts // # with "mrk-", this is a multi-Region key id and MUST return true. assertEquals(AwsKmsCmkArnInfo.isMRK("mrk-edb7fe6942894d32ac46dbb1c922d574"), true); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If the input starts with "alias/", this an AWS KMS alias and // # not a multi-Region key id and MUST return false. assertEquals(AwsKmsCmkArnInfo.isMRK("alias/mrk-1234"), false); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If // # the input does not start with any of the above, this is not a multi- // # Region key id and MUST return false. assertEquals(AwsKmsCmkArnInfo.isMRK("64339c87-2ae4-42b1-8875-c83fc47acc97"), false); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If the input starts with "arn:", this MUST return the output of // # identifying an an AWS KMS multi-Region ARN (aws-kms-key- // # arn.md#identifying-an-an-aws-kms-multi-region-arn) called with this // # input. assertEquals( AwsKmsCmkArnInfo.isMRK( "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If the input is an invalid AWS KMS ARN this function MUST error. public void invalid_arn() { assertThrows( () -> AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:not-key/mrk-edb7fe6942894d32ac46dbb1c922d574"))); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If resource type is "alias", this is an AWS KMS alias ARN and MUST // # return false. public void with_an_alias_AwsKmsCmkArnInfo() { assertEquals( AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574")), false); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # This function MUST take a single AWS KMS ARN public void with_an_mrk_AwsKmsCmkArnInfo() { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If resource type is "key" and resource ID starts with // # "mrk-", this is a AWS KMS multi-Region key ARN and MUST return true. assertEquals( AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")), true); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If resource type is "key" and resource ID does not start with "mrk-", // # this is a (single-region) AWS KMS key ARN and MUST return false. public void with_an_srk_AwsKmsCmkArnInfo() { assertEquals( AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")), false); } } public static class awsKmsArnMatchForDecrypt { @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # The caller MUST provide: public void basic_use() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # If both identifiers are identical, this function MUST return "true". public void string_match_cases() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97", "arn:aws:kms:us-west-2:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:alias/my-name", "arn:aws:kms:us-west-2:111122223333:alias/my-name"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt("alias/my-raw-alias", "alias/my-raw-alias"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "64339c87-2ae4-42b1-8875-c83fc47acc97", "64339c87-2ae4-42b1-8875-c83fc47acc97"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "c83fc47acc97", "64339c87-2ae4-42b1-8875-c83fc47acc97"), false); } @Test @DisplayName( "Check for early return (Postcondition): Both identifiers are not ARNs and not equal, therefore they can not match.") public void flexibility_for_only_arns() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # Otherwise if either input is not identified as a multi-Region key // # (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then // # this function MUST return "false". public void no_flexibility_for_non_mrks() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97", "arn:aws:kms:us-east-1:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97"), false); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:alias/mrk-someOtherName", "arn:aws:kms:us-east-1:111122223333:alias/mrk-someOtherName"), false); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # Otherwise if both inputs are // # identified as a multi-Region keys (aws-kms-key-arn.md#identifying-an- // # aws-kms-multi-region-key), this function MUST return the result of // # comparing the "partition", "service", "accountId", "resourceType", // # and "resource" parts of both ARN inputs. public void all_elements_must_match() { // Different partition assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:not-aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); // Different account assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-east-1:333322221111:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); // Different resource type assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:not-aws:kms:us-east-1:111122223333:not-key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); // Different resource assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-east-1:111122223333:key/mrk-475d229c1bbd64ca23d4982496ef7bde", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); } } public static class to_string_tests { @Test public void basic_use() { final String arn = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String region = "us-east-1"; final AwsKmsCmkArnInfo test = AwsKmsCmkArnInfo.parseInfoFromKeyArn(arn); assertEquals(arn, test.toString()); assertEquals( "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", test.toString("us-east-1")); } } }
5,402
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/CipherHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.util.Arrays; import java.util.EnumSet; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; public class CipherHandlerTest { private final int contentLen_ = 1024; // 1KB private final byte[] contentAad_ = "Test string AAD".getBytes(); @Test public void encryptDecryptWithAllAlgos() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { assertTrue(encryptDecryptContent(cryptoAlg)); assertTrue(encryptDecryptEmptyContent(cryptoAlg)); } } @Test(expected = BadCiphertextException.class) public void tamperCiphertext() { final CryptoAlgorithm cryptoAlgorithm = TestUtils.DEFAULT_TEST_CRYPTO_ALG; final byte[] content = RandomBytesGenerator.generate(contentLen_); final byte[] keyBytes = RandomBytesGenerator.generate(cryptoAlgorithm.getKeyLength()); final byte[] nonce = RandomBytesGenerator.generate(cryptoAlgorithm.getNonceLen()); final SecretKey key = new SecretKeySpec(keyBytes, cryptoAlgorithm.getKeyAlgo()); CipherHandler cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.ENCRYPT_MODE); final byte[] encryptedBytes = cipherHandler.cipherData(nonce, contentAad_, content, 0, content.length); encryptedBytes[0] += 1; // tamper the first byte in ciphertext cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.DECRYPT_MODE); cipherHandler.cipherData(nonce, contentAad_, encryptedBytes, 0, encryptedBytes.length); } private boolean encryptDecryptContent(final CryptoAlgorithm cryptoAlgorithm) { final byte[] content = RandomBytesGenerator.generate(contentLen_); final byte[] result = encryptDecrypt(content, cryptoAlgorithm); return Arrays.equals(content, result) ? true : false; } private boolean encryptDecryptEmptyContent(final CryptoAlgorithm cryptoAlgorithm) { final byte[] result = encryptDecrypt(new byte[0], cryptoAlgorithm); return (result.length == 0) ? true : false; } private byte[] encryptDecrypt(final byte[] content, final CryptoAlgorithm cryptoAlgorithm) { final byte[] keyBytes = RandomBytesGenerator.generate(cryptoAlgorithm.getKeyLength()); final byte[] nonce = RandomBytesGenerator.generate(cryptoAlgorithm.getNonceLen()); final SecretKey key = new SecretKeySpec(keyBytes, cryptoAlgorithm.getKeyAlgo()); CipherHandler cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.ENCRYPT_MODE); final byte[] encryptedBytes = cipherHandler.cipherData(nonce, contentAad_, content, 0, content.length); cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.DECRYPT_MODE); final byte[] decryptedBytes = cipherHandler.cipherData(nonce, contentAad_, encryptedBytes, 0, encryptedBytes.length); return decryptedBytes; } private CipherHandler createCipherHandler( final SecretKey key, final CryptoAlgorithm cryptoAlgorithm, final int mode) { return new CipherHandler(key, mode, cryptoAlgorithm); } }
5,403
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/BlockDecryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.nio.ByteBuffer; import java.security.SecureRandom; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; public class BlockDecryptionHandlerTest { private static final SecureRandom RND = new SecureRandom(); private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = new byte[cryptoAlgorithm_.getMessageIdLength()]; private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = new byte[cryptoAlgorithm_.getKeyLength()]; private final SecretKey dataKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private final BlockDecryptionHandler blockDecryptionHandler_ = new BlockDecryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_); @Before public void setup() { RND.nextBytes(messageId_); RND.nextBytes(dataKeyBytes_); } @Test public void estimateOutputSize() { final int inLen = 1; final int outSize = blockDecryptionHandler_.estimateOutputSize(inLen); // the estimated output size must at least be equal to inLen. assertTrue(outSize >= inLen); } @Test(expected = BadCiphertextException.class) public void doFinalCalledWhileNotComplete() { blockDecryptionHandler_.doFinal(new byte[1], 0); } @Test(expected = AwsCryptoException.class) public void decryptMaxContentLength() { final BlockEncryptionHandler blockEncryptionHandler = new BlockEncryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_); final byte[] in = new byte[0]; final int outLen = blockEncryptionHandler.estimateOutputSize(in.length); final byte[] out = new byte[outLen]; blockEncryptionHandler.processBytes(in, 0, in.length, out, 0); blockEncryptionHandler.doFinal(out, 0); final ByteBuffer outBuff = ByteBuffer.wrap(out); // pull out nonce to get to content length. final byte[] nonce = new byte[nonceLen_]; outBuff.get(nonce); // set content length to integer max value + 1. outBuff.putLong(Integer.MAX_VALUE + 1L); final int decryptedOutLen = blockDecryptionHandler_.estimateOutputSize(outLen); final byte[] decryptedOut = new byte[decryptedOutLen]; blockDecryptionHandler_.processBytes( outBuff.array(), 0, outBuff.array().length, decryptedOut, 0); } @Test(expected = AwsCryptoException.class) public void processBytesCalledWhileComplete() { final BlockEncryptionHandler blockEncryptionHandler = new BlockEncryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_); final byte[] in = new byte[0]; final int outLen = blockEncryptionHandler.estimateOutputSize(in.length); final byte[] out = new byte[outLen]; blockEncryptionHandler.processBytes(in, 0, in.length, out, 0); blockEncryptionHandler.doFinal(out, 0); final byte[] decryptedOut = new byte[outLen]; blockDecryptionHandler_.processBytes(out, 0, outLen, decryptedOut, 0); blockDecryptionHandler_.processBytes(out, 0, outLen, decryptedOut, 0); } }
5,404
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/EncryptionHandlerTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static java.util.Collections.emptyList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; public class EncryptionHandlerTest { private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final int frameSize_ = AwsCrypto.getDefaultFrameSize(); private final Map<String, String> encryptionContext_ = Collections.<String, String>emptyMap(); private StaticMasterKey masterKeyProvider = new StaticMasterKey("mock"); private final List<StaticMasterKey> cmks_ = Collections.singletonList(masterKeyProvider); private final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private EncryptionMaterialsRequest testRequest = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext_) .setRequestedAlgorithm(cryptoAlgorithm_) .setCommitmentPolicy(commitmentPolicy) .build(); private EncryptionMaterials testResult = new DefaultCryptoMaterialsManager(masterKeyProvider).getMaterialsForEncrypt(testRequest); @Test public void badArguments() { assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setAlgorithm(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setEncryptionContext(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setEncryptedDataKeys(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setEncryptedDataKeys(emptyList()).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setCleartextDataKey(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setMasterKeys(null).build(), commitmentPolicy)); assertThrows(() -> new EncryptionHandler(-1, testResult, commitmentPolicy)); assertThrows(() -> new EncryptionHandler(frameSize_, testResult, null)); } @Test(expected = AwsCryptoException.class) public void invalidLenProcessBytes() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); final byte[] in = new byte[1]; final byte[] out = new byte[1]; encryptionHandler.processBytes(in, 0, -1, out, 0); } @Test(expected = AwsCryptoException.class) public void invalidOffsetProcessBytes() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); final byte[] in = new byte[1]; final byte[] out = new byte[1]; encryptionHandler.processBytes(in, -1, in.length, out, 0); } @Test public void whenEncrypting_headerIVIsZero() throws Exception { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); assertArrayEquals( new byte[encryptionHandler.getHeaders().getCryptoAlgoId().getNonceLen()], encryptionHandler.getHeaders().getHeaderNonce()); } @Test public void whenConstructWithForbidPolicyAndCommittingAlg_fails() throws Exception { final EncryptionMaterials resultWithV2Alg = testResult.toBuilder().setAlgorithm(TestUtils.DEFAULT_TEST_CRYPTO_ALG).build(); assertThrows( AwsCryptoException.class, () -> new EncryptionHandler( frameSize_, resultWithV2Alg, CommitmentPolicy.ForbidEncryptAllowDecrypt)); } @Test public void whenConstructWithForbidPolicyAndNonCommittingAlg_succeeds() throws Exception { final CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final EncryptionMaterialsRequest requestForMaterialsWithoutCommitment = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext_) .setRequestedAlgorithm(algorithm) .setCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); final EncryptionMaterials materials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(requestForMaterialsWithoutCommitment); EncryptionHandler handler = new EncryptionHandler(frameSize_, materials, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertNotNull(handler); assertEquals(algorithm, handler.getHeaders().getCryptoAlgoId()); } @Test public void whenConstructWithRequirePolicyAndNonCommittingAlg_fails() throws Exception { final EncryptionMaterials resultWithV1Alg = testResult.toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384) .build(); assertThrows( AwsCryptoException.class, () -> new EncryptionHandler( frameSize_, resultWithV1Alg, CommitmentPolicy.RequireEncryptRequireDecrypt)); assertThrows( AwsCryptoException.class, () -> new EncryptionHandler( frameSize_, resultWithV1Alg, CommitmentPolicy.RequireEncryptAllowDecrypt)); } @Test public void whenConstructWithRequirePolicyAndCommittingAlg_succeeds() throws Exception { final CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; final EncryptionMaterialsRequest requestForMaterialsWithCommitment = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext_) .setRequestedAlgorithm(algorithm) .setCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); final EncryptionMaterials materials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(requestForMaterialsWithCommitment); final List<CommitmentPolicy> requireWritePolicies = Arrays.asList( CommitmentPolicy.RequireEncryptAllowDecrypt, CommitmentPolicy.RequireEncryptRequireDecrypt); for (CommitmentPolicy policy : requireWritePolicies) { EncryptionHandler handler = new EncryptionHandler(frameSize_, materials, policy); assertNotNull(handler); assertEquals(algorithm, handler.getHeaders().getCryptoAlgoId()); } } @Test public void setMaxInputLength() { byte[] plaintext = "Don't warn the tadpoles".getBytes(); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); encryptionHandler.setMaxInputLength(plaintext.length - 1); assertEquals(encryptionHandler.getMaxInputLength(), (long) plaintext.length - 1); final byte[] out = new byte[1]; assertThrows( IllegalStateException.class, "Plaintext size exceeds max input size limit", () -> encryptionHandler.processBytes(plaintext, 0, plaintext.length, out, 0)); } @Test public void setMaxInputLengthThrowsIfAlreadyOver() { byte[] plaintext = "Don't warn the tadpoles".getBytes(); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); final byte[] out = new byte[1024]; encryptionHandler.processBytes(plaintext, 0, plaintext.length - 1, out, 0); assertFalse(encryptionHandler.isComplete()); assertThrows( IllegalStateException.class, "Plaintext size exceeds max input size limit", () -> encryptionHandler.setMaxInputLength(plaintext.length - 2)); } @Test public void setMaxInputLengthAcceptsSmallerValue() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); encryptionHandler.setMaxInputLength(100); assertEquals(encryptionHandler.getMaxInputLength(), 100); encryptionHandler.setMaxInputLength(10); assertEquals(encryptionHandler.getMaxInputLength(), 10); } @Test public void setMaxInputLengthIgnoresLargerValue() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); encryptionHandler.setMaxInputLength(10); assertEquals(encryptionHandler.getMaxInputLength(), 10); encryptionHandler.setMaxInputLength(100); assertEquals(encryptionHandler.getMaxInputLength(), 10); } }
5,405
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/FrameDecryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.nio.ByteBuffer; import java.security.SecureRandom; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; public class FrameDecryptionHandlerTest { private static final SecureRandom RND = new SecureRandom(); private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = new byte[cryptoAlgorithm_.getMessageIdLength()]; private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = new byte[cryptoAlgorithm_.getKeyLength()]; private final SecretKey dataKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private final int frameSize_ = AwsCrypto.getDefaultFrameSize(); private final FrameDecryptionHandler frameDecryptionHandler_ = new FrameDecryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_, frameSize_); @Before public void setup() { RND.nextBytes(messageId_); RND.nextBytes(dataKeyBytes_); } @Test public void estimateOutputSize() { final int inLen = 1; final int outSize = frameDecryptionHandler_.estimateOutputSize(inLen); // the estimated output size must at least be equal to inLen. assertTrue(outSize >= inLen); } @Test(expected = AwsCryptoException.class) public void decryptMaxContentLength() { // Create input of size 1 byte: 1 byte of the sequence number, // Only 1 byte of the sequence number is provided because this // forces the frame decryption handler to buffer that 1 byte while // waiting for the remaining bytes of the sequence number. We do this so // we can specify an input of max value and the total bytes to parse // will become max value + 1. final byte[] in = new byte[1]; final byte[] out = new byte[1]; frameDecryptionHandler_.processBytes(in, 0, in.length, out, 0); frameDecryptionHandler_.processBytes(in, 0, Integer.MAX_VALUE, out, 0); } @Test(expected = BadCiphertextException.class) public void finalFrameLengthTooLarge() { final ByteBuffer byteBuffer = ByteBuffer.allocate(25); byteBuffer.put( TestUtils.unsignedBytesToSignedBytes( new int[] {255, 255, 255, 255, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})); byteBuffer.putInt(AwsCrypto.getDefaultFrameSize() + 1); final byte[] in = byteBuffer.array(); final byte[] out = new byte[in.length]; frameDecryptionHandler_.processBytes(in, 0, in.length, out, 0); } @Test(expected = BadCiphertextException.class) public void doFinalCalledWhileNotComplete() { frameDecryptionHandler_.doFinal(new byte[1], 0); } @Test(expected = AwsCryptoException.class) public void processBytesCalledWhileComplete() { final FrameEncryptionHandler frameEncryptionHandler = new FrameEncryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_, frameSize_); final byte[] in = new byte[0]; final int outLen = frameEncryptionHandler.estimateOutputSize(in.length); final byte[] out = new byte[outLen]; frameEncryptionHandler.processBytes(in, 0, in.length, out, 0); frameEncryptionHandler.doFinal(out, 0); final byte[] decryptedOut = new byte[outLen]; frameDecryptionHandler_.processBytes(out, 0, out.length, decryptedOut, 0); frameDecryptionHandler_.processBytes(out, 0, out.length, decryptedOut, 0); } }
5,406
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/EncContextSerializerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.junit.Test; public class EncContextSerializerTest { @Test public void nullContext() { final byte[] ctxBytes = EncryptionContextSerializer.serialize(null); final Map<String, String> result = EncryptionContextSerializer.deserialize(ctxBytes); assertEquals(null, result); } @Test public void emptyContext() { testMap(Collections.<String, String>emptyMap()); } @Test public void singletonContext() { testMap(Collections.singletonMap("Alice:", "trusts Bob")); } @Test public void contextOrdering() throws Exception { // Context keys should be sorted by unsigned byte order Map<String, String> map = new HashMap<>(); map.put("\0", "\0"); map.put("\u0081", "\u0081"); // 0xC2 0x81 in UTF8 assertArrayEquals( new byte[] { 0, 2, // "\0" 0, 1, (byte) '\0', // "\0" 0, 1, (byte) '\0', // "\u0081" 0, 2, (byte) 0xC2, (byte) 0x81, // "\u0081" 0, 2, (byte) 0xC2, (byte) 0x81, }, EncryptionContextSerializer.serialize(map)); } @Test public void smallContext() { final Map<String, String> map = new HashMap<String, String>(); map.put("Alice:", "trusts Bob"); map.put("Bob:", "trusts Trent"); testMap(map); } @Test public void largeContext() { final int size = 100; final Map<String, String> ctx = new HashMap<String, String>(size); for (int x = 0; x < size; x++) { ctx.put(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeContext() { final int size = Short.MAX_VALUE; final Map<String, String> ctx = new HashMap<String, String>(size); // we want to be at least 1 over the (max) size. for (int x = 0; x <= size; x++) { ctx.put(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeKey() { final int size = 10; final Map<String, String> ctx = new HashMap<String, String>(size); final char[] keyChars = new char[Short.MAX_VALUE + 1]; final String key = new String(keyChars); for (int x = 0; x < size; x++) { ctx.put(key, UUID.randomUUID().toString()); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeValue() { final int size = 10; final Map<String, String> ctx = new HashMap<String, String>(size); final char[] valueChars = new char[Short.MAX_VALUE + 1]; final String value = new String(valueChars); for (int x = 0; x < size; x++) { ctx.put(UUID.randomUUID().toString(), value); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeContextBytes() { final char[] keyChars = new char[Short.MAX_VALUE]; final String key = new String(keyChars); final char[] valueChars = new char[Short.MAX_VALUE]; final String value = new String(valueChars); testMap(Collections.singletonMap(key, value)); } @Test(expected = IllegalArgumentException.class) public void contextWithBadUnicodeKey() { final StringBuilder invalidString = new StringBuilder("Valid text"); // Loop over invalid unicode codepoints for (int x = 0xd800; x <= 0xdfff; x++) { invalidString.appendCodePoint(x); } testMap(Collections.singletonMap(invalidString.toString(), "Valid value")); } @Test(expected = IllegalArgumentException.class) public void contextWithBadUnicodeValue() { final StringBuilder invalidString = new StringBuilder("Base valid text"); for (int x = 0xd800; x <= 0xdfff; x++) { // Invalid unicode codepoints invalidString.appendCodePoint(x); } testMap(Collections.singletonMap("Valid key", invalidString.toString())); } @Test(expected = AwsCryptoException.class) public void contextWithEmptyKey() { testMap(Collections.singletonMap("", "Value for empty key")); } @Test(expected = AwsCryptoException.class) public void contextWithEmptyValue() { testMap(Collections.singletonMap("Key for empty value", "")); } @Test(expected = AwsCryptoException.class) public void contextWithEmptyKeyAndValue() { testMap(Collections.singletonMap("", "")); } @Test(expected = AwsCryptoException.class) public void contextWithNullKey() { testMap(Collections.singletonMap((String) null, "value for null key")); } @Test(expected = AwsCryptoException.class) public void contextWithNullValue() { testMap(Collections.singletonMap("Key for null value", (String) null)); } @Test(expected = AwsCryptoException.class) public void contextWithNullKeyAndValue() { testMap(Collections.singletonMap((String) null, (String) null)); } @Test(expected = AwsCryptoException.class) public void contextWithLargeKey() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Overwrite key length ctxBuff.putShort((short) Constants.UNSIGNED_SHORT_MAX_VAL); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithShortKey() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Overwrite key length with 0 ctxBuff.putShort((short) 0); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithNegativeKey() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Overwrite key length with -1. ctxBuff.putShort((short) -1); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithLargeValue() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // Overwrite value length ctxBuff.putShort((short) Constants.UNSIGNED_SHORT_MAX_VAL); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithShortValue() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // Overwrite value length ctxBuff.putShort((short) 0); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithNegativeValue() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // Overwrite value length ctxBuff.putShort((short) -1); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithNegativeCount() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); ctx.put("Bob:", "trusts Trent"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Overwrite entry count ctxBuff.putShort((short) -1); EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithZeroCount() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); ctx.put("Bob:", "trusts Trent"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Overwrite entry count ctxBuff.putShort((short) 0); EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithInvalidCount() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); ctx.put("Bob:", "trusts Trent"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Overwrite count with more than what we have ctxBuff.putShort((short) 100); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = IllegalArgumentException.class) public void contextWithInvalidCharacters() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); ctxBuff.mark(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // set the first two bytes of the key to an invalid // unicode character: 0xd800. key[0] = 0x0; key[1] = (byte) 0xd8; ctxBuff.reset(); ctxBuff.put(key); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithDuplicateEntries() { final Map<String, String> ctx = Collections.singletonMap("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Don't duplicate the entry count final ByteBuffer dupCtxBuff = ByteBuffer.allocate((2 * ctxBytes.length) - 2); // Set to 2 entries dupCtxBuff.putShort((short) 2); // Pull out entry count to move to key pos ctxBuff.getShort(); // From here to the end is a single entry, copy it final byte[] entry = new byte[ctxBuff.remaining()]; ctxBuff.get(entry); dupCtxBuff.put(entry); dupCtxBuff.put(entry); EncryptionContextSerializer.deserialize(dupCtxBuff.array()); } private void testMap(final Map<String, String> ctx) { final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final Map<String, String> result = EncryptionContextSerializer.deserialize(ctxBytes); assertEquals(ctx, result); } }
5,407
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/BlockEncryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.model.CipherBlockHeaders; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; public class BlockEncryptionHandlerTest { private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = RandomBytesGenerator.generate(cryptoAlgorithm_.getMessageIdLength()); private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = RandomBytesGenerator.generate(cryptoAlgorithm_.getKeyLength()); private final SecretKey encryptionKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private BlockEncryptionHandler blockEncryptionHandler_; @Before public void setUp() throws Exception { blockEncryptionHandler_ = new BlockEncryptionHandler(encryptionKey_, nonceLen_, cryptoAlgorithm_, messageId_); } @Test public void emptyOutBytes() { final int outLen = 0; final byte[] out = new byte[outLen]; final int processedLen = blockEncryptionHandler_.doFinal(out, 0); assertEquals(outLen, processedLen); } @Test public void correctIVGenerated() throws Exception { final byte[] out = new byte[1024]; int outOff = blockEncryptionHandler_.processBytes(new byte[1], 0, 1, out, 0).getBytesWritten(); final int processedLen = blockEncryptionHandler_.doFinal(out, outOff); CipherBlockHeaders headers = new CipherBlockHeaders(); headers.setNonceLength(cryptoAlgorithm_.getNonceLen()); headers.deserialize(out, 0); assertArrayEquals( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, headers.getNonce()); } }
5,408
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/DecryptionHandlerTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.ParsedCiphertext; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.CiphertextType; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; public class DecryptionHandlerTest { private StaticMasterKey masterKeyProvider_; private final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private final CommitmentPolicy requireReadPolicy = CommitmentPolicy.RequireEncryptRequireDecrypt; private final List<CommitmentPolicy> allowReadPolicies = Arrays.asList( CommitmentPolicy.RequireEncryptAllowDecrypt, CommitmentPolicy.ForbidEncryptAllowDecrypt); private final SignaturePolicy signaturePolicy = SignaturePolicy.AllowEncryptAllowDecrypt; @Before public void init() { masterKeyProvider_ = new StaticMasterKey("testmaterial"); } @Test(expected = NullPointerException.class) public void nullMasterKey() { DecryptionHandler.create( (MasterKey) null, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); } @Test public void nullCommitment() { final byte[] ciphertext = getTestHeaders( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), null, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, null, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void nullSignaturePolicy() { final byte[] ciphertext = getTestHeaders( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), commitmentPolicy, null, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, null, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test(expected = AwsCryptoException.class) public void invalidLenProcessBytes() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] in = new byte[1]; final byte[] out = new byte[1]; decryptionHandler.processBytes(in, 0, -1, out, 0); } @Test(expected = AwsCryptoException.class) public void maxLenProcessBytes() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // Create input of size 3 bytes: 1 byte containing version, 1 byte // containing type, and 1 byte containing half of the algoId short // primitive. Only 1 byte of the algoId is provided because this // forces the decryption handler to buffer that 1 byte while waiting for // the other byte. We do this so we can specify an input of max // value and the total bytes to parse will become max value + 1. final byte[] in = new byte[3]; final byte[] out = new byte[3]; in[1] = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA.getValue(); decryptionHandler.processBytes(in, 0, in.length, out, 0); decryptionHandler.processBytes(in, 0, Integer.MAX_VALUE, out, 0); } @Test public void maxInputLength() { final byte[] testMessage = getTestMessage( TestUtils.DEFAULT_TEST_CRYPTO_ALG, CommitmentPolicy.RequireEncryptRequireDecrypt); final byte[] out = new byte[100]; final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(testMessage.length - 1); assertThrows( IllegalStateException.class, () -> decryptionHandler.processBytes(testMessage, 0, testMessage.length, out, 0)); } @Test public void maxInputLengthIncludingParsedCiphertext() { final byte[] testMessage = getTestMessage( TestUtils.DEFAULT_TEST_CRYPTO_ALG, CommitmentPolicy.RequireEncryptRequireDecrypt); final byte[] out = new byte[100]; ParsedCiphertext parsedHeaders = new ParsedCiphertext(testMessage); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, parsedHeaders, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(testMessage.length - 1); assertThrows( IllegalStateException.class, () -> decryptionHandler.processBytes( testMessage, parsedHeaders.getOffset(), testMessage.length - parsedHeaders.getOffset(), out, 0)); } @Test public void maxInputLengthIncludingCiphertextHeaders() { final byte[] testMessage = getTestMessage( TestUtils.DEFAULT_TEST_CRYPTO_ALG, CommitmentPolicy.RequireEncryptRequireDecrypt); final byte[] out = new byte[100]; ParsedCiphertext parsedHeaders = new ParsedCiphertext(testMessage); CiphertextHeaders headers = new CiphertextHeaders(); headers.deserialize( parsedHeaders.getCiphertext(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, headers, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(testMessage.length - 1); assertThrows( IllegalStateException.class, () -> decryptionHandler.processBytes( testMessage, parsedHeaders.getOffset(), testMessage.length - parsedHeaders.getOffset(), out, 0)); } @Test(expected = BadCiphertextException.class) public void headerIntegrityFailure() { byte[] ciphertext = getTestHeaders(); // tamper the fifth byte in the header which corresponds to the first // byte of the message identifier. We do this because tampering the // first four bytes will be detected as invalid values during parsing. ciphertext[5] += 1; // attempt to decrypt with the tampered header. final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); } @Test(expected = BadCiphertextException.class) public void invalidVersion() { byte[] ciphertext = getTestHeaders(); // set byte containing version to invalid value. ciphertext[0] = 0; // NOTE: This will need to be updated should 0 ever be a valid version // attempt to decrypt with the tampered header. final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); } @Test(expected = AwsCryptoException.class) public void invalidCMK() { final byte[] ciphertext = getTestHeaders(); masterKeyProvider_.setKeyId(masterKeyProvider_.getKeyId() + "nonsense"); // attempt to decrypt with the tampered header. final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); } @Test public void validAlgForCommitmentPolicyCreate() { // ensure we can decrypt non-committing algs with the policies that allow it final CryptoAlgorithm nonCommittingAlg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; for (CommitmentPolicy policy : allowReadPolicies) { final byte[] ciphertext = getTestHeaders(nonCommittingAlg, CommitmentPolicy.ForbidEncryptAllowDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, policy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // expected plaintext is zero length final byte[] plaintext = new byte[0]; ProcessingSummary processingSummary = decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); assertEquals(ciphertext.length, processingSummary.getBytesProcessed()); assertArrayEquals(new byte[0], plaintext); } // ensure we can decrypt committing algs with all policies final CryptoAlgorithm committingAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; for (CommitmentPolicy policy : CommitmentPolicy.values()) { final byte[] ciphertext = getTestHeaders(committingAlg, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, policy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // expected plaintext is zero length final byte[] plaintext = new byte[0]; ProcessingSummary processingSummary = decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); assertEquals(ciphertext.length, processingSummary.getBytesProcessed()); assertArrayEquals(new byte[0], plaintext); } } @Test public void invalidAlgForCommitmentPolicyCreateWithoutHeaders() { final CryptoAlgorithm nonCommittingAlg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final byte[] ciphertext = getTestHeaders(nonCommittingAlg, CommitmentPolicy.ForbidEncryptAllowDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, requireReadPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( AwsCryptoException.class, () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void invalidAlgForCommitmentPolicyCreateWithHeaders() { final CryptoAlgorithm nonCommittingAlg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final byte[] ciphertext = getTestHeaders(nonCommittingAlg, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertThrows( AwsCryptoException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), requireReadPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void validAlgForSignaturePolicyCreate() { // ensure we can decrypt non-signing algs with the policy that allows it final CryptoAlgorithm nonSigningAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; final byte[] ciphertext = getTestHeaders(nonSigningAlg, commitmentPolicy); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, SignaturePolicy.AllowEncryptAllowDecrypt, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // expected plaintext is zero length final byte[] plaintext = new byte[0]; ProcessingSummary processingSummary = decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); assertEquals(ciphertext.length, processingSummary.getBytesProcessed()); assertArrayEquals(new byte[0], plaintext); } @Test public void invalidAlgForSignaturePolicyCreateWithoutHeaders() { final CryptoAlgorithm signingAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; final byte[] ciphertext = getTestHeaders(signingAlg, commitmentPolicy); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, SignaturePolicy.AllowEncryptForbidDecrypt, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( AwsCryptoException.class, () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void invalidAlgForSignaturePolicyCreateWithHeaders() { final CryptoAlgorithm signingAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; final byte[] ciphertext = getTestHeaders(signingAlg, commitmentPolicy); assertThrows( AwsCryptoException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), commitmentPolicy, SignaturePolicy.AllowEncryptForbidDecrypt, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } private byte[] getTestHeaders() { return getTestHeaders( TestUtils.DEFAULT_TEST_CRYPTO_ALG, TestUtils.DEFAULT_TEST_COMMITMENT_POLICY, 1); } private byte[] getTestHeaders(CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy) { return getTestHeaders(cryptoAlgorithm, policy, 1); } private byte[] getTestHeaders(int numEdks) { return getTestHeaders( TestUtils.DEFAULT_TEST_CRYPTO_ALG, TestUtils.DEFAULT_TEST_COMMITMENT_POLICY, numEdks); } private byte[] getTestHeaders( CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy, int numEdks) { // Note that it's questionable to assume that failing to call doFinal() on the encryption // handler // always results in only outputting the header! return getTestMessage(cryptoAlgorithm, policy, numEdks, false); } private byte[] getTestMessage(CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy) { return getTestMessage(cryptoAlgorithm, policy, 1, true); } private byte[] getTestMessage( CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy, int numEdks, boolean doFinal) { final int frameSize_ = AwsCrypto.getDefaultFrameSize(); final Map<String, String> encryptionContext = Collections.<String, String>emptyMap(); final EncryptionMaterialsRequest encryptionMaterialsRequest = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(cryptoAlgorithm) .setCommitmentPolicy(policy) .build(); List<MasterKeyProvider<?>> providers = new ArrayList<>(); for (int i = 0; i < numEdks; i++) { providers.add(masterKeyProvider_); } MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(providers); final EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(provider) .getMaterialsForEncrypt(encryptionMaterialsRequest); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, encryptionMaterials, policy); // create the ciphertext headers by calling encryption handler. final byte[] in = new byte[0]; final int ciphertextLen = encryptionHandler.estimateOutputSize(in.length); final byte[] ciphertext = new byte[ciphertextLen]; ProcessingSummary summary = encryptionHandler.processBytes(in, 0, in.length, ciphertext, 0); if (doFinal) { encryptionHandler.doFinal(ciphertext, summary.getBytesWritten()); } return ciphertext; } @Test(expected = AwsCryptoException.class) public void invalidOffsetProcessBytes() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] in = new byte[1]; final byte[] out = new byte[1]; decryptionHandler.processBytes(in, -1, in.length, out, 0); } @Test(expected = BadCiphertextException.class) public void incompleteCiphertext() { byte[] ciphertext = getTestHeaders(); CiphertextHeaders h = new CiphertextHeaders(); h.deserialize(ciphertext, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; // Note the " - 1" is a bit deceptive: the ciphertext SHOULD already be incomplete because we // called getTestHeaders() above, so the whole body is missing! decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); decryptionHandler.doFinal(out, 0); } @Test public void incompleteCiphertextV2() { byte[] ciphertext = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); final DecryptionHandler<JceMasterKey> decryptionHandler = DecryptionHandler.create( TestUtils.messageWithCommitKeyMasterKey, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); assertThrows( BadCiphertextException.class, "Unable to process entire ciphertext.", () -> decryptionHandler.doFinal(out, 0)); } @Test public void incompleteCiphertextSigned() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); assertThrows( BadCiphertextException.class, "Unable to process entire ciphertext.", () -> decryptionHandler.doFinal(out, 0)); } @Test public void headerV2HeaderIntegrityFailure() { byte[] ciphertext = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); // Tamper the bytes that corresponds to the frame length. // This is the only reasonable way to tamper with this handcrafted message's // header which can still be successfully parsed. ciphertext[134] += 1; // attempt to decrypt with the tampered header. final DecryptionHandler<JceMasterKey> decryptionHandler = DecryptionHandler.create( TestUtils.messageWithCommitKeyMasterKey, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( BadCiphertextException.class, "Header integrity check failed", () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void headerV2BodyIntegrityFailure() { byte[] ciphertext = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); // Tamper the bytes that corresponds to the body auth ciphertext[ciphertext.length - 1] += 1; // attempt to decrypt with the tampered header. final DecryptionHandler<JceMasterKey> decryptionHandler = DecryptionHandler.create( TestUtils.messageWithCommitKeyMasterKey, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( BadCiphertextException.class, "Tag mismatch", () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void withLessThanMaxEdks() { byte[] header = getTestHeaders(2); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, 3); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(header, 0, header.length, plaintext, 0); } @Test public void withMaxEdks() { byte[] header = getTestHeaders(3); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, 3); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(header, 0, header.length, plaintext, 0); } @Test public void withMoreThanMaxEdks() { byte[] header = getTestHeaders(4); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, 3); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> decryptionHandler.processBytes(header, 0, header.length, plaintext, 0)); } @Test public void withNoMaxEdks() { byte[] header = getTestHeaders(1 << 16 - 1); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(header, 0, header.length, plaintext, 0); } @Test public void validSignatureAcrossMultipleBlocks() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; // Parse the header and body final int headerLength = 388; decryptionHandler.processBytes(ciphertext, 0, headerLength, out, 0); // Parse the footer across two calls // This used to fail to verify the signature because partial bytes were dropped instead. // The overall decryption would still succeed because the completeness check in doFinal // used to not include the footer. // The number of bytes read in the first chunk is completely arbitrary. The // parameterized CryptoOutputStreamTest tests covers lots of possible chunk // sizes much more thoroughly. This is just a very explicit regression unit test for a known // issue that is now fixed. final int firstChunkLength = 12; final int firstChunkOffset = headerLength; final int secondChunkOffset = headerLength + firstChunkLength; final int secondChunkLength = ciphertext.length - secondChunkOffset; decryptionHandler.processBytes(ciphertext, firstChunkOffset, firstChunkLength, out, 0); decryptionHandler.processBytes(ciphertext, secondChunkOffset, secondChunkLength, out, 0); decryptionHandler.doFinal(out, 0); } @Test public void invalidSignatureAcrossMultipleBlocks() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; // Parse the header and body decryptionHandler.processBytes(ciphertext, 0, 388, out, 0); // Process extra bytes before processing the actual signature bytes. // This used to actually work because the handler failed to buffer the unparsed bytes // across calls. To regression test this properly we have to parse the two bytes for the // length... decryptionHandler.processBytes(ciphertext, 388, 2, out, 0); // ...and after that any bytes fewer than that length would previously be dropped. decryptionHandler.processBytes(new byte[10], 0, 10, out, 0); assertThrows( BadCiphertextException.class, "Bad trailing signature", () -> decryptionHandler.processBytes(ciphertext, 390, ciphertext.length - 390, out, 0)); } @Test public void setMaxInputLength() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(ciphertext.length - 1); assertEquals(decryptionHandler.getMaxInputLength(), (long) ciphertext.length - 1); final byte[] out = new byte[1]; assertThrows( IllegalStateException.class, "Ciphertext size exceeds size bound", () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, out, 0)); } @Test public void setMaxInputLengthThrowsIfAlreadyOver() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); assertFalse(decryptionHandler.isComplete()); assertThrows( IllegalStateException.class, "Ciphertext size exceeds size bound", () -> decryptionHandler.setMaxInputLength(ciphertext.length - 2)); } @Test public void setMaxInputLengthAcceptsSmallerValue() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(100); assertEquals(decryptionHandler.getMaxInputLength(), 100); decryptionHandler.setMaxInputLength(10); assertEquals(decryptionHandler.getMaxInputLength(), 10); } @Test public void setMaxInputLengthIgnoresLargerValue() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(10); assertEquals(decryptionHandler.getMaxInputLength(), 10); decryptionHandler.setMaxInputLength(100); assertEquals(decryptionHandler.getMaxInputLength(), 10); } }
5,409
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/TrailingSignatureAlgorithmTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import java.math.BigInteger; import java.security.AlgorithmParameters; import java.security.KeyFactory; import java.security.PublicKey; import java.security.interfaces.ECPublicKey; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import org.junit.Test; public class TrailingSignatureAlgorithmTest { private static final int[] secp256r1PublicFixture_X = new int[] { 163, 132, 202, 41, 50, 135, 193, 159, 67, 19, 186, 212, 0, 129, 16, 182, 186, 176, 124, 94, 242, 139, 48, 143, 158, 96, 51, 133, 188, 144, 137, 148 }; private static final int[] secp256r1PublicFixture_Y = new int[] { 71, 234, 253, 112, 131, 106, 243, 169, 143, 58, 39, 222, 47, 211, 230, 90, 139, 163, 54, 249, 187, 115, 209, 203, 239, 98, 26, 47, 101, 213, 140, 212 }; private static final int[] secp2561CompressedFixture = new int[] { 2, 163, 132, 202, 41, 50, 135, 193, 159, 67, 19, 186, 212, 0, 129, 16, 182, 186, 176, 124, 94, 242, 139, 48, 143, 158, 96, 51, 133, 188, 144, 137, 148 }; private static final int[] secp384r1PublicFixture_X = new int[] { 207, 62, 215, 143, 116, 128, 174, 103, 1, 81, 127, 212, 163, 19, 165, 220, 74, 144, 26, 59, 87, 0, 214, 47, 66, 73, 152, 227, 196, 81, 14, 28, 58, 221, 178, 63, 150, 119, 62, 195, 99, 63, 60, 42, 223, 207, 28, 65 }; private static final int[] secp384r1PublicFixture_Y = new int[] { 180, 143, 190, 5, 150, 247, 225, 240, 153, 150, 119, 109, 210, 243, 151, 206, 217, 120, 2, 171, 75, 180, 31, 4, 91, 78, 206, 217, 241, 119, 55, 230, 216, 23, 237, 101, 21, 89, 132, 84, 100, 3, 255, 90, 197, 237, 139, 209 }; private static final int[] secp384r1CompressedFixture = new int[] { 3, 207, 62, 215, 143, 116, 128, 174, 103, 1, 81, 127, 212, 163, 19, 165, 220, 74, 144, 26, 59, 87, 0, 214, 47, 66, 73, 152, 227, 196, 81, 14, 28, 58, 221, 178, 63, 150, 119, 62, 195, 99, 63, 60, 42, 223, 207, 28, 65 }; @Test public void serializationEquality() throws Exception { CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256; PublicKey publicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).generateKey().getPublic(); String serializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).serializePublicKey(publicKey); PublicKey deserializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm) .deserializePublicKey(serializedPublicKey); assertEquals(publicKey, deserializedPublicKey); algorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; publicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).generateKey().getPublic(); serializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).serializePublicKey(publicKey); deserializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm) .deserializePublicKey(serializedPublicKey); assertEquals(publicKey, deserializedPublicKey); } @Test public void deserializeSecp384() { testDeserialization( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, secp384r1CompressedFixture, secp384r1PublicFixture_X, secp384r1PublicFixture_Y); } @Test public void serializeSecp384() throws Exception { testSerialization( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, "secp384r1", secp384r1PublicFixture_X, secp384r1PublicFixture_Y, secp384r1CompressedFixture); } @Test public void deserializeSecp256() { testDeserialization( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, secp2561CompressedFixture, secp256r1PublicFixture_X, secp256r1PublicFixture_Y); } @Test public void serializeSecp256() throws Exception { testSerialization( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, "secp256r1", secp256r1PublicFixture_X, secp256r1PublicFixture_Y, secp2561CompressedFixture); } @Test(expected = IllegalArgumentException.class) public void testBadPoint() { byte[] bytes = TestUtils.unsignedBytesToSignedBytes(secp384r1CompressedFixture); bytes[20]++; String publicKey = Utils.encodeBase64String(bytes); TrailingSignatureAlgorithm.forCryptoAlgorithm( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384) .deserializePublicKey(publicKey); } private void testSerialization( CryptoAlgorithm algorithm, String curveName, int[] x, int[] y, int[] expected) throws Exception { byte[] xBytes = TestUtils.unsignedBytesToSignedBytes(x); byte[] yBytes = TestUtils.unsignedBytesToSignedBytes(y); final AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); parameters.init(new ECGenParameterSpec(curveName)); ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class); PublicKey publicKey = KeyFactory.getInstance("EC") .generatePublic( new ECPublicKeySpec( new ECPoint(new BigInteger(1, xBytes), new BigInteger(1, yBytes)), ecParameterSpec)); int[] result = TestUtils.signedBytesToUnsignedBytes( Utils.decodeBase64String( TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm) .serializePublicKey(publicKey))); assertArrayEquals(expected, result); } private void testDeserialization( CryptoAlgorithm algorithm, int[] compressedKey, int[] expectedX, int[] expectedY) { byte[] bytes = TestUtils.unsignedBytesToSignedBytes(compressedKey); String publicKey = Utils.encodeBase64String(bytes); PublicKey publicKeyDeserialized = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).deserializePublicKey(publicKey); ECPublicKey desKey = (ECPublicKey) publicKeyDeserialized; BigInteger x = desKey.getW().getAffineX(); BigInteger y = desKey.getW().getAffineY(); BigInteger expectedXBigInteger = new BigInteger(1, TestUtils.unsignedBytesToSignedBytes(expectedX)); BigInteger expectedYBigInteger = new BigInteger(1, TestUtils.unsignedBytesToSignedBytes(expectedY)); assertEquals(expectedXBigInteger, x); assertEquals(expectedYBigInteger, y); } }
5,410
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/CiphertextHeadersTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.model; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.EncryptionContextSerializer; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class CiphertextHeadersTest { final CryptoAlgorithm cryptoAlgo_ = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final String keyProviderId_ = "None"; final byte[] keyProviderInfo_ = "TestKeyID".getBytes(); final byte version_ = cryptoAlgo_.getMessageFormatVersion(); final byte invalidVersion_ = 0x00; final CiphertextType type_ = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA; final int nonceLen_ = cryptoAlgo_.getNonceLen(); final int tagLenBytes_ = cryptoAlgo_.getTagLen(); final ContentType contentType_ = ContentType.FRAME; final int frameSize_ = AwsCrypto.getDefaultFrameSize(); // A set of crypto algs that are representative of the different ciphertext header formats final List<CryptoAlgorithm> testAlgs = Arrays.asList( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256); byte[] encryptedKey_ = RandomBytesGenerator.generate(cryptoAlgo_.getKeyLength()); final KeyBlob keyBlob_ = new KeyBlob(keyProviderId_, keyProviderInfo_, encryptedKey_); byte[] headerNonce_ = RandomBytesGenerator.generate(nonceLen_); byte[] headerTag_ = RandomBytesGenerator.generate(tagLenBytes_); @Test public void serializeDeserialize() { int maxEncryptedDataKeys = 42; Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize(headerBytes, 0, maxEncryptedDataKeys); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertEquals(reconstructedHeaders.getMaxEncryptedDataKeys(), maxEncryptedDataKeys); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } } @Test public void serializeDeserializeDefaultMaxEncryptedDataKeys() { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize(headerBytes, 0); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertEquals( reconstructedHeaders.getMaxEncryptedDataKeys(), CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } } @Test public void serializeDeserializeStreaming() { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); int totalParsedBytes = 0; int bytesToParseLen = 1; int bytesParsed; while (reconstructedHeaders.isComplete() == false) { final byte[] bytesToParse = new byte[bytesToParseLen]; System.arraycopy(headerBytes, totalParsedBytes, bytesToParse, 0, bytesToParse.length); bytesParsed = reconstructedHeaders.deserialize( bytesToParse, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); if (bytesParsed == 0) { bytesToParseLen++; } else { totalParsedBytes += bytesParsed; bytesToParseLen = 1; } } final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } } @Test public void deserializeNull() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); final int deserializedBytes = ciphertextHeaders.deserialize(null, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(0, deserializedBytes); } @Test public void overlyLargeEncryptionContext() { final int size = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] encContextBytes = RandomBytesGenerator.generate(size); for (CryptoAlgorithm alg : testAlgs) { assertThrows(AwsCryptoException.class, () -> createCiphertextHeaders(encContextBytes, alg)); } } @Test public void serializeWithNullHeaderNonce() { for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, alg, new byte[0], Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderTag(headerTag_); assertThrows(AwsCryptoException.class, () -> ciphertextHeaders.toByteArray()); } } @Test public void serializeWithNullHeaderTag() { for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, alg, new byte[0], Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderNonce(headerNonce_); assertThrows(AwsCryptoException.class, () -> ciphertextHeaders.toByteArray()); } } @Test public void serializeWithNullSuiteData() { // Only applicable for V2 algorithms CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, alg, new byte[0], Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderTag(headerTag_); ciphertextHeaders.setHeaderNonce(headerNonce_); assertThrows(AwsCryptoException.class, () -> ciphertextHeaders.toByteArray()); } /* * @Test * public void byteFormatCheck() { * testPlaintextKey_ = ByteFormatCheckValues.getPlaintextKey(); * testKey_ = new SecretKeySpec(testPlaintextKey_, * cryptoAlgo_.getKeySpec()); * encryptedKey_ = ByteFormatCheckValues.getEncryptedKey(); * dataKey_ = new AWSKMSDataKey(testKey_, encryptedKey_); * headerNonce_ = ByteFormatCheckValues.getNonce(); * headerTag_ = ByteFormatCheckValues.getTag(); * * Map<String, String> encryptionContext = new HashMap<String, String>(1); * encryptionContext.put("ENC", "CiphertextHeader format check test"); * * final CiphertextHeaders ciphertextHeaders = * createCiphertextHeaders(encryptionContext); * //NOTE: this test will fail because of the line below. * //That is, the message id is randomly generated in the ciphertext * headers. * messageId_ = ciphertextHeaders.getMessageId(); * final byte[] ciphertextHeaderHash = * TestIOUtils.getSha256Hash(ciphertextHeaders.toByteArray()); * * assertArrayEquals(ByteFormatCheckValues.getCiphertextHeaderHash(), * ciphertextHeaderHash); * } */ private CiphertextHeaders createCiphertextHeaders( final byte[] encryptionContextBytes, CryptoAlgorithm cryptoAlg) { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, cryptoAlg, encryptionContextBytes, Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderNonce(headerNonce_); ciphertextHeaders.setHeaderTag(headerTag_); if (cryptoAlg.getMessageFormatVersion() == 2) { ciphertextHeaders.setSuiteData(new byte[cryptoAlg.getSuiteDataLength()]); } return ciphertextHeaders; } private CiphertextHeaders createCiphertextHeaders( final Map<String, String> encryptionContext, CryptoAlgorithm cryptoAlg) { byte[] encryptionContextBytes = null; if (encryptionContext != null) { encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); } return createCiphertextHeaders(encryptionContextBytes, cryptoAlg); } @SuppressWarnings("deprecation") @Test public void legacyConstructCiphertextHeaders() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( version_, type_, cryptoAlgo_, encryptionContextBytes, Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderNonce(headerNonce_); ciphertextHeaders.setHeaderTag(headerTag_); assertNotNull(ciphertextHeaders); } @SuppressWarnings("deprecation") @Test(expected = IllegalArgumentException.class) public void legacyConstructCiphertextHeadersMismatchedVersion() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( invalidVersion_, type_, cryptoAlgo_, encryptionContextBytes, Collections.singletonList(keyBlob_), contentType_, frameSize_); } @Test public void checkEncContextLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); final int encryptionContextLen = encryptionContextBytes.length; for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize( headerBytes, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(encryptionContextLen, reconstructedHeaders.getEncryptionContextLen()); } } @Test public void checkKeyBlobCount() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize( headerBytes, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(1, reconstructedHeaders.getEncryptedKeyBlobCount()); } } @Test public void checkNullMessageId() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); assertEquals(null, ciphertextHeaders.getMessageId()); } @Test public void checkNullHeaderNonce() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); assertEquals(null, ciphertextHeaders.getHeaderNonce()); } @Test public void checkNullHeaderTag() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); assertEquals(null, ciphertextHeaders.getHeaderTag()); } private void readVersion(final ByteBuffer headerBuff) { headerBuff.get(); } private void readType(final ByteBuffer headerBuff) { readVersion(headerBuff); headerBuff.get(); } private void readToAlgoId(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { // Use the message format version to determine where the algorithm Id is in the // header and how to get to it. if (cryptoAlg.getMessageFormatVersion() == 1) { readType(headerBuff); } else { readVersion(headerBuff); } } private void readAlgoId(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToAlgoId(headerBuff, cryptoAlg); headerBuff.getShort(); } private void readEncContext(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readAlgoId(headerBuff, cryptoAlg); // pull out messageId to get to enc context len. final byte[] msgId = new byte[cryptoAlg.getMessageIdLength()]; headerBuff.get(msgId); // pull out enc context to get to key count. final int encContextLen = headerBuff.getShort(); final byte[] encContext = new byte[encContextLen]; headerBuff.get(encContext); } private void readKeyBlob(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readEncContext(headerBuff, cryptoAlg); headerBuff.getShort(); // get key count final short keyProviderIdLen = headerBuff.getShort(); final byte[] keyProviderId = new byte[keyProviderIdLen]; headerBuff.get(keyProviderId); final short keyProviderInfoLen = headerBuff.getShort(); final byte[] keyProviderInfo = new byte[keyProviderInfoLen]; headerBuff.get(keyProviderInfo); final short keyLen = headerBuff.getShort(); final byte[] key = new byte[keyLen]; headerBuff.get(key); } private void readToContentType(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readKeyBlob(headerBuff, cryptoAlg); } private void readContentType(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToContentType(headerBuff, cryptoAlg); headerBuff.get(); } private void readToReservedField(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readContentType(headerBuff, cryptoAlg); } private void readReservedField(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToReservedField(headerBuff, cryptoAlg); headerBuff.getInt(); } private void readToNonceLen(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readReservedField(headerBuff, cryptoAlg); } private void readNonceLen(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToNonceLen(headerBuff, cryptoAlg); headerBuff.get(); } private void readToFrameLen(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { // Use the message format version to determine where the frame length is in the // header and how to get to it. if (cryptoAlg.getMessageFormatVersion() == 1) { readNonceLen(headerBuff, cryptoAlg); } else { readContentType(headerBuff, cryptoAlg); } } @Test public void invalidVersion() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); // set version to invalid type of 0. headerBuff.put((byte) 0); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid version", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } @Test public void invalidType() { // Only applicable for V1 algorithms final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final CryptoAlgorithm cryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, cryptoAlgorithm); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readVersion(headerBuff); // set type to invalid value of 0. headerBuff.put((byte) 0); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid ciphertext type", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void invalidAlgoId() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToAlgoId(headerBuff, alg); // set algoId to invalid value of 0. headerBuff.putShort((short) 0); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid algorithm identifier in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } @Test public void invalidContentType() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToContentType(headerBuff, alg); // set content type to an invalid value headerBuff.put((byte) 10); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid content type in ciphertext.", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } @Test public void invalidReservedFieldLen() { // Only applicable for V1 algorithms final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final CryptoAlgorithm cryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, cryptoAlgorithm); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToReservedField(headerBuff, cryptoAlgorithm); // set reserved field to an invalid value headerBuff.putInt(-1); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid value for reserved field in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void invalidNonceLen() { // Only applicable for V1 algorithms final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final CryptoAlgorithm cryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, cryptoAlgorithm); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToNonceLen(headerBuff, cryptoAlgorithm); // set nonce len to an invalid value headerBuff.put((byte) -1); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid nonce length in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void invalidFrameLength() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToFrameLen(headerBuff, alg); // set frame len to an invalid value headerBuff.putInt(-1); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid frame length in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } }
5,411
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/EncryptionMaterialsRequestTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.CommitmentPolicy; import org.junit.Test; public class EncryptionMaterialsRequestTest { @Test(expected = IllegalArgumentException.class) public void testConstructWithNullCommitmentPolicy() { EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(null).build(); } @Test(expected = IllegalArgumentException.class) public void testConstructWithoutCommitmentPolicy() { EncryptionMaterialsRequest.newBuilder().build(); } @Test public void testConstructWithCommitmentPolicy() { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); assertNotNull(req); assertEquals(CommitmentPolicy.ForbidEncryptAllowDecrypt, req.getCommitmentPolicy()); } }
5,412
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/DecryptionMaterialsRequestTest.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class DecryptionMaterialsRequestTest { @Test public void build() { CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("DMR", "DecryptionMaterialsRequest Test"); List<KeyBlob> kbs = new ArrayList<KeyBlob>(); DecryptionMaterialsRequest request0 = DecryptionMaterialsRequest.newBuilder() .setAlgorithm(alg) .setEncryptionContext(encryptionContext) .setEncryptedDataKeys(kbs) .build(); DecryptionMaterialsRequest request1 = request0.toBuilder().build(); assertEquals(request0.getAlgorithm(), request1.getAlgorithm()); assertEquals(request0.getEncryptionContext().size(), request1.getEncryptionContext().size()); assertEquals(request0.getEncryptedDataKeys().size(), request1.getEncryptedDataKeys().size()); } }
5,413
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/KeyBlobTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; public class KeyBlobTest { private static CryptoAlgorithm ALGORITHM = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF; final String providerId_ = "Test Key"; final String providerInfo_ = "Test Info"; private StaticMasterKey masterKeyProvider_; @Before public void init() { masterKeyProvider_ = new StaticMasterKey("testmaterial"); } private byte[] createKeyBlobBytes() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey_ = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final KeyBlob keyBlob = new KeyBlob( providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), mockDataKey_.getEncryptedDataKey()); return keyBlob.toByteArray(); } private KeyBlob deserialize(final byte[] keyBlobBytes) { final KeyBlob reconstructedKeyBlob = new KeyBlob(); reconstructedKeyBlob.deserialize(keyBlobBytes, 0); return reconstructedKeyBlob; } @Test public void serializeDeserialize() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); final byte[] reconstructedKeyBlobBytes = reconstructedKeyBlob.toByteArray(); assertArrayEquals(reconstructedKeyBlobBytes, keyBlobBytes); } @Test(expected = AwsCryptoException.class) public void overlyLargeKeyProviderIdLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final int providerId_Len = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] providerId_Bytes = RandomBytesGenerator.generate(providerId_Len); final String providerId_ = new String(providerId_Bytes, StandardCharsets.UTF_8); final String providerInfo_ = "Test Info"; new KeyBlob( providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), mockDataKey.getEncryptedDataKey()); } @Test(expected = AwsCryptoException.class) public void overlyLargeKeyProviderInfoLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final int providerInfo_Len = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] providerInfo_ = RandomBytesGenerator.generate(providerInfo_Len); new KeyBlob(providerId_, providerInfo_, mockDataKey.getEncryptedDataKey()); } @Test(expected = AwsCryptoException.class) public void overlyLargeKey() { final int keyLen = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] encryptedKeyBytes = RandomBytesGenerator.generate(keyLen); new KeyBlob(providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), encryptedKeyBytes); } @Test public void deserializeNull() { final KeyBlob keyBlob = new KeyBlob(); final int deserializedBytes = keyBlob.deserialize(null, 0); assertEquals(0, deserializedBytes); } @Test public void checkKeyProviderIdLen() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertEquals(providerId_.length(), reconstructedKeyBlob.getKeyProviderIdLen()); } @Test public void checkKeyProviderId() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertArrayEquals( providerId_.getBytes(StandardCharsets.UTF_8), reconstructedKeyBlob.getProviderId().getBytes(StandardCharsets.UTF_8)); } @Test public void checkKeyProviderInfoLen() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertEquals(providerInfo_.length(), reconstructedKeyBlob.getKeyProviderInfoLen()); } @Test public void checkKeyProviderInfo() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertArrayEquals( providerInfo_.getBytes(StandardCharsets.UTF_8), reconstructedKeyBlob.getProviderInformation()); } @Test public void checkKeyLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey_ = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final KeyBlob keyBlob = new KeyBlob( providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), mockDataKey_.getEncryptedDataKey()); final byte[] keyBlobBytes = keyBlob.toByteArray(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertEquals( mockDataKey_.getEncryptedDataKey().length, reconstructedKeyBlob.getEncryptedDataKeyLen()); } private KeyBlob generateRandomKeyBlob(int idLen, int infoLen, int keyLen) { final byte[] idBytes = new byte[idLen]; Arrays.fill(idBytes, (byte) 'A'); final byte[] infoBytes = RandomBytesGenerator.generate(infoLen); final byte[] keyBytes = RandomBytesGenerator.generate(keyLen); return new KeyBlob(new String(idBytes, StandardCharsets.UTF_8), infoBytes, keyBytes); } private void assertKeyBlobsEqual(KeyBlob b1, KeyBlob b2) { assertArrayEquals( b1.getProviderId().getBytes(StandardCharsets.UTF_8), b2.getProviderId().getBytes(StandardCharsets.UTF_8)); assertArrayEquals(b1.getProviderInformation(), b2.getProviderInformation()); assertArrayEquals(b1.getEncryptedDataKey(), b2.getEncryptedDataKey()); } @Test public void checkKeyProviderIdLenUnsigned() { // provider id length is too large for a signed short but fits in unsigned final KeyBlob blob = generateRandomKeyBlob(Constants.UNSIGNED_SHORT_MAX_VAL, Short.MAX_VALUE, Short.MAX_VALUE); final byte[] arr = blob.toByteArray(); assertKeyBlobsEqual(deserialize(arr), blob); } @Test public void checkKeyProviderInfoLenUnsigned() { // provider info length is too large for a signed short but fits in unsigned final KeyBlob blob = generateRandomKeyBlob(Short.MAX_VALUE, Constants.UNSIGNED_SHORT_MAX_VAL, Short.MAX_VALUE); final byte[] arr = blob.toByteArray(); assertKeyBlobsEqual(deserialize(arr), blob); } @Test public void checkKeyLenUnsigned() { // key length is too large for a signed short but fits in unsigned final KeyBlob blob = generateRandomKeyBlob(Short.MAX_VALUE, Short.MAX_VALUE, Constants.UNSIGNED_SHORT_MAX_VAL); final byte[] arr = blob.toByteArray(); assertKeyBlobsEqual(deserialize(arr), blob); } }
5,414
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/CipherFrameHeadersTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import java.nio.ByteBuffer; import java.util.Arrays; import org.junit.Test; public class CipherFrameHeadersTest { final int nonceLen_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG.getNonceLen(); final int testSeqNum_ = 1; final int testFrameContentLen_ = 4096; byte[] nonce_ = RandomBytesGenerator.generate(nonceLen_); @Test public void serializeDeserializeTest() { for (boolean includeContentLen : new boolean[] {true, false}) { for (boolean isFinalFrame : new boolean[] {true, false}) { assertTrue(serializeDeserialize(includeContentLen, isFinalFrame)); } } } @Test public void serializeDeserializeStreamingTest() { for (boolean includeContentLen : new boolean[] {true, false}) { for (boolean isFinalFrame : new boolean[] {true, false}) { assertTrue(serializeDeserializeStreaming(includeContentLen, isFinalFrame)); } } } private byte[] createHeaderBytes(final boolean includeContentLen, final boolean isFinalFrame) { final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(testSeqNum_, nonce_, testFrameContentLen_, isFinalFrame); cipherFrameHeaders.includeFrameSize(includeContentLen); return cipherFrameHeaders.toByteArray(); } private CipherFrameHeaders deserialize(final boolean parseContentLen, final byte[] headerBytes) { final CipherFrameHeaders reconstructedHeaders = new CipherFrameHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.includeFrameSize(parseContentLen); reconstructedHeaders.deserialize(headerBytes, 0); return reconstructedHeaders; } private boolean serializeDeserialize( final boolean includeContentLen, final boolean isFinalFrame) { final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final CipherFrameHeaders reconstructedHeaders = deserialize(includeContentLen, headerBytes); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); return Arrays.equals(headerBytes, reconstructedHeaderBytes) ? true : false; } private boolean serializeDeserializeStreaming( final boolean includeContentLen, final boolean isFinalFrame) { final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final CipherFrameHeaders reconstructedHeaders = new CipherFrameHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.includeFrameSize(includeContentLen); int totalParsedBytes = 0; int bytesToParseLen = 1; int bytesParsed; while (reconstructedHeaders.isComplete() == false) { final byte[] bytesToParse = new byte[bytesToParseLen]; System.arraycopy(headerBytes, totalParsedBytes, bytesToParse, 0, bytesToParse.length); bytesParsed = reconstructedHeaders.deserialize(bytesToParse, 0); if (bytesParsed == 0) { bytesToParseLen++; } else { totalParsedBytes += bytesParsed; bytesToParseLen = 1; } } final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); return Arrays.equals(headerBytes, reconstructedHeaderBytes) ? true : false; } @Test public void deserializeNull() { final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(); final int deserializedBytes = cipherFrameHeaders.deserialize(null, 0); assertEquals(0, deserializedBytes); } @Test public void checkNullNonce() { final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(); cipherFrameHeaders.setNonceLength((short) nonceLen_); assertEquals(null, cipherFrameHeaders.getNonce()); } @Test public void checkNonce() { final byte[] headerBytes = createHeaderBytes(false, false); final CipherFrameHeaders reconstructedHeaders = deserialize(false, headerBytes); assertArrayEquals(nonce_, reconstructedHeaders.getNonce()); } @Test public void checkSeqNum() { final byte[] headerBytes = createHeaderBytes(false, false); final CipherFrameHeaders reconstructedHeaders = deserialize(false, headerBytes); assertEquals(testSeqNum_, reconstructedHeaders.getSequenceNumber()); } @Test public void checkFrameLen() { final boolean isFinalFrame = false; final boolean includeContentLen = true; final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final CipherFrameHeaders reconstructedHeaders = deserialize(includeContentLen, headerBytes); assertEquals(testFrameContentLen_, reconstructedHeaders.getFrameContentLength()); } @Test(expected = BadCiphertextException.class) public void invalidFrameLen() { final boolean isFinalFrame = false; final boolean includeContentLen = true; final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); // Pull out seq num to move to nonce headerBuff.getInt(); // Pull out nonce to move to content len final byte[] nonce = new byte[nonceLen_]; headerBuff.get(nonce); // Set content length (of type long) to -1; headerBuff.putInt(-1); final CipherFrameHeaders reconstructedHeaders = new CipherFrameHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.includeFrameSize(includeContentLen); reconstructedHeaders.deserialize(headerBuff.array(), 0); } @Test(expected = AwsCryptoException.class) public void nullNonce() { boolean isFinalFrame = false; new CipherFrameHeaders(testSeqNum_, null, testFrameContentLen_, isFinalFrame); } @Test(expected = AwsCryptoException.class) public void invalidNonce() { boolean isFinalFrame = false; new CipherFrameHeaders( testSeqNum_, new byte[Constants.MAX_NONCE_LENGTH + 1], testFrameContentLen_, isFinalFrame); } @Test public void byteFormatCheck() { boolean isFinalFrame = false; nonce_ = ByteFormatCheckValues.getNonce(); final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(testSeqNum_, nonce_, testFrameContentLen_, isFinalFrame); final byte[] cipherFrameHeaderHash = TestIOUtils.getSha256Hash(cipherFrameHeaders.toByteArray()); assertArrayEquals(ByteFormatCheckValues.getCipherFrameHeaderHash(), cipherFrameHeaderHash); } @Test public void byteFormatCheckforFinalFrame() { boolean isFinalFrame = true; nonce_ = ByteFormatCheckValues.getNonce(); final CipherFrameHeaders cipherFinalFrameHeaders = new CipherFrameHeaders(testSeqNum_, nonce_, testFrameContentLen_, isFinalFrame); final byte[] cipherFinalFrameHeaderHash = TestIOUtils.getSha256Hash(cipherFinalFrameHeaders.toByteArray()); assertArrayEquals( ByteFormatCheckValues.getCipherFinalFrameHeaderHash(), cipherFinalFrameHeaderHash); } }
5,415
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/CipherBlockHeadersTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import java.nio.ByteBuffer; import java.util.Arrays; import org.junit.Test; public class CipherBlockHeadersTest { final int nonceLen_ = 12; byte[] nonce_ = RandomBytesGenerator.generate(nonceLen_); final int sampleContentLen_ = 1024; @Test public void serializeDeserialize() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBytes, 0); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } private boolean serializeDeserializeStreaming(final boolean isFinalFrame) { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); int totalParsedBytes = 0; int bytesToParseLen = 1; int bytesParsed; while (reconstructedHeaders.isComplete() == false) { final byte[] bytesToParse = new byte[bytesToParseLen]; System.arraycopy(headerBytes, totalParsedBytes, bytesToParse, 0, bytesToParse.length); bytesParsed = reconstructedHeaders.deserialize(bytesToParse, 0); if (bytesParsed == 0) { bytesToParseLen++; } else { totalParsedBytes += bytesParsed; bytesToParseLen = 1; } } final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); return Arrays.equals(headerBytes, reconstructedHeaderBytes) ? true : false; } @Test public void serializeDeserializeStreamingFinalFrame() { assertTrue(serializeDeserializeStreaming(true)); } @Test public void deserializeNull() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(); final int deserializedBytes = cipherBlockHeaders.deserialize(null, 0); assertEquals(0, deserializedBytes); } @Test public void checkContentLen() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBytes, 0); assertEquals(sampleContentLen_, reconstructedHeaders.getContentLength()); } @Test public void checkNonce() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBytes, 0); assertArrayEquals(nonce_, reconstructedHeaders.getNonce()); } @Test public void checkNullNonce() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(); cipherBlockHeaders.setNonceLength((short) nonceLen_); assertArrayEquals(null, cipherBlockHeaders.getNonce()); } @Test(expected = AwsCryptoException.class) public void nullNonce() { new CipherBlockHeaders(null, sampleContentLen_); } @Test(expected = AwsCryptoException.class) public void invalidNonce() { new CipherBlockHeaders(new byte[Constants.MAX_NONCE_LENGTH + 1], sampleContentLen_); } @Test(expected = BadCiphertextException.class) public void invalidContentLen() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); // Pull out nonce to move to content len final byte[] nonce = new byte[nonceLen_]; headerBuff.get(nonce); // Set content length (of type long) to -1; headerBuff.putLong(-1); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBuff.array(), 0); } @Test public void byteFormatCheck() { nonce_ = ByteFormatCheckValues.getNonce(); final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] cipherBlockHeaderHash = TestIOUtils.getSha256Hash(cipherBlockHeaders.toByteArray()); assertArrayEquals(ByteFormatCheckValues.getCipherBlockHeaderHash(), cipherBlockHeaderHash); } }
5,416
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/ByteFormatCheckValues.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.internal.Utils; public class ByteFormatCheckValues { private static final String base64MessageId_ = "NQ/NXvg4mMN5zm5JFZHUWw=="; private static final String base64PlaintextKey_ = "N9vW5Ox5xh4BrUgeaL2gXg=="; private static final String base64EncryptedKey_ = "Zg5VUzPfgD0/H92Fx7h0ew=="; private static final String base64Nonce_ = "3rktZhNbwrZBSaqt"; private static final String base64Tag_ = "cBPLjSEz0fsWDToxTqMvfQ=="; private static final String base64CiphertextHeaderHash_ = "bCScP4wa25l9TLQZ4KLv7xqVCg9AN58lB1FHrl2yVes="; private static final String base64BlockHeaderHash_ = "7q8fULz95XaJqrksEuzDoVpSYih54QbPC1+v833s/5Y="; private static final String base64FrameHeaderHash_ = "tB/UmW+/hLJU5i2D9Or8guXrn8lP0uCiUaP1KkdyKGs="; private static final String base64FinalFrameHeaderHash_ = "/b2fVFOxvnaM5vXDMGyyFPNTWMjuU/c/48qeH3uTHj0="; public static byte[] getMessageId() { return Utils.decodeBase64String(base64MessageId_); } public static byte[] getEncryptedKey() { return Utils.decodeBase64String(base64EncryptedKey_); } public static byte[] getPlaintextKey() { return Utils.decodeBase64String(base64PlaintextKey_); } public static byte[] getCiphertextHeaderHash() { return Utils.decodeBase64String(base64CiphertextHeaderHash_); } public static byte[] getCipherBlockHeaderHash() { return Utils.decodeBase64String(base64BlockHeaderHash_); } public static byte[] getCipherFrameHeaderHash() { return Utils.decodeBase64String(base64FrameHeaderHash_); } public static byte[] getCipherFinalFrameHeaderHash() { return Utils.decodeBase64String(base64FinalFrameHeaderHash_); } public static byte[] getNonce() { return Utils.decodeBase64String(base64Nonce_); } public static byte[] getTag() { return Utils.decodeBase64String(base64Tag_); } }
5,417
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/LocalCryptoMaterialsCacheTest.java
package com.amazonaws.encryptionsdk.caching; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.UsageStats; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class LocalCryptoMaterialsCacheTest { public static final String PARTTION_NAME = "foo"; FakeClock clock; LocalCryptoMaterialsCache cache; CryptoMaterialsCache.CacheHint hint = () -> 1000; // maxAge = 1000 @Before public void setUp() { clock = new FakeClock(); cache = new LocalCryptoMaterialsCache(5); cache.clock = clock; } @Test public void whenNoEntriesInCache_noEntriesReturned() { assertNull(cache.getEntryForDecrypt(new byte[10])); byte[] cacheId = new byte[10]; assertNull(cache.getEntryForEncrypt(cacheId, UsageStats.ZERO)); } @Test public void whenEntriesAddedToDecryptCache_correctEntriesReturned() { DecryptionMaterials result1 = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(1)); DecryptionMaterials result2 = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(2)); cache.putEntryForDecrypt(new byte[] {1}, result1, hint); cache.putEntryForDecrypt(new byte[] {2}, result2, hint); assertEquals(result2, cache.getEntryForDecrypt(new byte[] {2}).getResult()); assertEquals(result1, cache.getEntryForDecrypt(new byte[] {1}).getResult()); } @Test public void whenManyDecryptEntriesAdded_LRURespected() { DecryptionMaterials[] results = new DecryptionMaterials[6]; for (int i = 0; i < results.length; i++) { results[i] = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(i)); } cache.putEntryForDecrypt(new byte[] {0}, results[0], hint); cache.putEntryForDecrypt(new byte[] {1}, results[1], hint); cache.putEntryForDecrypt(new byte[] {2}, results[2], hint); cache.putEntryForDecrypt(new byte[] {3}, results[3], hint); cache.putEntryForDecrypt(new byte[] {4}, results[4], hint); // make entry 0 most recently used assertEquals(results[0], cache.getEntryForDecrypt(new byte[] {0}).getResult()); // entry 1 is evicted cache.putEntryForDecrypt(new byte[] {5}, results[5], hint); for (int i = 0; i < results.length; i++) { DecryptionMaterials actualResult = Optional.ofNullable(cache.getEntryForDecrypt(new byte[] {(byte) i})) .map(CryptoMaterialsCache.DecryptCacheEntry::getResult) .orElse(null); DecryptionMaterials expected = (i == 1) ? null : results[i]; assertEquals("index " + i, expected, actualResult); } } @Test public void whenEncryptEntriesAdded_theyCanBeRetrieved() { EncryptionMaterials result1a = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); EncryptionMaterials result1b = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); EncryptionMaterials result2 = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(1)); cache.putEntryForEncrypt(new byte[] {0}, result1a, hint, UsageStats.ZERO); cache.putEntryForEncrypt(new byte[] {0}, result1b, hint, UsageStats.ZERO); cache.putEntryForEncrypt(new byte[] {1}, result2, hint, UsageStats.ZERO); assertEncryptEntry(new byte[] {0}, result1b); assertEncryptEntry(new byte[] {1}, result2); } @Test public void whenInitialUsagePassed_itIsRetained() { UsageStats stats = new UsageStats(123, 456); EncryptionMaterials result1a = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {0}, result1a, hint, stats); assertEquals(stats, cache.getEntryForEncrypt(new byte[] {0}, UsageStats.ZERO).getUsageStats()); } @Test public void whenManyEncryptEntriesAdded_LRUIsRespected() { EncryptionMaterials[] results = new EncryptionMaterials[6]; for (int i = 0; i < results.length; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(i / 3)); cache.putEntryForEncrypt(new byte[] {(byte) (i)}, results[i], hint, UsageStats.ZERO); } for (int i = 0; i < results.length; i++) { EncryptionMaterials expected = i == 0 ? null : results[i]; assertEncryptEntry(new byte[] {(byte) i}, expected); } } @Test public void whenManyEncryptEntriesAdded_andEntriesTouched_LRUIsRespected() { EncryptionMaterials[] results = new EncryptionMaterials[6]; for (int i = 0; i < 3; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } cache.getEntryForEncrypt(new byte[] {0}, UsageStats.ZERO); for (int i = 3; i < 6; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } assertEncryptEntry(new byte[] {0}, results[0]); assertEncryptEntry(new byte[] {1}, null); assertEncryptEntry(new byte[] {2}, results[2]); assertEncryptEntry(new byte[] {3}, results[3]); assertEncryptEntry(new byte[] {4}, results[4]); assertEncryptEntry(new byte[] {5}, results[5]); } @Test public void whenManyEncryptEntriesAdded_andEntryInvalidated_LRUIsRespected() { EncryptionMaterials[] results = new EncryptionMaterials[6]; for (int i = 0; i < 3; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } cache.getEntryForEncrypt(new byte[] {2}, UsageStats.ZERO).invalidate(); for (int i = 3; i < 6; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } assertEncryptEntry(new byte[] {0}, results[0]); assertEncryptEntry(new byte[] {1}, results[1]); assertEncryptEntry(new byte[] {2}, null); assertEncryptEntry(new byte[] {3}, results[3]); assertEncryptEntry(new byte[] {4}, results[4]); assertEncryptEntry(new byte[] {5}, results[5]); } @Test public void testCacheEntryBehavior() { EncryptionMaterials result = createResult(); CryptoMaterialsCache.EncryptCacheEntry e = cache.putEntryForEncrypt(new byte[] {0}, result, hint, new UsageStats(1, 2)); assertEquals(clock.now, e.getEntryCreationTime()); assertEquals(new UsageStats(1, 2), e.getUsageStats()); CryptoMaterialsCache.EncryptCacheEntry e2 = cache.getEntryForEncrypt(new byte[] {0}, new UsageStats(200, 100)); // Old entry usage is unchanged assertEquals(new UsageStats(1, 2), e.getUsageStats()); assertEquals(new UsageStats(201, 102), e2.getUsageStats()); e2.invalidate(); // All EncryptCacheEntry methods should still work after invalidation Assert.assertEquals(result, e2.getResult()); assertEquals(new UsageStats(201, 102), e2.getUsageStats()); } @Test public void whenTTLExceeded_encryptEntriesAreEvicted() throws Exception { EncryptionMaterials result = createResult(); cache.putEntryForEncrypt(new byte[] {0}, result, () -> 500, UsageStats.ZERO); clock.now += 500; assertEncryptEntry(new byte[] {0}, result); clock.now += 1; assertEncryptEntry(new byte[] {0}, null); // Verify that the cache isn't hanging on to memory once it notices the entry is expired assertEquals(0, getCacheMap(cache).size()); } @Test public void whenManyEntriesExpireAtOnce_expiredEncryptEntriesStillNotReturned() { // Our active TTL expiration logic will only remove a certain number of entries per call, make // sure that even // if we bail out before removing a particular entry, it's still filtered from the return value. cache = new LocalCryptoMaterialsCache(200); cache.clock = clock; for (int i = 0; i < 100; i++) { cache.putEntryForEncrypt(new byte[] {(byte) i}, createResult(), () -> 500, UsageStats.ZERO); } cache.putEntryForEncrypt(new byte[] {(byte) 0xFF}, createResult(), () -> 501, UsageStats.ZERO); clock.now += 502; assertEncryptEntry(new byte[] {(byte) 0xFF}, null); } @Test public void whenAccessed_encryptEntryTTLNotReset() { EncryptionMaterials result = createResult(); cache.putEntryForEncrypt(new byte[] {0}, result, hint, UsageStats.ZERO); clock.now += 1000; assertEncryptEntry(new byte[] {0}, result); clock.now += 1; assertEncryptEntry(new byte[] {0}, null); } @Test public void whenTTLExceeded_decryptEntriesAreEvicted() throws Exception { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); clock.now += 1001; assertNull(cache.getEntryForDecrypt(new byte[] {0})); // Verify that the cache isn't hanging on to memory once it notices the entry is expired assertEquals(0, getCacheMap(cache).size()); } @Test public void whenAccessed_decryptEntryTTLNotReset() { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); clock.now += 500; assertNotNull(cache.getEntryForDecrypt(new byte[] {0})); clock.now += 501; assertNull(cache.getEntryForDecrypt(new byte[] {0})); } @Test public void whenManyEntriesExpireAtOnce_expiredDecryptEntriesStillNotReturned() { cache = new LocalCryptoMaterialsCache(200); cache.clock = clock; for (int i = 0; i < 100; i++) { cache.putEntryForEncrypt( new byte[] {(byte) (i + 1)}, createResult(), () -> 500, UsageStats.ZERO); } DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, () -> 501); // our encrypt entries will expire first clock.now += 502; assertNull(cache.getEntryForDecrypt(new byte[] {0})); } @Test public void testDecryptInvalidate() { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); cache.getEntryForDecrypt(new byte[] {0}).invalidate(); assertNull(cache.getEntryForDecrypt(new byte[] {0})); } @Test public void testDecryptEntryCreationTime() { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); assertEquals( clock.timestamp(), cache.getEntryForDecrypt(new byte[] {0}).getEntryCreationTime()); } @Test public void whenIdentifiersDifferInLowOrderBytes_theyAreNotConsideredEquivalent() throws Exception { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[128], result, hint); for (int i = 0; i < 128; i++) { byte[] otherIdentifier = new byte[128]; otherIdentifier[i]++; assertNull(cache.getEntryForDecrypt(otherIdentifier)); } } @Test public void testUsageStatsCtorValidation() { assertThrows(() -> new UsageStats(1, -1)); assertThrows(() -> new UsageStats(-1, 1)); } private EncryptionMaterials createResult() { return CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); } private void assertEncryptEntry(byte[] cacheId, EncryptionMaterials expectedResult) { CryptoMaterialsCache.EncryptCacheEntry entry = cache.getEntryForEncrypt(cacheId, UsageStats.ZERO); EncryptionMaterials actual = entry == null ? null : entry.getResult(); assertEquals(expectedResult, actual); } private Map getCacheMap(LocalCryptoMaterialsCache cache) throws Exception { Field field = LocalCryptoMaterialsCache.class.getDeclaredField("cacheMap"); field.setAccessible(true); return (Map) field.get(cache); } private static final class FakeClock implements MsClock { long now = 0x1_0000_0000L; @Override public long timestamp() { return now; } } }
5,418
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/CacheIdentifierTests.java
package com.amazonaws.encryptionsdk.caching; import static com.amazonaws.encryptionsdk.CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256; import static com.amazonaws.encryptionsdk.CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; public class CacheIdentifierTests { static String partitionName = "c15b9079-6d0e-42b6-8784-5e804b025692"; static Map<String, String> contextEmpty = Collections.emptyMap(); static Map<String, String> contextFull; static CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; static { contextFull = new HashMap<>(); contextFull.put("this", "is"); contextFull.put("a", "non-empty"); contextFull.put("encryption", "context"); } static List<KeyBlob> keyBlobs = Arrays.asList( new KeyBlob( "this is a provider ID", "this is some key info".getBytes(UTF_8), "super secret key, now with encryption!".getBytes(UTF_8)), new KeyBlob( "another provider ID!", "this is some different key info".getBytes(UTF_8), "better super secret key, now with encryption!".getBytes(UTF_8))); @Test public void pythonTestVecs() throws Exception { assertEncryptId( partitionName, null, contextEmpty, "rkrFAso1YyPbOJbmwVMjrPw+wwLJT7xusn8tA8zMe9e3+OqbtfDueB7bvoKLU3fsmdUvZ6eMt7mBp1ThMMB25Q=="); assertEncryptId( partitionName, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, contextEmpty, "3icBIkLK4V3fVwbm3zSxUdUQV6ZvZYUOLl8buN36g6gDMqAkghcGryxX7QiVABkW1JhB6GRp5z+bzbiuciBcKQ=="); assertEncryptId( partitionName, null, contextFull, "IHiUHYOUVUEFTc3BcZPJDlsWct2Qy1A7JdfQl9sQoV/ILIbRpoz9q7RtGd/MlibaGl5ihE66cN8ygM8A5rtYbg=="); assertEncryptId( partitionName, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, contextFull, "mRNK7qhTb/kJiiyGPgAevp0gwFRcET4KeeNYwZHhoEDvSUzQiDgl8Of+YRDaVzKxAqpNBgcAuFXde9JlaRRsmw=="); assertDecryptId( partitionName, ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256, Collections.singletonList(keyBlobs.get(0)), contextEmpty, "n0zVzk9QIVxhz6ET+aJIKKOJNxtpGtSe1yAbu7WU5l272Iw/jmhlER4psDHJs9Mr8KYiIvLGSXzggNDCc23+9w=="); assertDecryptId( partitionName, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, keyBlobs, contextFull, "+rtwUe38CGnczGmYu12iqGWHIyDyZ44EvYQ4S6ACmsgS8VaEpiw0RTGpDk6Z/7YYN/jVHOAcNKDyCNP8EmstFg=="); } void assertDecryptId( String partitionName, CryptoAlgorithm algo, List<KeyBlob> blobs, Map<String, String> context, String expect) throws Exception { DecryptionMaterialsRequest request = DecryptionMaterialsRequest.newBuilder() .setAlgorithm(algo) .setEncryptionContext(context) .setEncryptedDataKeys(blobs) .build(); byte[] id = getCacheIdentifier(getCMM(partitionName), request); assertEquals(expect, Utils.encodeBase64String(id)); } void assertEncryptId( String partitionName, CryptoAlgorithm algo, Map<String, String> context, String expect) throws Exception { EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setContext(context) .setRequestedAlgorithm(algo) .setCommitmentPolicy(commitmentPolicy) .build(); byte[] id = getCacheIdentifier(getCMM(partitionName), request); assertEquals(expect, Utils.encodeBase64String(id)); } @Test public void encryptDigestTestVector() throws Exception { HashMap<String, String> contextMap = new HashMap<>(); contextMap.put("\0\0TEST", "\0\0test"); // Note! This key is actually U+10000, but java treats it as a UTF-16 surrogate pair. // UTF-8 encoding should be 0xF0 0x90 0x80 0x80 contextMap.put("\uD800\uDC00", "UTF-16 surrogate"); contextMap.put("\uABCD", "\\uABCD"); byte[] id = getCacheIdentifier( getCMM("partition ID"), EncryptionMaterialsRequest.newBuilder() .setContext(contextMap) .setRequestedAlgorithm(null) .setCommitmentPolicy(commitmentPolicy) .build()); assertEquals( "683328d033fc60a20e3d3936190b33d91aad0143163226af9530e7d1b3de0e96" + "39c00a2885f9cea09cf9a273bef316a39616475b50adc2441b69f67e1a25145f", new String(Hex.encode(id))); id = getCacheIdentifier( getCMM("partition ID"), EncryptionMaterialsRequest.newBuilder() .setContext(contextMap) .setRequestedAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256) .setCommitmentPolicy(commitmentPolicy) .build()); assertEquals( "3dc70ff1d4621059b97179563ab6592dff4319bfaf8ed1a819c96d33d3194d5c" + "354a361e879d0356e4d9e868170ebc9e934fa5eaf6e6d11de4ee801645723fa9", new String(Hex.encode(id))); } @Test public void decryptDigestTestVector() throws Exception { HashMap<String, String> contextMap = new HashMap<>(); contextMap.put("\0\0TEST", "\0\0test"); // Note! This key is actually U+10000, but java treats it as a UTF-16 surrogate pair. // UTF-8 encoding should be 0xF0 0x90 0x80 0x80 contextMap.put("\uD800\uDC00", "UTF-16 surrogate"); contextMap.put("\uABCD", "\\uABCD"); ArrayList<KeyBlob> keyBlobs = new ArrayList<>(); keyBlobs.addAll( Arrays.asList( new KeyBlob("", new byte[] {}, new byte[] {}), // always first new KeyBlob("\0", new byte[] {0}, new byte[] {0}), new KeyBlob("\u0081", new byte[] {(byte) 0x81}, new byte[] {(byte) 0x81}), new KeyBlob("abc", Hex.decode("deadbeef"), Hex.decode("bad0cafe")))); assertEquals( "e16344634350fe8cb51e69ec4e0681c84ac7ef2df427bd4de4aefbebcd3ead22" + "95f1b15a98ce60699e0efbf69dbbc12e2552b16eff84a6e9b5766ee4d69a7897", new String( Hex.encode( getCacheIdentifier( getCMM("partition ID"), DecryptionMaterialsRequest.newBuilder() .setAlgorithm( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256) .setEncryptionContext(contextMap) .setEncryptedDataKeys(keyBlobs) .build())))); } private byte[] getCacheIdentifier( CachingCryptoMaterialsManager cmm, EncryptionMaterialsRequest request) throws Exception { Method m = CachingCryptoMaterialsManager.class.getDeclaredMethod( "getCacheIdentifier", EncryptionMaterialsRequest.class); m.setAccessible(true); return (byte[]) m.invoke(cmm, request); } private byte[] getCacheIdentifier( CachingCryptoMaterialsManager cmm, DecryptionMaterialsRequest request) throws Exception { Method m = CachingCryptoMaterialsManager.class.getDeclaredMethod( "getCacheIdentifier", DecryptionMaterialsRequest.class); m.setAccessible(true); return (byte[]) m.invoke(cmm, request); } private CachingCryptoMaterialsManager getCMM(final String partitionName) { return CachingCryptoMaterialsManager.newBuilder() .withCache(mock(CryptoMaterialsCache.class)) .withBackingMaterialsManager(mock(CryptoMaterialsManager.class)) .withMaxAge(1, TimeUnit.MILLISECONDS) .withPartitionId(partitionName) .build(); } }
5,419
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/CacheTestFixtures.java
package com.amazonaws.encryptionsdk.caching; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Collections; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class CacheTestFixtures { private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private static final MasterKey<?> FIXED_KEY = JceMasterKey.getInstance( new SecretKeySpec(TestUtils.insecureRandomBytes(16), "AES"), "prov", "keyid", "AES/GCM/NoPadding"); public static EncryptionMaterialsRequest createMaterialsRequest(int index) { return EncryptionMaterialsRequest.newBuilder() .setContext(Collections.singletonMap("index", Integer.toString(index))) .setCommitmentPolicy(commitmentPolicy) .build(); } public static EncryptionMaterials createMaterialsResult(EncryptionMaterialsRequest request) { return new DefaultCryptoMaterialsManager(FIXED_KEY) .getMaterialsForEncrypt(request).toBuilder().setCleartextDataKey(new SentinelKey()).build(); } public static DecryptionMaterialsRequest createDecryptRequest(int index) { EncryptionMaterialsRequest mreq = createMaterialsRequest(index); EncryptionMaterials mres = createMaterialsResult(mreq); return createDecryptRequest(mres); } public static DecryptionMaterialsRequest createDecryptRequest(EncryptionMaterials mres) { return DecryptionMaterialsRequest.newBuilder() .setAlgorithm(mres.getAlgorithm()) .setEncryptionContext(mres.getEncryptionContext()) .setEncryptedDataKeys(mres.getEncryptedDataKeys()) .build(); } public static DecryptionMaterials createDecryptResult(DecryptionMaterialsRequest request) { DecryptionMaterials realResult = new DefaultCryptoMaterialsManager(FIXED_KEY).decryptMaterials(request); return realResult.toBuilder() .setDataKey( new DataKey( new SentinelKey(), realResult.getDataKey().getEncryptedDataKey(), realResult.getDataKey().getProviderInformation(), realResult.getDataKey().getMasterKey())) .build(); } static EncryptionMaterials createMaterialsResult() { return createMaterialsResult(createMaterialsRequest(0)); } // These SentinelKeys let us detect when a particular DecryptionMaterials or EncryptionMaterials // is being used, without // being concerned about matching all of the fields - we can just use object identity. public static class SentinelKey implements SecretKey { @Override public String getAlgorithm() { return "AES"; } @Override public String getFormat() { return "RAW"; } @Override public byte[] getEncoded() { return null; } } }
5,420
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/NullCryptoMaterialsCacheTest.java
package com.amazonaws.encryptionsdk.caching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import org.junit.Test; public class NullCryptoMaterialsCacheTest { @Test public void testEncryptPath() { NullCryptoMaterialsCache cache = new NullCryptoMaterialsCache(); EncryptionMaterialsRequest req = CacheTestFixtures.createMaterialsRequest(1); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(req); CryptoMaterialsCache.UsageStats stats = new CryptoMaterialsCache.UsageStats(123, 456); CryptoMaterialsCache.EncryptCacheEntry entry = cache.putEntryForEncrypt(new byte[1], result, () -> Long.MAX_VALUE, stats); assertEquals(result, entry.getResult()); assertFalse(entry.getEntryCreationTime() > System.currentTimeMillis()); assertEquals(stats, entry.getUsageStats()); ; // the entry should not be in the "cache" byte[] cacheId = new byte[1]; assertNull(cache.getEntryForEncrypt(cacheId, CryptoMaterialsCache.UsageStats.ZERO)); entry.invalidate(); // shouldn't throw } @Test public void testDecryptPath() { NullCryptoMaterialsCache cache = new NullCryptoMaterialsCache(); DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(1); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); assertNull(cache.getEntryForDecrypt(new byte[1])); cache.putEntryForDecrypt(new byte[1], result, () -> Long.MAX_VALUE); assertNull(cache.getEntryForDecrypt(new byte[1])); } }
5,421
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/LocalCryptoMaterialsCacheThreadStormTest.java
package com.amazonaws.encryptionsdk.caching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.UsageStats; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.function.Supplier; import org.junit.Test; public class LocalCryptoMaterialsCacheThreadStormTest { /* * This test tests the behavior of LocalCryptoMaterialsCache under contention at the cache level. * We specifically test: * * 1. Gets and puts of encrypt and decrypt entries, including entries under the same cache ID for encrypt * 2. Invalidations * 3. Changes to cache capacity * * Periodically, we verify that the system state is sane. This is done by inspecting the private members of * LocalCryptoMaterialsCache and verifying that all cache entries are in the LRU map. */ // Private member accessors private static final Function<LocalCryptoMaterialsCache, HashMap<?, ?>> get_cacheMap; private static final Function<LocalCryptoMaterialsCache, TreeSet<?>> get_expirationQueue; private static <T, R> Function<T, R> getGetter(Class<T> klass, String fieldName) { try { Field f = klass.getDeclaredField(fieldName); f.setAccessible(true); return obj -> { try { return (R) f.get(obj); } catch (Exception e) { throw new RuntimeException(e); } }; } catch (Exception e) { throw new Error(e); } } static { get_cacheMap = getGetter(LocalCryptoMaterialsCache.class, "cacheMap"); get_expirationQueue = getGetter(LocalCryptoMaterialsCache.class, "expirationQueue"); } public static void assertConsistent(LocalCryptoMaterialsCache cache) { synchronized (cache) { HashSet<Object> expirationQueue = new HashSet<>(get_expirationQueue.apply(cache)); HashSet<Object> cacheMap = new HashSet<>(get_cacheMap.apply(cache).values()); assertEquals( "Cache group entries are inconsistent with expiration queue", cacheMap, expirationQueue); } } LocalCryptoMaterialsCache cache; // When barrier request = true, all worker threads will join the barrier twice. CyclicBarrier barrier; volatile boolean barrierRequest = false; CountDownLatch stopRequest = new CountDownLatch(1); // Decrypt results that _might_ be returned. Note that due to race conditions in the test itself, // we might be // missing valid cached values here; if a result is in neither forbiddenKeys nor possibleDecrypts, // then we must // assume that it's allowed to be returned. ConcurrentHashMap<ByteBuffer, ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object>> possibleDecrypts = new ConcurrentHashMap<>(); // The values of the inner map are arbitrary but non-null (we use this effectively like a set) ConcurrentHashMap<ByteBuffer, ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object>> possibleEncrypts = new ConcurrentHashMap<>(); // Counters for debugging the test itself. If null, this debug infrastructure is disabled. private ConcurrentHashMap<String, AtomicLong> counters = null; // new ConcurrentHashMap<>(); void inc(String s) { if (counters != null) { counters.computeIfAbsent(s, ignored -> new AtomicLong(0)).incrementAndGet(); } } private static final EncryptionMaterials BASE_ENCRYPT = CacheTestFixtures.createMaterialsResult(); private static final DecryptionMaterials BASE_DECRYPT = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); private void maybeBarrier() { if (barrierRequest) { try { barrier.await(); barrier.await(); } catch (Exception e) { throw new RuntimeException(e); } } } // This thread continually adds items to the decrypt cache, logging ones it added. // The expectedDecryptMap has multiple items because we don't know if the cache expired the prior // one; the // decrypt check thread will check and forget/forbid the expected items that were not found. public void decryptAddThread() { int nItemsBeforeRelax = 200_000; int nItems = 0; try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[3]; ThreadLocalRandom.current().nextBytes(ref); ref[0] = 0; CacheTestFixtures.SentinelKey key = new CacheTestFixtures.SentinelKey(); DecryptionMaterials result = BASE_DECRYPT.toBuilder() .setDataKey( new DataKey( key, new byte[0], new byte[0], BASE_DECRYPT.getDataKey().getMasterKey())) .build(); ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> expectedDecryptMap = possibleDecrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (expectedDecryptMap) { cache.putEntryForDecrypt(ref, result, () -> Long.MAX_VALUE); expectedDecryptMap.put(key, this); } inc("decrypt put"); if (++nItems >= nItemsBeforeRelax) { Thread.sleep(5); nItems = 0; } } } catch (Exception e) { throw new RuntimeException(e); } } // The decrypt check thread verifies that the decrypt results are sane - specifically, if we don't // see an item // that is known to have once been added to the cache, we should not see it reappear later. public void decryptCheckThread() { try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[3]; ThreadLocalRandom.current().nextBytes(ref); ref[0] = 0; ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> expectedDecryptMap = possibleDecrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (expectedDecryptMap) { CryptoMaterialsCache.DecryptCacheEntry result = cache.getEntryForDecrypt(ref); CacheTestFixtures.SentinelKey cachedKey = null; if (result != null) { inc("decrypt: hit"); cachedKey = (CacheTestFixtures.SentinelKey) result.getResult().getDataKey().getKey(); if (expectedDecryptMap.containsKey(cachedKey)) { inc("decrypt: found key in expected"); } else { fail("decrypt: unexpected key"); } } else { inc("decrypt: miss"); } for (CacheTestFixtures.SentinelKey expectedKey : expectedDecryptMap.keySet()) { if (cachedKey != expectedKey) { inc("decrypt: prune"); expectedDecryptMap.remove(expectedKey); } } } } } catch (Exception e) { throw new RuntimeException(e); } } // Continually adds encryption cache entries. public void encryptAddThread() { int nItemsBeforeRelax = 200_000; int nItems = 0; try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[2]; ThreadLocalRandom.current().nextBytes(ref); EncryptionMaterials result = BASE_ENCRYPT.toBuilder() .setCleartextDataKey(new CacheTestFixtures.SentinelKey()) .build(); ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> keys = possibleEncrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (keys) { inc("encrypt: add"); cache.putEntryForEncrypt(ref, result, () -> Long.MAX_VALUE, UsageStats.ZERO); keys.put((CacheTestFixtures.SentinelKey) result.getCleartextDataKey(), this); } if (++nItems >= nItemsBeforeRelax) { Thread.sleep(5); nItems = 0; } } } catch (Exception e) { throw new RuntimeException(e); } } // Verifies that there is no resurrection, as above. public void encryptCheckThread() { try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[2]; ThreadLocalRandom.current().nextBytes(ref); ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> allowedKeys = possibleEncrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (allowedKeys) { HashSet<CacheTestFixtures.SentinelKey> foundKeys = new HashSet<>(); CryptoMaterialsCache.EncryptCacheEntry ece = cache.getEntryForEncrypt(ref, UsageStats.ZERO); if (ece != null) { foundKeys.add((CacheTestFixtures.SentinelKey) ece.getResult().getCleartextDataKey()); } if (foundKeys.isEmpty()) { inc("encrypt check: empty foundRefs"); } else { inc("encrypt check: non-empty foundRefs"); } foundKeys.forEach( foundKey -> { if (!allowedKeys.containsKey(foundKey)) { fail("encrypt check: unexpected key; " + allowedKeys + " " + foundKeys); } }); allowedKeys .keySet() .forEach( allowedKey -> { if (!foundKeys.contains(allowedKey)) { inc("encrypt check: prune"); // safe since this is a concurrent map allowedKeys.remove(allowedKey); } }); } } } catch (Exception e) { throw new RuntimeException(e); } } // Performs a consistency check of the cache entries vs the LRU tracker periodically. Due to the // high overhead // of this test, we run it infrequently. public void checkThread() { try { while (!stopRequest.await(5000, TimeUnit.MILLISECONDS)) { barrierRequest = true; barrier.await(); assertConsistent(cache); inc("consistency check passed"); barrier.await(); } } catch (Exception e) { throw new RuntimeException(e); } } @Test public void test() throws Exception { cache = new LocalCryptoMaterialsCache(100_000); ArrayList<CompletableFuture<?>> futures = new ArrayList<>(); ExecutorService es = Executors.newCachedThreadPool(); ArrayList<Supplier<CompletableFuture<?>>> starters = new ArrayList<>(); for (int i = 0; i < 2; i++) { starters.add(() -> CompletableFuture.runAsync(this::encryptAddThread, es)); starters.add(() -> CompletableFuture.runAsync(this::encryptCheckThread, es)); starters.add(() -> CompletableFuture.runAsync(this::decryptAddThread, es)); starters.add(() -> CompletableFuture.runAsync(this::decryptCheckThread, es)); } starters.add(() -> CompletableFuture.runAsync(this::checkThread, es)); barrier = new CyclicBarrier(starters.size()); try { starters.forEach(s -> futures.add(s.get())); CompletableFuture<?> metaFuture = CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0])); try { metaFuture.get(10, TimeUnit.SECONDS); fail("unexpected termination"); } catch (TimeoutException e) { // ok } } finally { stopRequest.countDown(); es.shutdownNow(); es.awaitTermination(1, TimeUnit.SECONDS); if (counters != null) { new TreeMap<>(counters) .forEach((k, v) -> System.out.println(String.format("%s: %d", k, v.get()))); } } } }
5,422
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/CachingCryptoMaterialsManagerTest.java
package com.amazonaws.encryptionsdk.caching; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.EncryptCacheEntry; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.UsageStats; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Arrays; import java.util.concurrent.TimeUnit; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class CachingCryptoMaterialsManagerTest { private static final String PARTITION_ID = "partition ID"; @Mock private CryptoMaterialsCache cache; @Mock private CryptoMaterialsManager delegate; private CachingCryptoMaterialsManager cmm; private CachingCryptoMaterialsManager.Builder builder; private long maxAgeMs = 123456789; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(cache.putEntryForEncrypt(any(), any(), any(), any())) .thenAnswer( invocation -> entryFor((EncryptionMaterials) invocation.getArguments()[1], UsageStats.ZERO)); when(delegate.getMaterialsForEncrypt(any())) .thenThrow(new RuntimeException("Unexpected invocation")); when(delegate.decryptMaterials(any())).thenThrow(new RuntimeException("Unexpected invocation")); builder = CachingCryptoMaterialsManager.newBuilder() .withBackingMaterialsManager(delegate) .withCache(cache) .withPartitionId(PARTITION_ID) .withMaxAge(maxAgeMs, TimeUnit.MILLISECONDS) .withByteUseLimit(200) .withMessageUseLimit(100); cmm = builder.build(); } @Test public void whenCacheIsEmpty_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = setupForCacheMiss(request, result); EncryptionMaterials actualResult = cmm.getMaterialsForEncrypt(request); assertEquals(result, actualResult); verify(delegate).getMaterialsForEncrypt(request); verify(cache).putEntryForEncrypt(any(), any(), any(), eq(new UsageStats(100, 1))); } @Test public void whenCacheMisses_correctHintAndUsagePassed() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); setupForCacheMiss(request, result); cmm.getMaterialsForEncrypt(request); ArgumentCaptor<CryptoMaterialsCache.CacheHint> hintCaptor = ArgumentCaptor.forClass(CryptoMaterialsCache.CacheHint.class); verify(cache).putEntryForEncrypt(any(), any(), hintCaptor.capture(), any()); assertEquals(maxAgeMs, hintCaptor.getValue().getMaxAgeMillis()); } @Test public void whenCacheHasEntry_performsCacheHit() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = entryFor(result, UsageStats.ZERO); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); assertEquals(result, cmm.getMaterialsForEncrypt(request)); verify(delegate, never()).getMaterialsForEncrypt(any()); ArgumentCaptor<UsageStats> statsCaptor = ArgumentCaptor.forClass(UsageStats.class); verify(cache).getEntryForEncrypt(any(), statsCaptor.capture()); assertEquals(statsCaptor.getValue(), new UsageStats(100, 1)); } @Test public void whenAlgorithmIsUncachable_resultNotStoredInCache() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request).toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF) .build(); setupForCacheMiss(request, result); CachingCryptoMaterialsManager allowNoKdfCMM = CachingCryptoMaterialsManager.newBuilder() .withBackingMaterialsManager(delegate) .withCache(cache) .withPartitionId(PARTITION_ID) .withMaxAge(maxAgeMs, TimeUnit.MILLISECONDS) .withByteUseLimit(200) .withMessageUseLimit(100) .build(); assertEquals(result, allowNoKdfCMM.getMaterialsForEncrypt(request)); verify(cache, never()).putEntryForEncrypt(any(), any(), any(), any()); } @Test public void whenInitialUsageExceedsLimit_cacheIsBypassed() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder() // Even at _exactly_ the byte-use limit, we won't try the cache, // because it's unlikely to be useful to leave an entry with zero // bytes remaining. .setPlaintextSize(200) .build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request).toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); setupForCacheMiss(request, result); assertEquals(result, cmm.getMaterialsForEncrypt(request)); verifyNoMoreInteractions(cache); } @Test public void whenCacheEntryIsExhausted_byMessageLimit_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials cacheHitResult = CacheTestFixtures.createMaterialsResult(request); doReturn(CacheTestFixtures.createMaterialsResult(request)) .when(delegate) .getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(cacheHitResult, new UsageStats(0, 101)); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); EncryptionMaterials returnedResult = cmm.getMaterialsForEncrypt(request); assertNotEquals(cacheHitResult, returnedResult); verify(delegate, times(1)).getMaterialsForEncrypt(any()); verify(cache).putEntryForEncrypt(any(), eq(returnedResult), any(), any()); } @Test public void whenEncryptCacheEntryIsExpired_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials cacheHitResult = CacheTestFixtures.createMaterialsResult(request); doReturn(CacheTestFixtures.createMaterialsResult(request)) .when(delegate) .getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(cacheHitResult, new UsageStats(0, 100)); when(entry.getEntryCreationTime()).thenReturn(System.currentTimeMillis() - maxAgeMs - 1); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); EncryptionMaterials returnedResult = cmm.getMaterialsForEncrypt(request); assertNotEquals(cacheHitResult, returnedResult); verify(delegate, times(1)).getMaterialsForEncrypt(any()); verify(cache).putEntryForEncrypt(any(), eq(returnedResult), any(), any()); verify(entry).invalidate(); } @Test public void whenCacheEntryIsExhausted_byByteLimit_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials cacheHitResult = CacheTestFixtures.createMaterialsResult(request); doReturn(CacheTestFixtures.createMaterialsResult(request)) .when(delegate) .getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(cacheHitResult, new UsageStats(1_000_000 - 99, 0)); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); EncryptionMaterials returnedResult = cmm.getMaterialsForEncrypt(request); assertNotEquals(cacheHitResult, returnedResult); verify(delegate, times(1)).getMaterialsForEncrypt(any()); verify(cache).putEntryForEncrypt(any(), eq(returnedResult), any(), any()); } @Test public void whenStreaming_cacheMiss_withNoSizeHint_doesNotCache() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = setupForCacheMiss(request, result); EncryptionMaterials actualResult = cmm.getMaterialsForEncrypt(request); verifyNoMoreInteractions(cache); } @Test public void whenDecrypting_cacheMiss() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); doReturn(result).when(delegate).decryptMaterials(any()); DecryptionMaterials actual = cmm.decryptMaterials(request); assertEquals(result, actual); verify(cache).putEntryForDecrypt(any(), eq(result), any()); } @Test public void whenDecryptCacheMisses_correctHintPassed() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); doReturn(result).when(delegate).decryptMaterials(any()); cmm.decryptMaterials(request); ArgumentCaptor<CryptoMaterialsCache.CacheHint> hintCaptor = ArgumentCaptor.forClass(CryptoMaterialsCache.CacheHint.class); verify(cache).putEntryForDecrypt(any(), any(), hintCaptor.capture()); assertEquals(maxAgeMs, hintCaptor.getValue().getMaxAgeMillis()); } @Test public void whenDecrypting_cacheHit() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); when(cache.getEntryForDecrypt(any())).thenReturn(new TestDecryptCacheEntry(result)); DecryptionMaterials actual = cmm.decryptMaterials(request); assertEquals(result, actual); verify(cache, never()).putEntryForDecrypt(any(), any(), any()); verify(delegate, never()).decryptMaterials(any()); } @Test public void whenDecrypting_andEntryExpired_cacheMiss() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); doReturn(CacheTestFixtures.createDecryptResult(request)).when(delegate).decryptMaterials(any()); TestDecryptCacheEntry entry = new TestDecryptCacheEntry(result); entry.creationTime -= (maxAgeMs + 1); when(cache.getEntryForDecrypt(any())).thenReturn(entry); DecryptionMaterials actual = cmm.decryptMaterials(request); assertNotEquals(result, actual); verify(delegate, times(1)).decryptMaterials(any()); verify(cache, times(1)).putEntryForDecrypt(any(), any(), any()); } @Test public void testBuilderValidation() throws Exception { CachingCryptoMaterialsManager.Builder b = CachingCryptoMaterialsManager.newBuilder(); assertThrows(() -> b.withMaxAge(-1, TimeUnit.MILLISECONDS)); assertThrows(() -> b.withMaxAge(0, TimeUnit.MILLISECONDS)); assertThrows(() -> b.withMessageUseLimit(-1)); assertThrows(() -> b.withMessageUseLimit(1L << 33)); assertThrows(() -> b.withByteUseLimit(-1)); assertThrows(b::build); // backing CMM not set b.withBackingMaterialsManager(delegate); assertThrows(b::build); // cache not set b.withCache(cache); assertThrows(b::build); // max age b.withMaxAge(1, TimeUnit.SECONDS); b.build(); } @Test public void whenBuilderReused_uniquePartitionSet() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(1).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = setupForCacheMiss(request, result); CachingCryptoMaterialsManager.Builder builder = CachingCryptoMaterialsManager.newBuilder() .withCache(cache) .withBackingMaterialsManager(delegate) .withMaxAge(5, TimeUnit.DAYS); builder.build().getMaterialsForEncrypt(request); builder.build().getMaterialsForEncrypt(request); ArgumentCaptor<byte[]> idCaptor = ArgumentCaptor.forClass(byte[].class); verify(cache, times(2)).getEntryForEncrypt(idCaptor.capture(), any()); byte[] firstId = idCaptor.getAllValues().get(0); byte[] secondId = idCaptor.getAllValues().get(1); assertFalse(Arrays.equals(firstId, secondId)); } @Test public void whenMKPPassed_itIsUsed() throws Exception { JceMasterKey key = spy( JceMasterKey.getInstance( new SecretKeySpec(new byte[16], "AES"), "provider", "keyId", "AES/GCM/NoPadding")); CryptoMaterialsManager cmm = CachingCryptoMaterialsManager.newBuilder() .withCache(cache) .withMasterKeyProvider(key) .withMaxAge(5, TimeUnit.DAYS) .build(); cmm.getMaterialsForEncrypt(CacheTestFixtures.createMaterialsRequest(0)); verify(key).generateDataKey(any(), any()); } private EncryptCacheEntry setupForCacheMiss( EncryptionMaterialsRequest request, EncryptionMaterials result) throws Exception { doReturn(result).when(delegate).getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(result, UsageStats.ZERO); doReturn(entry).when(cache).putEntryForEncrypt(any(), eq(result), any(), any()); return entry; } private EncryptCacheEntry entryFor(EncryptionMaterials result, final UsageStats initialUsage) throws Exception { return spy(new TestEncryptCacheEntry(result, initialUsage)); } private static class TestEncryptCacheEntry implements EncryptCacheEntry { private final EncryptionMaterials result; private final UsageStats stats; public TestEncryptCacheEntry(EncryptionMaterials result, UsageStats initialUsage) { this.result = result; stats = initialUsage; } @Override public UsageStats getUsageStats() { return stats; } @Override public long getEntryCreationTime() { return System.currentTimeMillis(); } @Override public EncryptionMaterials getResult() { return result; } @Override public void invalidate() {} } private class TestDecryptCacheEntry implements CryptoMaterialsCache.DecryptCacheEntry { private final DecryptionMaterials result; private long creationTime = System.currentTimeMillis(); public TestDecryptCacheEntry(final DecryptionMaterials result) { this.result = result; } @Override public DecryptionMaterials getResult() { return result; } @Override public void invalidate() {} @Override public long getEntryCreationTime() { return creationTime; } } }
5,423
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/FileStreamingExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.SecureRandom; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoInputStream; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.util.IOUtils; /** * <p> * Encrypts and then decrypts a file under a random key. * * <p> * Arguments: * <ol> * <li>Name of file containing plaintext data to encrypt * </ol> * * <p> * This program demonstrates using a standard Java {@link SecretKey} object as a {@link MasterKey} to * encrypt and decrypt streaming data. */ public class FileStreamingExample { private static String srcFile; public static void main(String[] args) throws IOException { srcFile = args[0]; // In this example, we generate a random key. In practice, // you would get a key from an existing store SecretKey cryptoKey = retrieveEncryptionKey(); // Create a JCE master key provider using the random key and an AES-GCM encryption algorithm JceMasterKey masterKey = JceMasterKey.getInstance(cryptoKey, "Example", "RandomKey", "AES/GCM/NoPadding"); // Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. // This also chooses to encrypt with an algorithm suite that doesn't include signing for faster decryption, // since this use case assumes that the contexts that encrypt and decrypt are equally trusted. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); // Create an encryption context to identify this ciphertext Map<String, String> context = Collections.singletonMap("Example", "FileStreaming"); // Because the file might be to large to load into memory, we stream the data, instead of //loading it all at once. FileInputStream in = new FileInputStream(srcFile); CryptoInputStream<JceMasterKey> encryptingStream = crypto.createEncryptingStream(masterKey, in, context); FileOutputStream out = new FileOutputStream(srcFile + ".encrypted"); IOUtils.copy(encryptingStream, out); encryptingStream.close(); out.close(); // Decrypt the file. Verify the encryption context before returning the plaintext. // Since we encrypted using an unsigned algorithm suite, we can use the recommended // createUnsignedMessageDecryptingStream method that only accepts unsigned messages. in = new FileInputStream(srcFile + ".encrypted"); CryptoInputStream<JceMasterKey> decryptingStream = crypto.createUnsignedMessageDecryptingStream(masterKey, in); // Does it contain the expected encryption context? if (!"FileStreaming".equals(decryptingStream.getCryptoResult().getEncryptionContext().get("Example"))) { throw new IllegalStateException("Bad encryption context"); } // Write the plaintext data to disk. out = new FileOutputStream(srcFile + ".decrypted"); IOUtils.copy(decryptingStream, out); decryptingStream.close(); out.close(); } /** * In practice, this key would be saved in a secure location. * For this demo, we generate a new random key for each operation. */ private static SecretKey retrieveEncryptionKey() { SecureRandom rnd = new SecureRandom(); byte[] rawKey = new byte[16]; // 128 bits rnd.nextBytes(rawKey); return new SecretKeySpec(rawKey, "AES"); } }
5,424
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/BasicMultiRegionKeyEncryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; /** * Encrypts and then decrypts data using two related AWS KMS multi-Region keys. In this example, the * AWS KMS multi-Region encrypt key is in a different region than the related AWS KMS multi-Region * decrypt key. * * <p>This example demonstrates how you might use AWS KMS multi-Region keys and the AWS Encryption * SDK client-side library to encrypt data in one region, move or copy it to a different region, and * decrypt the data in the destination region. * * <p>Arguments: Two related AWS KMS multi-Region keys * * <ol> * <li>Encrypt multi-Region key ARN * <li>Decrypt multi-Region key ARN * </ol> * * For help finding the key ARN of your multi-Region key, see "Finding the key ID and ARN" at * https://docs.aws.amazon.com/kms/latest/developerguide/find-cmk-id-arn.html */ public class BasicMultiRegionKeyEncryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String multiRegionEncryptKey = args[0]; final String multiRegionDecryptKey = args[1]; encryptAndDecrypt(multiRegionEncryptKey, multiRegionDecryptKey); } static void encryptAndDecrypt( final String multiRegionEncryptKey, final String multiRegionDecryptKey ) { // 1. Instantiate the SDK // This builds the AwsCrypto client with // the RequireEncryptRequireDecrypt commitment policy, // which encrypts and decrypts only with committing algorithm suites. // This is the default commitment policy // if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS multi-Region optimized master key provider // in strict mode using buildStrict(). // This example uses two related multi-Region keys. // In strict mode, the AWS KMS multi-Region optimized master key provider encrypts // and decrypts only by using the key indicated // by key ARN passed to `buildStrict`. // To encrypt with this master key provider, // use any valid AWS KMS key identifier to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final AwsKmsMrkAwareMasterKeyProvider encryptingKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .buildStrict(multiRegionEncryptKey); // 3. Create an encryption context // Most encrypted data // should have an associated encryption context // protect its integrity. // This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> encryptResult = crypto.encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Instantiate an AWS KMS multi-Region optimized master key provider // in strict mode using buildStrict(). // This example uses two related multi-Region keys. // Now decrypt with a related multi-Region key in a different region. // In strict mode, the decrypt operation requires a key ARN. final AwsKmsMrkAwareMasterKeyProvider decryptKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .buildStrict(multiRegionDecryptKey); // 6. Decrypt the data with a related multi-Region key in a different region. final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> decryptResult = crypto.decryptData(decryptKeyProvider, ciphertext); // 7. Verify that the encryption context in the result contains // the encryption context supplied to the encryptData method. // Because the ESDK can add values to the encryption context, // don't require that the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 8. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,425
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/SetCommitmentPolicyExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; /** * <p> * Configures a client with a specific commitment policy, then * encrypts and decrypts data using an AWS KMS customer master key. * * This configuration should only be used as part of a migration from version 1.x to 2.x, or for advanced users * with specialized requirements. We recommend that AWS Encryption SDK users use the default commitment policy * whenever possible. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class SetCommitmentPolicyExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn = args[0]; encryptAndDecrypt(keyArn); } static void encryptAndDecrypt(final String keyArn) { // 1. Instantiate the SDK with a specific commitment policy // // `withCommitmentPolicy(CommitmentPolicy)` configures the client with // a commitment policy that dictates whether the client is required to encrypt // using committing algorithms and whether the client must require that the messages // it decrypts were encrypted using committing algorithms. // In this example, we set the commitment policy to `ForbidEncryptAllowDecrypt`. // This policy enforces that the client writes using non-committing algorithms, // and allows decrypting of messages created with committing algorithms. // // If this value is not set, the client is configured to use our recommended default: // `RequireEncryptRequireDecrypt`. // This policy enforces that the client uses committing algorithms // to encrypt and enforces that the client only decrypts messages created with committing algorithms. // We recommend using the default whenever possible. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict() // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyArn. // To encrypt and decrypt with this master key provider, use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn); // 3. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(keyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(keyProvider, ciphertext); // 6. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 7. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,426
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/EscrowedEncryptExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoOutputStream; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.util.IOUtils; /** * <p> * Encrypts a file using both AWS KMS and an asymmetric key pair. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * * <li>Name of file containing plaintext data to encrypt * </ol> * * You might use AWS Key Management Service (AWS KMS) for most encryption and decryption operations, but * still want the option of decrypting your data offline independently of AWS KMS. This sample * demonstrates one way to do this. * * The sample encrypts data under both an AWS KMS customer master key (CMK) and an "escrowed" RSA key pair * so that either key alone can decrypt it. You might commonly use the AWS KMS CMK for decryption. However, * at any time, you can use the private RSA key to decrypt the ciphertext independent of AWS KMS. * * This sample uses the JCEMasterKey class to generate a RSA public-private key pair * and saves the key pair in memory. In practice, you would store the private key in a secure offline * location, such as an offline HSM, and distribute the public key to your development team. * */ public class EscrowedEncryptExample { private static PublicKey publicEscrowKey; private static PrivateKey privateEscrowKey; public static void main(final String[] args) throws Exception { // This sample generates a new random key for each operation. // In practice, you would distribute the public key and save the private key in secure // storage. generateEscrowKeyPair(); final String kmsArn = args[0]; final String fileName = args[1]; standardEncrypt(kmsArn, fileName); standardDecrypt(kmsArn, fileName); escrowDecrypt(fileName); } private static void standardEncrypt(final String kmsArn, final String fileName) throws Exception { // Encrypt with the KMS CMK and the escrowed public key // 1. Instantiate the SDK // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict() // // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by kmsArn. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsArn); // 3. Instantiate a JCE master key provider // Because the user does not have access to the private escrow key, // they pass in "null" for the private key parameter. final JceMasterKey escrowPub = JceMasterKey.getInstance(publicEscrowKey, null, "Escrow", "Escrow", "RSA/ECB/OAEPWithSHA-512AndMGF1Padding"); // 4. Combine the providers into a single master key provider final MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(keyProvider, escrowPub); // 5. Encrypt the file // To simplify the code, we omit the encryption context. Production code should always // use an encryption context. For an example, see the other SDK samples. final FileInputStream in = new FileInputStream(fileName); final FileOutputStream out = new FileOutputStream(fileName + ".encrypted"); final CryptoOutputStream<?> encryptingStream = crypto.createEncryptingStream(provider, out); IOUtils.copy(in, encryptingStream); in.close(); encryptingStream.close(); } private static void standardDecrypt(final String kmsArn, final String fileName) throws Exception { // Decrypt with the AWS KMS CMK and the escrow public key. You can use a combined provider, // as shown here, or just the AWS KMS master key provider. // 1. Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict() // // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by kmsArn. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsArn); // 3. Instantiate a JCE master key provider // Because the user does not have access to the private // escrow key, they pass in "null" for the private key parameter. final JceMasterKey escrowPub = JceMasterKey.getInstance(publicEscrowKey, null, "Escrow", "Escrow", "RSA/ECB/OAEPWithSHA-512AndMGF1Padding"); // 4. Combine the providers into a single master key provider final MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(keyProvider, escrowPub); // 5. Decrypt the file // To simplify the code, we omit the encryption context. Production code should always // use an encryption context. For an example, see the other SDK samples. final FileInputStream in = new FileInputStream(fileName + ".encrypted"); final FileOutputStream out = new FileOutputStream(fileName + ".decrypted"); // Since we are using a signing algorithm suite, we avoid streaming decryption directly to the output file, // to ensure that the trailing signature is verified before writing any untrusted plaintext to disk. final ByteArrayOutputStream plaintextBuffer = new ByteArrayOutputStream(); final CryptoOutputStream<?> decryptingStream = crypto.createDecryptingStream(provider, plaintextBuffer); IOUtils.copy(in, decryptingStream); in.close(); decryptingStream.close(); final ByteArrayInputStream plaintextReader = new ByteArrayInputStream(plaintextBuffer.toByteArray()); IOUtils.copy(plaintextReader, out); out.close(); } private static void escrowDecrypt(final String fileName) throws Exception { // You can decrypt the stream using only the private key. // This method does not call AWS KMS. // 1. Instantiate the SDK final AwsCrypto crypto = AwsCrypto.standard(); // 2. Instantiate a JCE master key provider // This method call uses the escrowed private key, not null final JceMasterKey escrowPriv = JceMasterKey.getInstance(publicEscrowKey, privateEscrowKey, "Escrow", "Escrow", "RSA/ECB/OAEPWithSHA-512AndMGF1Padding"); // 3. Decrypt the file // To simplify the code, we omit the encryption context. Production code should always // use an encryption context. For an example, see the other SDK samples. final FileInputStream in = new FileInputStream(fileName + ".encrypted"); final FileOutputStream out = new FileOutputStream(fileName + ".deescrowed"); final CryptoOutputStream<?> decryptingStream = crypto.createDecryptingStream(escrowPriv, out); IOUtils.copy(in, decryptingStream); in.close(); decryptingStream.close(); } private static void generateEscrowKeyPair() throws GeneralSecurityException { final KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA"); kg.initialize(4096); // Escrow keys should be very strong final KeyPair keyPair = kg.generateKeyPair(); publicEscrowKey = keyPair.getPublic(); privateEscrowKey = keyPair.getPrivate(); } }
5,427
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/SetEncryptionAlgorithmExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; /** * <p> * Configures a client with a specific encryption algorithm, then * encrypts and decrypts data using that encryption algorithm and * an AWS KMS customer master key. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class SetEncryptionAlgorithmExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn = args[0]; encryptAndDecrypt(keyArn); } static void encryptAndDecrypt(final String keyArn) { // 1. Instantiate the SDK with the algorithm for encryption // // `withEncryptionAlgorithm(cryptoAlgorithm)` configures the client to encrypt // using a specified encryption algorithm. // This example sets the encryption algorithm to // `CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY`, // which is an algorithm that does not contain message signing. // // If this value is not set, the client encrypts with the recommended default: // `CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384`. // We recommend using the default whenever possible. // For a description of our supported algorithms, see https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/supported-algorithms.html // // You can update the encryption algorithm after constructing the client // by using `crypto.setEncryptionAlgorithm(CryptoAlgorithm)`. final AwsCrypto crypto = AwsCrypto.builder() .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict(). // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyArn. // To encrypt and decrypt with this master key provider, use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn); // 3. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(keyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(keyProvider, ciphertext); // 6. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 7. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,428
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/MultipleCmkEncryptExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; /** * <p> * Encrypts data using two different AWS KMS customer master keys, * which can then be decrypted by configuring an AWS KMS master key provider in * strict mode (`buildStrict`) with at least one of either key. * * <p> * Arguments: * <ol> * <li>Key ARN 1: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * <li>Key ARN 2: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class MultipleCmkEncryptExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn1 = args[0]; final String keyArn2 = args[1]; encryptAndDecrypt(keyArn1, keyArn2); } static void encryptAndDecrypt(final String keyArn1, final String keyArn2) { // Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider to encrypt with // In strict mode (`buildStrict`), the AWS KMS master key provider encrypts and decrypts only by using the // keys indicated by keyArn1 and keyArn2 final KmsMasterKeyProvider multiCmkKeyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn1, keyArn2); // 3. Instantiate an AWS KMS master key providers that are configured with keyArn1 and keyArn2 // separately. // These will be used later in this example to show that the encrypted messages created by multiCmkKeyProvider // can be decrypted by AWS KMS master key providers that are configured with either CMK. final KmsMasterKeyProvider singleCMKKeyProvider1 = KmsMasterKeyProvider.builder().buildStrict(keyArn1); final KmsMasterKeyProvider singleCMKKeyProvider2 = KmsMasterKeyProvider.builder().buildStrict(keyArn2); // 4. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 5. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(multiCmkKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 6. Decrypt the data with the AWS KMS master key provider that originally encrypted this data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(multiCmkKeyProvider, ciphertext); // 7. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 8. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); // 9. Now show that the encrypted message can also be decrypted by AWS KMS master key providers // configured with either CMK. final CryptoResult<byte[], KmsMasterKey> singleCmkDecryptResult1 = crypto.decryptData(singleCMKKeyProvider1, ciphertext); final CryptoResult<byte[], KmsMasterKey> singleCmkDecryptResult2 = crypto.decryptData(singleCMKKeyProvider2, ciphertext); // 10. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method for both decryptions if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(singleCmkDecryptResult1.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(singleCmkDecryptResult2.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 11. Verify that the decrypted plaintext matches the original plaintext for each decryption assert Arrays.equals(singleCmkDecryptResult1.getResult(), EXAMPLE_DATA); assert Arrays.equals(singleCmkDecryptResult2.getResult(), EXAMPLE_DATA); } }
5,429
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/BasicEncryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class BasicEncryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn = args[0]; encryptAndDecrypt(keyArn); } static void encryptAndDecrypt(final String keyArn) { // 1. Instantiate the SDK // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict(). // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyArn. // To encrypt and decrypt with this master key provider, use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn); // 3. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(keyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(keyProvider, ciphertext); // 6. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 7. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,430
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/DiscoveryMultiRegionDecryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import software.amazon.awssdk.regions.Region; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key in discovery mode. * Discovery mode is useful when you can't or don't want to specify a CMK on decrypt. * <p> * Arguments: * <ol> * <li>Key Name: A key identifier for the AWS KMS customer master key (CMK). For example, * a key ARN or a key alias. * For details, see "Key identifiers" at https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id * <li>Partition: The partition of the AWS KMS customer master key, which is usually "aws." * A partition is a group of regions. The partition is the second element in the key ARN, e.g. "arn" in "aws:aws: ..." * For details, see: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-syntax * <li>Account ID: The identifier for the account of the AWS KMS customer master key. * </ol> */ public class DiscoveryMultiRegionDecryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyName = args[0]; final String partition = args[1]; final String accountId = args[2]; final Region discoveryMrkRegion = Region.of(args[3]); encryptAndDecrypt(keyName, partition, accountId, discoveryMrkRegion); } static void encryptAndDecrypt( final String keyName, final String partition, final String accountId, final Region discoveryMrkRegion ) { // 1. Instantiate the SDK // This builds the AwsCrypto client with // the RequireEncryptRequireDecrypt commitment policy, // which decrypts only with committing algorithm suites. // This is the default commitment policy // if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS multi region optimized master key provider // in strict mode using buildStrict(). // In this example we are using // two related multi region keys. // we will encrypt with // the encrypting in the encrypting region first. // In strict mode, // the AWS KMS multi region optimized master key provider encrypts // and decrypts only by using the key indicated // by key arn passed to `buildStrict`. // To encrypt with this master key provider, // use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final AwsKmsMrkAwareMasterKeyProvider encryptingKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .buildStrict(keyName); // 3. Create an encryption context // Most encrypted data // should have an associated encryption context // to protect integrity. // This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> encryptResult = crypto .encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Instantiate a discovery filter for decrypting. // This filter limits the CMKs that the ESDK can use // to those in the specified AWS partition and accounts. // This filter is not required for discovery mode, // but is a best practice. final DiscoveryFilter discoveryFilter = new DiscoveryFilter(partition, accountId); // 6. Instantiate an AWS KMS multi region optimized master key provider // for decryption in discovery mode (`buildDiscovery`) // with a Discovery Mrk Region // and with a discovery filter. // // In discovery mode, the AWS KMS multi region optimized master key provider // attempts to decrypt only by using AWS KMS keys indicated in the encrypted message. // By configuring the master key provider with a Discovery Mrk Region, // this master key provider will only attempt to decrypt // with AWS KMS multi-Region keys in the Discovery Mrk Region. // If the Discovery Mrk Region is not configured, // it is limited to the Region configured for the AWS SDK. final AwsKmsMrkAwareMasterKeyProvider decryptingKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .discoveryMrkRegion(discoveryMrkRegion) .buildDiscovery(discoveryFilter); // 7. Decrypt the data // Even though the message was encrypted with an AWS KMS key in one region // the master key provider will attempt to decrypt with the discoveryMrkRegion. final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> decryptResult = crypto .decryptData(decryptingKeyProvider, ciphertext); // 8. Verify that the encryption context in the result contains // the encryption context supplied to the encryptData method. // Because the ESDK can add values to the encryption context, // don't require that the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 9. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,431
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/SimpleDataKeyCachingExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache; import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCache; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; /** * <p> * Encrypts a string using an AWS KMS customer master key (CMK) and data key caching * * <p> * Arguments: * <ol> * <li>KMS CMK ARN: To find the Amazon Resource Name of your AWS KMS customer master key (CMK), * see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * <li>Max entry age: Maximum time (in seconds) that a cached entry can be used * <li>Cache capacity: Maximum number of entries in the cache * </ol> */ public class SimpleDataKeyCachingExample { /* * Security thresholds * Max entry age is required. * Max messages (and max bytes) per data key are optional */ private static final int MAX_ENTRY_MSGS = 100; public static byte[] encryptWithCaching(String kmsCmkArn, int maxEntryAge, int cacheCapacity) { // Plaintext data to be encrypted byte[] myData = "My plaintext data".getBytes(StandardCharsets.UTF_8); // Encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("purpose", "test"); // Create a master key provider MasterKeyProvider<KmsMasterKey> keyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsCmkArn); // Create a cache CryptoMaterialsCache cache = new LocalCryptoMaterialsCache(cacheCapacity); // Create a caching CMM CryptoMaterialsManager cachingCmm = CachingCryptoMaterialsManager.newBuilder().withMasterKeyProvider(keyProvider) .withCache(cache) .withMaxAge(maxEntryAge, TimeUnit.SECONDS) .withMessageUseLimit(MAX_ENTRY_MSGS) .build(); // When the call to encryptData specifies a caching CMM, // the encryption operation uses the data key cache final AwsCrypto encryptionSdk = AwsCrypto.standard(); return encryptionSdk.encryptData(cachingCmm, myData, encryptionContext).getResult(); } }
5,432
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/RestrictRegionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key in discovery mode. * Discovery mode is useful when you use an alias to identify a CMK when encrypting and the * underlying key ARN might vary in each AWS Region. * <p> * Arguments: * <ol> * <li>Key Name: An identifier for the AWS KMS customer master key (CMK) to use. For example, * a key ARN or an alias name. * See https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id for * a description of AWS KMS key identifiers. * <li>Partition: The partition that the AWS KMS customer master key belongs in. This is usually "aws". * <li>Account ID: The identifier for the account that the AWS KMS customer master key belongs in. * <li>Region Name: The region that the AWS KMS customer master key belongs in. * </ol> */ public class RestrictRegionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyName = args[0]; final String partition = args[1]; final String accountId = args[2]; final Region region = Region.of(args[3]); encryptAndDecrypt(keyName, partition, accountId, region); } static void encryptAndDecrypt(final String keyName, final String partition, final String accountId, final Region region) { // Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate the AWS KMS client for the desired region final KmsClient kmsClient = KmsClient.builder().region(region).build(); // 3. Instantiate an AWS KMS master key provider for encryption. // // In strict mode (`buildStrict`), the AWS KMS master key provider will only encrypt and decrypt using the key // indicated by keyName. // This example uses an AWS KMS CMK ARN. Because this master key provider will // only be used for encryption, an AWS KMS CMK alias could also be used. final KmsMasterKeyProvider encryptingKeyProvider = KmsMasterKeyProvider.builder().buildStrict(keyName); // 4. Create an encryption context // // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 5. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 6. Instantiate a Discovery Filter to restrict which AWS KMS CMKs an AWS KMS master key provider // is allowed to attempt decryption with to a particular partition and account. // Configuring a Discovery AWS KMS master key provider with a Discovery Filter is a best practice, // but is not required to restrict the CMKs by region. final DiscoveryFilter discoveryFilter = new DiscoveryFilter(partition, accountId); // 7. Instantiate an AWS KMS master key provider for decryption in discovery mode (`buildDiscovery`) with a // custom client factory for the desired region. // // The custom client factory will only attempt to decrypt using CMKs from the desired region, // and skip any CMK not in the desired region. // If the encrypted message contains no CMKs within the desired region, decryption fails. // // In discovery mode, the AWS KMS master key provider will attempt to decrypt using AWS KMS ARNs // indicated in the encrypted message. // This example also configures the AWS KMS master key provider with a Discovery Filter to limit // the attempted AWS KMS CMKs to a particular partition and account. final KmsMasterKeyProvider decryptingKeyProvider = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(cmkRegion -> { if(cmkRegion.equals(region)) { // return the previously built AWS KMS client so that we do // not create a new client on every decrypt call. return kmsClient; } throw new AwsCryptoException("Only " + region.id() + " is supported"); }) .buildDiscovery(discoveryFilter); // 8. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(decryptingKeyProvider, ciphertext); // 9. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 10. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,433
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/DiscoveryDecryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key in discovery mode. * Discovery mode is useful when you use an alias to identify a CMK when encrypting and the * underlying key ARN might vary in each AWS Region. * <p> * Arguments: * <ol> * <li>Key Name: An identifier for the AWS KMS customer master key (CMK) to use. For example, * a key ARN or a key alias. * For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * <li>Partition: The partition of the AWS KMS customer master key, which is usually "aws." * A partition is a group of regions. The partition is the second element in the key ARN, e.g. "arn" in "aws:aws: ..." * <li>Account ID: The identifier for the account of the AWS KMS customer master key. * </ol> */ public class DiscoveryDecryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyName = args[0]; final String partition = args[1]; final String accountId = args[2]; encryptAndDecrypt(keyName, partition, accountId); } static void encryptAndDecrypt(final String keyName, final String partition, final String accountId) { // 1. Instantiate the SDK // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider for encryption. // // In strict mode (`buildStrict`), the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyName. final KmsMasterKeyProvider encryptingKeyProvider = KmsMasterKeyProvider.builder().buildStrict(keyName); // 3. Create an encryption context // // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Instantiate a discovery filter for decrypting. This filter restricts what AWS KMS CMKs the // AWS KMS master key provider can use to those in a particular AWS partition and account. // You can create a similar filter with one partition and multiple AWS accounts. // This example only configures the filter with one account, but more may be specified // as long as they exist within the same partition. // This filter is not required for Discovery mode, but is a best practice. final DiscoveryFilter discoveryFilter = new DiscoveryFilter(partition, accountId); // 6. Instantiate an AWS KMS master key provider for decryption in discovery mode (`buildDiscovery`) with a // Discovery Filter. // // In discovery mode, the AWS KMS master key provider attempts to decrypt only by using AWS KMS ARNs // indicated in the encrypted message. // By configuring the master key provider with a Discovery Filter, this master key provider // attempts to decrypt AWS KMS CMKs only in the configured partition and accounts. final KmsMasterKeyProvider decryptingKeyProvider = KmsMasterKeyProvider.builder().buildDiscovery(discoveryFilter); // 7. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(decryptingKeyProvider, ciphertext); // 8. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 9. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
5,434
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoOutputStream.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.MessageCryptoHandler; import com.amazonaws.encryptionsdk.internal.Utils; import java.io.IOException; import java.io.OutputStream; import java.util.List; /** * A CryptoOutputStream is a subclass of java.io.OutputStream. It performs cryptographic * transformation of the bytes passing through it. * * <p>The CryptoOutputStream wraps a provided OutputStream object and performs cryptographic * transformation of the bytes written to it. The transformed bytes are then written to the wrapped * OutputStream. It uses the cryptography handler provided during construction to invoke methods * that perform the cryptographic transformations. * * <p>In short, writing to the CryptoOutputStream results in those bytes being cryptographically * transformed and written to the wrapped OutputStream. * * <p>For example, if the crypto handler provides methods for decryption, the CryptoOutputStream * will decrypt the provided ciphertext bytes and write the plaintext bytes to the wrapped * OutputStream. * * <p>This class adheres strictly to the semantics, especially the failure semantics, of its * ancestor class java.io.OutputStream. This class overrides all the methods specified in its * ancestor class. * * <p>To instantiate an instance of this class, please see {@link AwsCrypto}. * * @param <K> The type of {@link MasterKey}s used to manipulate the data. */ public class CryptoOutputStream<K extends MasterKey<K>> extends OutputStream { private final OutputStream outputStream_; private final MessageCryptoHandler cryptoHandler_; /** * Constructs a CryptoOutputStream that wraps the provided OutputStream object. It performs * cryptographic transformation of the bytes written to it using the methods provided in the * provided CryptoHandler implementation. The transformed bytes are then written to the wrapped * OutputStream. * * @param outputStream the outputStream object to be wrapped. * @param cryptoHandler the cryptoHandler implementation that provides the methods to use in * performing cryptographic transformation of the bytes written to this stream. */ CryptoOutputStream(final OutputStream outputStream, final MessageCryptoHandler cryptoHandler) { outputStream_ = Utils.assertNonNull(outputStream, "outputStream"); cryptoHandler_ = Utils.assertNonNull(cryptoHandler, "cryptoHandler"); } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void write(final byte[] b) throws IllegalArgumentException, IOException, BadCiphertextException { if (b == null) { throw new IllegalArgumentException("b cannot be null"); } write(b, 0, b.length); } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void write(final byte[] b, final int off, final int len) throws IllegalArgumentException, IOException, BadCiphertextException { if (b == null) { throw new IllegalArgumentException("b cannot be null"); } if (len < 0 || off < 0) { throw new IllegalArgumentException( String.format("Invalid values for offset: %d and length: %d", off, len)); } final int outLen = cryptoHandler_.estimatePartialOutputSize(len); final byte[] outBytes = new byte[outLen]; int bytesWritten = cryptoHandler_.processBytes(b, off, len, outBytes, 0).getBytesWritten(); if (bytesWritten > 0) { outputStream_.write(outBytes, 0, bytesWritten); } } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void write(int b) throws IOException, BadCiphertextException { byte[] bArray = new byte[1]; bArray[0] = (byte) b; write(bArray, 0, 1); } /** * Closes this output stream and releases any system resources associated with this stream. * * <p>This method writes any final bytes to the underlying stream that complete the cyptographic * transformation of the written bytes. It also calls close on the wrapped OutputStream. * * @throws IOException if an I/O error occurs. * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void close() throws IOException, BadCiphertextException { final byte[] outBytes = new byte[cryptoHandler_.estimateFinalOutputSize()]; int finalLen = cryptoHandler_.doFinal(outBytes, 0); outputStream_.write(outBytes, 0, finalLen); outputStream_.close(); } /** * Sets an upper bound on the size of the input data. This method should be called before writing * any data to the stream. If this method is not called prior to writing data, performance may be * reduced (notably, it will not be possible to cache data keys when encrypting). * * <p>Among other things, this size is used to enforce limits configured on the {@link * CachingCryptoMaterialsManager}. * * <p>If the size set here is exceeded, an exception will be thrown, and the encyption or * decryption will fail. * * <p>If this method is called multiple times, the smallest bound will be used. * * @param size Maximum input size. */ public void setMaxInputLength(long size) { cryptoHandler_.setMaxInputLength(size); } /** Returns the result of the cryptographic operations including associate metadata. */ public CryptoResult<CryptoOutputStream<K>, K> getCryptoResult() { if (!cryptoHandler_.getHeaders().isComplete()) { throw new IllegalStateException("Ciphertext headers not yet written to stream"); } //noinspection unchecked return new CryptoResult<>( this, (List<K>) cryptoHandler_.getMasterKeys(), cryptoHandler_.getHeaders()); } }
5,435
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoMaterialsManager.java
package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; /** * The crypto materials manager is responsible for preparing the cryptographic materials needed to * process a request - notably, preparing the cleartext data key and (if applicable) trailing * signature keys on both encrypt and decrypt. */ public interface CryptoMaterialsManager { /** * Prepares materials for an encrypt request. The resulting materials result must have a cleartext * data key and (if applicable for the crypto algorithm in use) a trailing signature key. * * <p>The encryption context returned may be different from the one passed in the materials * request, and will be serialized (in cleartext) within the encrypted message. * * @see EncryptionMaterials * @see EncryptionMaterialsRequest * @param request * @return */ EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request); DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request); }
5,436
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/MasterKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; /** * Represents the cryptographic key used to protect the {@link DataKey} (which, in turn, protects * the data). * * <p>All MasterKeys extend {@link MasterKeyProvider} because they are all capable of providing * exactly themselves. This simplifies implementation when only a single {@link MasterKey} is used * and/or expected. * * @param <K> the concrete type of the {@link MasterKey} */ public abstract class MasterKey<K extends MasterKey<K>> extends MasterKeyProvider<K> { public abstract String getProviderId(); /** Equivalent to calling {@link #getProviderId()}. */ @Override public String getDefaultProviderId() { return getProviderId(); } public abstract String getKeyId(); /** * Generates a new {@link DataKey} which is protected by this {@link MasterKey} for use with * {@code algorithm} and associated with the provided {@code encryptionContext}. */ public abstract DataKey<K> generateDataKey( CryptoAlgorithm algorithm, Map<String, String> encryptionContext); /** * Returns a new copy of the provided {@code dataKey} which is protected by this {@link MasterKey} * for use with {@code algorithm} and associated with the provided {@code encryptionContext}. */ public abstract DataKey<K> encryptDataKey( CryptoAlgorithm algorithm, Map<String, String> encryptionContext, DataKey<?> dataKey); /** Returns {@code true} if and only if {@code provider} equals {@link #getProviderId()}. */ @Override public boolean canProvide(final String provider) { return getProviderId().equals(provider); } /** * Returns {@code this} if {@code provider} and {@code keyId} match {@code this}. Otherwise, * throws an appropriate exception. */ @SuppressWarnings("unchecked") @Override public K getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { if (!canProvide(provider)) { throw new UnsupportedProviderException( "MasterKeys can only provide themselves. Requested " + buildName(provider, keyId) + " but only " + toString() + " is available"); } if (!getKeyId().equals(keyId)) { throw new NoSuchMasterKeyException( "MasterKeys can only provide themselves. Requested " + buildName(provider, keyId) + " but only " + toString() + " is available"); } return (K) this; } @Override public String toString() { return buildName(getProviderId(), getKeyId()); } /** Returns a list of length {@code 1} containing {@code this}. */ @SuppressWarnings("unchecked") @Override public List<K> getMasterKeysForEncryption(final MasterKeyRequest request) { return (List<K>) Collections.singletonList(this); } private static String buildName(final String provider, final String keyId) { return String.format("%s://%s", provider, keyId); } /** * Two {@link MasterKey}s are equal if they are instances of the <em>exact same class</em> and * their values for {@code keyId}, {@code providerId}, and {@code defaultProviderId} are equal. */ @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!obj.getClass().equals(getClass())) { return false; } final MasterKey<?> mk = (MasterKey<?>) obj; return Objects.equals(getKeyId(), mk.getKeyId()) && Objects.equals(getProviderId(), mk.getProviderId()) && Objects.equals(getDefaultProviderId(), mk.getDefaultProviderId()); } @Override public int hashCode() { return Objects.hash(getKeyId(), getProviderId(), getDefaultProviderId()); } }
5,437
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/DataKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import javax.crypto.SecretKey; /** * Represents both the cleartext and encrypted bytes of a data key. * * @param <M> the type of {@link MasterKey} used to protect this {@code DataKey}. */ public class DataKey<M extends MasterKey<M>> implements EncryptedDataKey { private final byte[] providerInformation_; private final byte[] encryptedDataKey_; private final SecretKey key_; private final M masterKey_; public DataKey( final SecretKey key, final byte[] encryptedDataKey, final byte[] providerInformation, final M masterKey) { super(); key_ = key; encryptedDataKey_ = encryptedDataKey.clone(); providerInformation_ = providerInformation.clone(); masterKey_ = masterKey; } /** Returns the cleartext bytes of the data key. */ public SecretKey getKey() { return key_; } @Override public String getProviderId() { return masterKey_.getProviderId(); } @Override public byte[] getProviderInformation() { return providerInformation_.clone(); } @Override public byte[] getEncryptedDataKey() { return encryptedDataKey_.clone(); } /** Returns the {@link MasterKey} used to encrypt this {@link DataKey}. */ public M getMasterKey() { return masterKey_; } }
5,438
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/ParsedCiphertext.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Exposes header information of ciphertexts to make it easier to inspect the algorithm, keys, and * encryption context prior to decryption. * * <p>Please note that the class does <em>not</em> make defensive copies. */ public class ParsedCiphertext extends CiphertextHeaders { private final byte[] ciphertext_; private final int offset_; /** * Parses {@code ciphertext}. Please note that this does <em>not</em> make a defensive copy of * {@code ciphertext} and that any changes made to the backing array will be reflected here as * well. * * @param ciphertext The ciphertext to parse * @param maxEncryptedDataKeys The maximum number of encrypted data keys to parse. Zero indicates * no maximum. */ public ParsedCiphertext(final byte[] ciphertext, final int maxEncryptedDataKeys) { ciphertext_ = Utils.assertNonNull(ciphertext, "ciphertext"); offset_ = deserialize(ciphertext_, 0, maxEncryptedDataKeys); if (!this.isComplete()) { throw new BadCiphertextException("Incomplete ciphertext."); } } /** * Parses {@code ciphertext} without enforcing a max EDK count. Please note that this does * <em>not</em> make a defensive copy of {@code ciphertext} and that any changes made to the * backing array will be reflected here as well. */ public ParsedCiphertext(final byte[] ciphertext) { this(ciphertext, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); } /** * Returns the raw ciphertext backing this object. This is <em>not</em> a defensive copy and so * must not be modified by callers. */ @SuppressFBWarnings("EI_EXPOSE_REP") public byte[] getCiphertext() { return ciphertext_; } /** The offset at which the first non-header byte in {@code ciphertext} is located. */ public int getOffset() { return offset_; } }
5,439
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/MasterKeyProvider.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; /** * Represents the logic necessary to select and construct {@link MasterKey}s for encrypting and * decrypting messages. This is an abstract class. * * @param <K> the type of {@link MasterKey} returned by this provider */ public abstract class MasterKeyProvider<K extends MasterKey<K>> { /** ProviderId used by this instance when no other is specified. */ public abstract String getDefaultProviderId(); /** * Returns true if this MasterKeyProvider can provide keys from the specified @{code provider}. * * @param provider * @return */ public boolean canProvide(final String provider) { return getDefaultProviderId().equals(provider); } /** * Equivalent to calling {@link #getMasterKey(String, String)} using {@link * #getDefaultProviderId()} as the provider. */ public K getMasterKey(final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { return getMasterKey(getDefaultProviderId(), keyId); } /** * Returns the specified {@link MasterKey} if possible. * * @param provider * @param keyId * @return * @throws UnsupportedProviderException if this object cannot return {@link MasterKey}s associated * with the given provider * @throws NoSuchMasterKeyException if this object cannot find (and thus construct) the {@link * MasterKey} associated with {@code keyId} */ public abstract K getMasterKey(String provider, String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException; /** * Returns all {@link MasterKey}s which should be used to protect the plaintext described by * {@code request}. */ public abstract List<K> getMasterKeysForEncryption(MasterKeyRequest request); /** * Iterates through {@code encryptedDataKeys} and returns the first one which can be successfully * decrypted. * * @return a DataKey if one can be decrypted, otherwise returns {@code null} * @throws UnsupportedProviderException if the {@code encryptedDataKey} is associated with an * unsupported provider * @throws CannotUnwrapDataKeyException if the {@code encryptedDataKey} cannot be decrypted */ public abstract DataKey<K> decryptDataKey( CryptoAlgorithm algorithm, Collection<? extends EncryptedDataKey> encryptedDataKeys, Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException; protected AwsCryptoException buildCannotDecryptDksException() { return buildCannotDecryptDksException(Collections.<Throwable>emptyList()); } protected AwsCryptoException buildCannotDecryptDksException(Throwable t) { return buildCannotDecryptDksException(Collections.singletonList(t)); } protected AwsCryptoException buildCannotDecryptDksException(List<? extends Throwable> t) { if (t == null || t.isEmpty()) { return new CannotUnwrapDataKeyException("Unable to decrypt any data keys"); } else { final CannotUnwrapDataKeyException ex = new CannotUnwrapDataKeyException("Unable to decrypt any data keys", t.get(0)); for (final Throwable e : t) { ex.addSuppressed(e); } return ex; } } }
5,440
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoInputStream.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.internal.Utils.assertNonNull; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.MessageCryptoHandler; import com.amazonaws.encryptionsdk.internal.Utils; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * A CryptoInputStream is a subclass of java.io.InputStream. It performs cryptographic * transformation of the bytes passing through it. * * <p>The CryptoInputStream wraps a provided InputStream object and performs cryptographic * transformation of the bytes read from the wrapped InputStream. It uses the cryptography handler * provided during construction to invoke methods that perform the cryptographic transformations. * * <p>In short, reading from the CryptoInputStream returns bytes that are the cryptographic * transformations of the bytes read from the wrapped InputStream. * * <p>For example, if the cryptography handler provides methods for decryption, the * CryptoInputStream will read ciphertext bytes from the wrapped InputStream, decrypt, and return * them as plaintext bytes. * * <p>This class adheres strictly to the semantics, especially the failure semantics, of its * ancestor class java.io.InputStream. This class overrides all the methods specified in its * ancestor class. * * <p>To instantiate an instance of this class, please see {@link AwsCrypto}. * * @param <K> The type of {@link MasterKey}s used to manipulate the data. */ public class CryptoInputStream<K extends MasterKey<K>> extends InputStream { private static final int MAX_READ_LEN = 4096; private byte[] outBytes_ = new byte[0]; private int outStart_; private int outEnd_; private final InputStream inputStream_; private final MessageCryptoHandler cryptoHandler_; private boolean hasFinalCalled_; private boolean hasProcessBytesCalled_; /** * Constructs a CryptoInputStream that wraps the provided InputStream object. It performs * cryptographic transformation of the bytes read from the wrapped InputStream using the methods * provided in the provided CryptoHandler implementation. * * @param inputStream the inputStream object to be wrapped. * @param cryptoHandler the cryptoHandler implementation that provides the methods to use in * performing cryptographic transformation of the bytes read from the inputStream. */ CryptoInputStream(final InputStream inputStream, final MessageCryptoHandler cryptoHandler) { inputStream_ = Utils.assertNonNull(inputStream, "inputStream"); cryptoHandler_ = Utils.assertNonNull(cryptoHandler, "cryptoHandler"); } /** * Fill the output bytes by reading from the wrapped InputStream and processing it through the * crypto handler. * * @return the number of bytes processed and returned by the crypto handler. */ private int fillOutBytes() throws IOException, BadCiphertextException { final byte[] inputStreamBytes = new byte[MAX_READ_LEN]; final int readLen = inputStream_.read(inputStreamBytes); outStart_ = 0; int processedLen; if (readLen < 0) { // Mark end of stream until doFinal returns something. processedLen = -1; if (!hasFinalCalled_) { int outOffset = 0; int outLen = 0; // Handle the case where processBytes() was never called before. // This happens with an empty file where the end of stream is // reached on the first read attempt. In this case, // processBytes() must be called so the header bytes are written // during encryption. if (!hasProcessBytesCalled_) { outBytes_ = new byte[cryptoHandler_.estimateOutputSize(0)]; outLen += cryptoHandler_ .processBytes(inputStreamBytes, 0, 0, outBytes_, outOffset) .getBytesWritten(); outOffset += outLen; } else { outBytes_ = new byte[cryptoHandler_.estimateFinalOutputSize()]; } // Get final bytes. outLen += cryptoHandler_.doFinal(outBytes_, outOffset); processedLen = outLen; hasFinalCalled_ = true; } } else { // process the read bytes. outBytes_ = new byte[cryptoHandler_.estimatePartialOutputSize(readLen)]; processedLen = cryptoHandler_ .processBytes(inputStreamBytes, 0, readLen, outBytes_, outStart_) .getBytesWritten(); hasProcessBytesCalled_ = true; } outEnd_ = processedLen; return processedLen; } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public int read(final byte[] b, final int off, final int len) throws IllegalArgumentException, IOException, BadCiphertextException { assertNonNull(b, "b"); if (len < 0 || off < 0) { throw new IllegalArgumentException( String.format("Invalid values for offset: %d and length: %d", off, len)); } if (b.length == 0 || len == 0) { return 0; } // fill the output bytes if there aren't any left to return. if ((outEnd_ - outStart_) <= 0) { int newBytesLen = 0; // Block until a byte is read or end of stream in the underlying // stream is reached. while (newBytesLen == 0) { newBytesLen = fillOutBytes(); } if (newBytesLen < 0) { return -1; } } final int copyLen = Math.min((outEnd_ - outStart_), len); System.arraycopy(outBytes_, outStart_, b, off, copyLen); outStart_ += copyLen; return copyLen; } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public int read(final byte[] b) throws IllegalArgumentException, IOException, BadCiphertextException { return read(b, 0, b.length); } /** * {@inheritDoc} * * @throws BadCiphertextException if b contains invalid or corrupt ciphertext. This is thrown only * during decryption. */ @Override public int read() throws IOException, BadCiphertextException { final byte[] bArray = new byte[1]; int result = 0; while (result == 0) { result = read(bArray, 0, 1); } if (result > 0) { return (bArray[0] & 0xFF); } else { return result; } } @Override public void close() throws IOException { inputStream_.close(); } /** Returns metadata associated with the performed cryptographic operation. */ @Override public int available() throws IOException { return (outBytes_.length + inputStream_.available()); } /** * Sets an upper bound on the size of the input data. This method should be called before reading * any data from the stream. If this method is not called prior to reading any data, performance * may be reduced (notably, it will not be possible to cache data keys when encrypting). * * <p>Among other things, this size is used to enforce limits configured on the {@link * CachingCryptoMaterialsManager}. * * <p>If the input size set here is exceeded, an exception will be thrown, and the encyption or * decryption will fail. * * <p>If this method is called multiple times, the smallest bound will be used. * * @param size Maximum input size. */ public void setMaxInputLength(long size) { cryptoHandler_.setMaxInputLength(size); } /** * Returns the result of the cryptographic operations including associate metadata. * * @throws IOException * @throws BadCiphertextException */ public CryptoResult<CryptoInputStream<K>, K> getCryptoResult() throws BadCiphertextException, IOException { while (!cryptoHandler_.getHeaders().isComplete()) { if (fillOutBytes() == -1) { throw new BadCiphertextException("No CiphertextHeaders found."); } } //noinspection unchecked return new CryptoResult<>( this, (List<K>) cryptoHandler_.getMasterKeys(), cryptoHandler_.getHeaders()); } }
5,441
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoResult.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Represents the result of an operation by {@link AwsCrypto}. It not only captures the {@code * result} of the operation but also additional metadata such as the {@code encryptionContext}, * {@code algorithm}, {@link MasterKey}(s), and any other information captured in the {@link * CiphertextHeaders}. * * @param <T> the type of the underlying {@code result} * @param <K> the type of the {@link MasterKey}s used in production of this result */ public class CryptoResult<T, K extends MasterKey<K>> { private final T result_; private final List<K> masterKeys_; private final Map<String, String> encryptionContext_; private final CiphertextHeaders headers_; /** Note, does not make a defensive copy of any of the data. */ CryptoResult(final T result, final List<K> masterKeys, final CiphertextHeaders headers) { result_ = result; masterKeys_ = Collections.unmodifiableList(masterKeys); headers_ = headers; encryptionContext_ = headers_.getEncryptionContextMap(); } /** * The actual result of the cryptographic operation. This is not a defensive copy and callers * should not modify it. * * @return */ public T getResult() { return result_; } /** * Returns all relevant {@link MasterKey}s. In the case of encryption, returns all {@code * MasterKey}s used to protect the ciphertext. In the case of decryption, returns just the {@code * MasterKey} used to decrypt the ciphertext. * * @return */ public List<K> getMasterKeys() { return masterKeys_; } /** Convenience method for retrieving the keyIds in the results from {@link #getMasterKeys()}. */ public List<String> getMasterKeyIds() { final List<String> result = new ArrayList<>(masterKeys_.size()); for (final MasterKey<K> mk : masterKeys_) { result.add(mk.getKeyId()); } return result; } public Map<String, String> getEncryptionContext() { return encryptionContext_; } /** Convenience method equivalent to {@link #getHeaders()}.{@code getCryptoAlgoId()}. */ public CryptoAlgorithm getCryptoAlgorithm() { return headers_.getCryptoAlgoId(); } public CiphertextHeaders getHeaders() { return headers_; } }
5,442
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/MasterKeyRequest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Contains information which {@link MasterKeyProvider}s can use to select which {@link MasterKey}s * to use to protect a given plaintext. This class is immutable. */ public final class MasterKeyRequest { private final Map<String, String> encryptionContext_; private final boolean isStreaming_; private final byte[] plaintext_; private final long size_; private MasterKeyRequest( final Map<String, String> encryptionContext, final boolean isStreaming, final byte[] plaintext, final long size) { encryptionContext_ = encryptionContext; isStreaming_ = isStreaming; plaintext_ = plaintext; size_ = size; } public Map<String, String> getEncryptionContext() { return encryptionContext_; } public boolean isStreaming() { return isStreaming_; } /** The plaintext, if available, to be protected by this request. Otherwise, {@code null}. */ public byte[] getPlaintext() { return plaintext_ != null ? plaintext_.clone() : null; } /** The size of the plaintext, if available. Otherwise {@code -1}. */ public long getSize() { return size_; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private Map<String, String> encryptionContext_ = new HashMap<>(); private boolean isStreaming_ = false; private byte[] plaintext_ = null; private long size_ = -1; public Map<String, String> getEncryptionContext() { return encryptionContext_; } public Builder setEncryptionContext(final Map<String, String> encryptionContext) { encryptionContext_ = encryptionContext; return this; } public boolean isStreaming() { return isStreaming_; } public Builder setStreaming(final boolean isStreaming) { isStreaming_ = isStreaming; return this; } /** * Please note that this does not make a defensive copy of the plaintext and so any * modifications made to the backing array will be reflected in this Builder. */ @SuppressFBWarnings("EI_EXPOSE_REP") public byte[] getPlaintext() { return plaintext_; } /** * Please note that this does not make a defensive copy of the plaintext and so any * modifications made to the backing array will be reflected in this Builder. */ @SuppressFBWarnings("EI_EXPOSE_REP") public Builder setPlaintext(final byte[] plaintext) { if (size_ != -1) { throw new IllegalStateException( "The plaintext may only be set if the size has not been explicitly set"); } plaintext_ = plaintext; return this; } public Builder setSize(final long size) { if (plaintext_ != null) { throw new IllegalStateException( "Size may only explicitly set when the plaintext is not set"); } size_ = size; return this; } public long getSize() { return size_; } public MasterKeyRequest build() { return new MasterKeyRequest( Collections.unmodifiableMap(new HashMap<>(encryptionContext_)), isStreaming_, plaintext_, plaintext_ != null ? plaintext_.length : size_); } } }
5,443
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/DefaultCryptoMaterialsManager.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.internal.Utils.assertNonNull; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.TrailingSignatureAlgorithm; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.PublicKey; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The default implementation of {@link CryptoMaterialsManager}, used implicitly when passing a * {@link MasterKeyProvider} to methods in {@link AwsCrypto}. * * <p>This default implementation delegates to a specific {@link MasterKeyProvider} specified at * construction time. It also handles generating trailing signature keys when needed, placing them * in the encryption context (and extracting them at decrypt time). */ public class DefaultCryptoMaterialsManager implements CryptoMaterialsManager { private final MasterKeyProvider<?> mkp; private final CryptoAlgorithm DEFAULT_CRYPTO_ALGORITHM = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; /** @param mkp The master key provider to delegate to */ public DefaultCryptoMaterialsManager(MasterKeyProvider<?> mkp) { Utils.assertNonNull(mkp, "mkp"); this.mkp = mkp; } @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { Map<String, String> context = request.getContext(); CryptoAlgorithm algo = request.getRequestedAlgorithm(); CommitmentPolicy commitmentPolicy = request.getCommitmentPolicy(); // Set default according to commitment policy if (algo == null && commitmentPolicy == CommitmentPolicy.ForbidEncryptAllowDecrypt) { algo = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; } else if (algo == null) { algo = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; } KeyPair trailingKeys = null; if (algo.getTrailingSignatureLength() > 0) { try { trailingKeys = generateTrailingSigKeyPair(algo); if (context.containsKey(Constants.EC_PUBLIC_KEY_FIELD)) { throw new IllegalArgumentException( "EncryptionContext contains reserved field " + Constants.EC_PUBLIC_KEY_FIELD); } // make mutable context = new HashMap<>(context); context.put(Constants.EC_PUBLIC_KEY_FIELD, serializeTrailingKeyForEc(algo, trailingKeys)); } catch (final GeneralSecurityException ex) { throw new AwsCryptoException(ex); } } final MasterKeyRequest.Builder mkRequestBuilder = MasterKeyRequest.newBuilder(); mkRequestBuilder.setEncryptionContext(context); mkRequestBuilder.setStreaming(request.getPlaintextSize() == -1); if (request.getPlaintext() != null) { mkRequestBuilder.setPlaintext(request.getPlaintext()); } else { mkRequestBuilder.setSize(request.getPlaintextSize()); } @SuppressWarnings("unchecked") final List<MasterKey> mks = (List<MasterKey>) assertNonNull(mkp, "provider").getMasterKeysForEncryption(mkRequestBuilder.build()); if (mks.isEmpty()) { throw new IllegalArgumentException("No master keys provided"); } DataKey<?> dataKey = mks.get(0).generateDataKey(algo, context); List<KeyBlob> keyBlobs = new ArrayList<>(mks.size()); keyBlobs.add(new KeyBlob(dataKey)); for (int i = 1; i < mks.size(); i++) { //noinspection unchecked keyBlobs.add(new KeyBlob(mks.get(i).encryptDataKey(algo, context, dataKey))); } //noinspection unchecked return EncryptionMaterials.newBuilder() .setAlgorithm(algo) .setCleartextDataKey(dataKey.getKey()) .setEncryptedDataKeys(keyBlobs) .setEncryptionContext(context) .setTrailingSignatureKey(trailingKeys == null ? null : trailingKeys.getPrivate()) .setMasterKeys(mks) .build(); } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { DataKey<?> dataKey = mkp.decryptDataKey( request.getAlgorithm(), request.getEncryptedDataKeys(), request.getEncryptionContext()); if (dataKey == null) { throw new CannotUnwrapDataKeyException("Could not decrypt any data keys"); } PublicKey pubKey = null; if (request.getAlgorithm().getTrailingSignatureLength() > 0) { try { String serializedPubKey = request.getEncryptionContext().get(Constants.EC_PUBLIC_KEY_FIELD); if (serializedPubKey == null) { throw new AwsCryptoException("Missing trailing signature public key"); } pubKey = deserializeTrailingKeyFromEc(request.getAlgorithm(), serializedPubKey); } catch (final IllegalStateException ex) { throw new AwsCryptoException(ex); } } else if (request.getEncryptionContext().containsKey(Constants.EC_PUBLIC_KEY_FIELD)) { throw new AwsCryptoException("Trailing signature public key found for non-signed algorithm"); } return DecryptionMaterials.newBuilder() .setDataKey(dataKey) .setTrailingSignatureKey(pubKey) .build(); } private PublicKey deserializeTrailingKeyFromEc(CryptoAlgorithm algo, String pubKey) { return TrailingSignatureAlgorithm.forCryptoAlgorithm(algo).deserializePublicKey(pubKey); } private static String serializeTrailingKeyForEc(CryptoAlgorithm algo, KeyPair trailingKeys) { return TrailingSignatureAlgorithm.forCryptoAlgorithm(algo) .serializePublicKey(trailingKeys.getPublic()); } private static KeyPair generateTrailingSigKeyPair(CryptoAlgorithm algo) throws GeneralSecurityException { return TrailingSignatureAlgorithm.forCryptoAlgorithm(algo).generateKey(); } }
5,444
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/EncryptedDataKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; // @ model import java.util.Arrays; // @ model import java.nio.charset.StandardCharsets; // @ nullable_by_default public interface EncryptedDataKey { // @// An EncryptedDataKey object abstractly contains 3 pieces of data. // @// These are represented by 3 byte arrays: // @ model public instance byte[] providerId; // @ model public instance byte[] providerInformation; // @ model public instance byte[] encryptedDataKey; // @// The fields of an EncryptedDataKey may be populated via deserialization. The // @// Encryption SDK design allows the deserialization routine to be called repeatedly, // @// each call trying to fill in information that for some reason was not possible // @// with the previous call. In some such "intermediate" states, the deserialization // @// is incomplete in a way that other methods don't expect. Therefore, those methods // @// should not be called in these incomplete intermediate states. The model field // @// isDeserializing is true in those incomplete intermediate states, and it is used // @// in method specifications. // @ public model instance boolean isDeserializing; // @// There are some complications surrounding the representations of strings versus // @// byte arrays. The serialized form in message headers is always a sequence of // @// bytes, but the EncryptedDataKey interface (and some other methods) // @// expose the provider ID as if it were a string. Conversions (using UTF-8) // @// between byte arrays and strings (which in Java use UTF-16) are not bijections. // @// For example, both "\u003f".getBytes() and "\ud800".getBytes() yield a 1-byte // @// array containing [0x3f], and calling `new String(..., StandardCharsets.UTF_8)` // @// with either the 1-byte array [0x80] or the 3-byte array [0xef,0xbf,0xbd] yields // @// the string "\ufffd". Therefore, all we can say about these conversions // @// is that a given byte[]-String pair satisfies a conversion relation. // @// // @// The model functions "ba2s" and "s2ba" are used to specify the conversions // @// between byte arrays and strings: /*@ public normal_behavior @ requires s != null; @ ensures \result != null; @ function @ public model static byte[] s2ba(String s) { @ return s.getBytes(StandardCharsets.UTF_8); @ } @*/ /*@ public normal_behavior @ requires ba != null; @ ensures \result != null; @ function @ public model static String ba2s(byte[] ba) { @ return new String(ba, StandardCharsets.UTF_8); @ } @*/ // @// The "ba2s" and "s2ba" are given function bodies above, but the verification // @// does not rely on these function bodies directly. Instead, the code (in KeyBlob) // @// uses "assume" statements when it necessary to connect these functions with // @// copies of their bodies that appear in the code. This is a limitation of JML. // @// // @// One of the properties that holds of "s2ba(s)" is that its result depends not // @// on the particular String reference "s" being passed in, but only the contents // @// of the string referenced by "s". This property is captured in the following // @// lemma: /*@ public normal_behavior @ requires s != null && t != null && String.equals(s, t); @ ensures Arrays.equalArrays(s2ba(s), s2ba(t)); @ pure @ public model static void lemma_s2ba_depends_only_string_contents_only(String s, String t); @*/ // @// // @// As a specification convenience, the model function "ba2s2ba" uses the two // @// model functions above to convert from a byte array to a String and then back // @// to a byte array. As mentioned above, this does not always result in a byte // @// array with the original contents. The "assume" statements about the conversion // @// functions need to be careful not to assume too much. /*@ public normal_behavior @ requires ba != null; @ ensures \result == s2ba(ba2s(ba)); @ function @ public model static byte[] ba2s2ba(byte[] ba) { @ return s2ba(ba2s(ba)); @ } @*/ // @// Here follows 3 methods that access the abstract values of interface properties. // @// Something to note about these methods is that each one requires the property // @// requested to be known to be non-null. For example, "getProviderId" is only allowed // @// to be called when "providerId" is known to be non-null. // @ public normal_behavior // @ requires providerId != null; // @ ensures \result != null; // @ ensures String.equals(\result, ba2s(providerId)); // @ pure public String getProviderId(); // @ public normal_behavior // @ requires providerInformation != null; // @ ensures \fresh(\result); // @ ensures Arrays.equalArrays(providerInformation, \result); // @ pure public byte[] getProviderInformation(); // @ public normal_behavior // @ requires encryptedDataKey != null; // @ ensures \fresh(\result); // @ ensures Arrays.equalArrays(encryptedDataKey, \result); // @ pure public byte[] getEncryptedDataKey(); }
5,445
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/AwsCrypto.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.*; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; /** * Provides the primary entry-point to the AWS Encryption SDK. All encryption and decryption * operations should start here. Most people will want to use either {@link * #encryptData(MasterKeyProvider, byte[], Map)} and {@link #decryptData(MasterKeyProvider, byte[])} * to encrypt/decrypt things. * * <p>The core concepts (and classes) in this SDK are: * * <ul> * <li>{@link AwsCrypto} * <li>{@link DataKey} * <li>{@link MasterKey} * <li>{@link MasterKeyProvider} * </ul> * * <p>{@link AwsCrypto} provides the primary way to encrypt/decrypt data. It can operate on * byte-arrays, streams, or {@link java.lang.String Strings}. This data is encrypted using the * specifed {@link CryptoAlgorithm} and a {@link DataKey} which is unique to each encrypted message. * This {@code DataKey} is then encrypted using one (or more) {@link MasterKey MasterKeys}. The * process is reversed on decryption with the code selecting a copy of the {@code DataKey} protected * by a usable {@code MasterKey}, decrypting the {@code DataKey}, and then decrypted the message. * * <p>The main way to get a {@code MasterKey} is through the use of a {@link MasterKeyProvider}. * This provides a common interface for the AwsEncryptionSdk to find and retrieve {@code * MasterKeys}. (Some {@code MasterKeys} can also be constructed directly.) * * <p>{@code AwsCrypto} uses the {@code MasterKeyProvider} to determine which {@code MasterKeys} * should be used to encrypt the {@code DataKeys} by calling {@link * MasterKeyProvider#getMasterKeysForEncryption(MasterKeyRequest)} . When more than one {@code * MasterKey} is returned, the first {@code MasterKeys} is used to create the {@code DataKeys} by * calling {@link MasterKey#generateDataKey(CryptoAlgorithm,java.util.Map)} . All of the other * {@code MasterKeys} are then used to re-encrypt that {@code DataKey} with {@link * MasterKey#encryptDataKey(CryptoAlgorithm,java.util.Map,DataKey)} . This list of {@link * EncryptedDataKey EncryptedDataKeys} (the same {@code DataKey} possibly encrypted multiple times) * is stored in the {@link com.amazonaws.encryptionsdk.model.CiphertextHeaders}. * * <p>{@code AwsCrypto} also uses the {@code MasterKeyProvider} to decrypt one of the {@link * EncryptedDataKey EncryptedDataKeys} from the header to retrieve the actual {@code DataKey} * necessary to decrypt the message. * * <p>Any place a {@code MasterKeyProvider} is used, a {@link MasterKey} can be used instead. The * {@code MasterKey} will behave as a {@code MasterKeyProvider} which is only capable of providing * itself. This is often useful when only one {@code MasterKey} is being used. * * <p>Note regarding the use of generics: This library makes heavy use of generics to provide type * safety to advanced developers. The great majority of users should be able to just use the * provided type parameters or the {@code ?} wildcard. */ @SuppressWarnings("WeakerAccess") // this is a public API public class AwsCrypto { private static final Map<String, String> EMPTY_MAP = Collections.emptyMap(); // These are volatile because we allow unsynchronized writes via our setters, // and without setting volatile we could see strange results. // E.g. copying these to a local might give different values on subsequent reads from the local. // By setting them volatile we ensure that proper memory barriers are applied // to ensure things behave in a sensible manner. private volatile CryptoAlgorithm encryptionAlgorithm_ = null; private volatile int encryptionFrameSize_ = getDefaultFrameSize(); private static final CommitmentPolicy DEFAULT_COMMITMENT_POLICY = CommitmentPolicy.RequireEncryptRequireDecrypt; private final CommitmentPolicy commitmentPolicy_; /** * The maximum number of encrypted data keys to unwrap (resp. wrap) on decrypt (resp. encrypt), if * positive. If zero, do not limit EDKs. */ private final int maxEncryptedDataKeys_; private AwsCrypto(Builder builder) { commitmentPolicy_ = builder.commitmentPolicy_ == null ? DEFAULT_COMMITMENT_POLICY : builder.commitmentPolicy_; if (builder.encryptionAlgorithm_ != null && !commitmentPolicy_.algorithmAllowedForEncrypt(builder.encryptionAlgorithm_)) { if (commitmentPolicy_ == CommitmentPolicy.ForbidEncryptAllowDecrypt) { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only non-committed messages. Algorithm ID was " + builder.encryptionAlgorithm_ + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } else { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only committed messages. Algorithm ID was " + builder.encryptionAlgorithm_ + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } } encryptionAlgorithm_ = builder.encryptionAlgorithm_; encryptionFrameSize_ = builder.encryptionFrameSize_; maxEncryptedDataKeys_ = builder.maxEncryptedDataKeys_; } public static class Builder { private CryptoAlgorithm encryptionAlgorithm_; private int encryptionFrameSize_ = getDefaultFrameSize(); private CommitmentPolicy commitmentPolicy_; private int maxEncryptedDataKeys_ = CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS; private Builder() {} private Builder(final AwsCrypto client) { encryptionAlgorithm_ = client.encryptionAlgorithm_; encryptionFrameSize_ = client.encryptionFrameSize_; commitmentPolicy_ = client.commitmentPolicy_; maxEncryptedDataKeys_ = client.maxEncryptedDataKeys_; } /** * Sets the {@link CryptoAlgorithm} to encrypt with. The Aws Crypto client will use the last * crypto algorithm set with either {@link * AwsCrypto.Builder#withEncryptionAlgorithm(CryptoAlgorithm)} or {@link * #setEncryptionAlgorithm(CryptoAlgorithm)} to encrypt with. * * @param encryptionAlgorithm The {@link CryptoAlgorithm} * @return The Builder, for method chaining */ public Builder withEncryptionAlgorithm(CryptoAlgorithm encryptionAlgorithm) { this.encryptionAlgorithm_ = encryptionAlgorithm; return this; } /** * Sets the frame size of the encrypted messages that the Aws Crypto client produces. The Aws * Crypto client will use the last frame size set with either {@link * AwsCrypto.Builder#withEncryptionFrameSize(int)} or {@link #setEncryptionFrameSize(int)}. * * @param frameSize The frame size to produce encrypted messages with. * @return The Builder, for method chaining */ public Builder withEncryptionFrameSize(int frameSize) { this.encryptionFrameSize_ = frameSize; return this; } /** * Sets the {@link CommitmentPolicy} of this Aws Crypto client. * * @param commitmentPolicy The commitment policy to enforce during encryption and decryption * @return The Builder, for method chaining */ public Builder withCommitmentPolicy(CommitmentPolicy commitmentPolicy) { Utils.assertNonNull(commitmentPolicy, "commitmentPolicy"); this.commitmentPolicy_ = commitmentPolicy; return this; } /** * Sets the maximum number of encrypted data keys that this Aws Crypto client will wrap when * encrypting, or unwrap when decrypting, a single message. * * @param maxEncryptedDataKeys The maximum number of encrypted data keys; must be positive * @return The Builder, for method chaining */ public Builder withMaxEncryptedDataKeys(int maxEncryptedDataKeys) { if (maxEncryptedDataKeys < 1) { throw new IllegalArgumentException("maxEncryptedDataKeys must be positive"); } this.maxEncryptedDataKeys_ = maxEncryptedDataKeys; return this; } public AwsCrypto build() { return new AwsCrypto(this); } } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static AwsCrypto standard() { return AwsCrypto.builder().build(); } /** * Returns the frame size to use for encryption when none is explicitly selected. Currently it is * 4096. */ public static int getDefaultFrameSize() { return 4096; } /** * Sets the {@link CryptoAlgorithm} to use when <em>encrypting</em> data. This has no impact on * decryption. */ public void setEncryptionAlgorithm(final CryptoAlgorithm alg) { if (!commitmentPolicy_.algorithmAllowedForEncrypt(alg)) { if (commitmentPolicy_ == CommitmentPolicy.ForbidEncryptAllowDecrypt) { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only non-committed messages. Algorithm ID was " + alg + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } else { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only committed messages. Algorithm ID was " + alg + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } } encryptionAlgorithm_ = alg; } public CryptoAlgorithm getEncryptionAlgorithm() { return encryptionAlgorithm_; } /** * Sets the framing size to use when <em>encrypting</em> data. This has no impact on decryption. * If {@code frameSize} is 0, then framing is disabled and the entire plaintext will be encrypted * in a single block. * * <p>Note that during encryption arrays of this size will be allocated. Using extremely large * frame sizes may pose compatibility issues when the decryptor is running on 32-bit systems. * Additionally, Java VM limits may set a platform-specific upper bound to frame sizes. */ public void setEncryptionFrameSize(final int frameSize) { if (frameSize < 0) { throw new IllegalArgumentException("frameSize must be non-negative"); } encryptionFrameSize_ = frameSize; } public int getEncryptionFrameSize() { return encryptionFrameSize_; } /** * Returns the best estimate for the output length of encrypting a plaintext with the provided * {@code plaintextSize} and {@code encryptionContext}. The actual ciphertext may be shorter. * * <p>This method is equivalent to calling {@link #estimateCiphertextSize(CryptoMaterialsManager, * int, Map)} with a {@link DefaultCryptoMaterialsManager} based on the given provider. */ public <K extends MasterKey<K>> long estimateCiphertextSize( final MasterKeyProvider<K> provider, final int plaintextSize, final Map<String, String> encryptionContext) { return estimateCiphertextSize( new DefaultCryptoMaterialsManager(provider), plaintextSize, encryptionContext); } /** * Returns the best estimate for the output length of encrypting a plaintext with the provided * {@code plaintextSize} and {@code encryptionContext}. The actual ciphertext may be shorter. */ public long estimateCiphertextSize( CryptoMaterialsManager materialsManager, final int plaintextSize, final Map<String, String> encryptionContext) { EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(getEncryptionAlgorithm()) // We're not actually encrypting any data, so don't consume any bytes from the cache's // limits. We do need to // pass /something/ though, or the cache will be bypassed (as it'll assume this is a // streaming encrypt of // unknown size). .setPlaintextSize(0) .setCommitmentPolicy(commitmentPolicy_) .build(); final MessageCryptoHandler cryptoHandler = new EncryptionHandler( getEncryptionFrameSize(), checkAlgorithm(materialsManager.getMaterialsForEncrypt(request)), commitmentPolicy_); return cryptoHandler.estimateOutputSize(plaintextSize); } /** * Returns the equivalent to calling {@link #estimateCiphertextSize(MasterKeyProvider, int, Map)} * with an empty {@code encryptionContext}. */ public <K extends MasterKey<K>> long estimateCiphertextSize( final MasterKeyProvider<K> provider, final int plaintextSize) { return estimateCiphertextSize(provider, plaintextSize, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #estimateCiphertextSize(CryptoMaterialsManager, int, * Map)} with an empty {@code encryptionContext}. */ public long estimateCiphertextSize( final CryptoMaterialsManager materialsManager, final int plaintextSize) { return estimateCiphertextSize(materialsManager, plaintextSize, EMPTY_MAP); } /** * Returns an encrypted form of {@code plaintext} that has been protected with {@link DataKey * DataKeys} that are in turn protected by {@link MasterKey MasterKeys} provided by {@code * provider}. * * <p>This method is equivalent to calling {@link #encryptData(CryptoMaterialsManager, byte[], * Map)} using a {@link DefaultCryptoMaterialsManager} based on the given provider. */ public <K extends MasterKey<K>> CryptoResult<byte[], K> encryptData( final MasterKeyProvider<K> provider, final byte[] plaintext, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoResult<byte[], K>) encryptData(new DefaultCryptoMaterialsManager(provider), plaintext, encryptionContext); } /** * Returns an encrypted form of {@code plaintext} that has been protected with {@link DataKey * DataKeys} that are in turn protected by the given CryptoMaterialsProvider. */ public CryptoResult<byte[], ?> encryptData( CryptoMaterialsManager materialsManager, final byte[] plaintext, final Map<String, String> encryptionContext) { EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(getEncryptionAlgorithm()) .setPlaintext(plaintext) .setCommitmentPolicy(commitmentPolicy_) .build(); EncryptionMaterials encryptionMaterials = checkMaxEncryptedDataKeys(checkAlgorithm(materialsManager.getMaterialsForEncrypt(request))); final MessageCryptoHandler cryptoHandler = new EncryptionHandler(getEncryptionFrameSize(), encryptionMaterials, commitmentPolicy_); final int outSizeEstimate = cryptoHandler.estimateOutputSize(plaintext.length); final byte[] out = new byte[outSizeEstimate]; int outLen = cryptoHandler.processBytes(plaintext, 0, plaintext.length, out, 0).getBytesWritten(); outLen += cryptoHandler.doFinal(out, outLen); final byte[] outBytes = Utils.truncate(out, outLen); //noinspection unchecked return new CryptoResult(outBytes, cryptoHandler.getMasterKeys(), cryptoHandler.getHeaders()); } /** * Returns the equivalent to calling {@link #encryptData(MasterKeyProvider, byte[], Map)} with an * empty {@code encryptionContext}. */ public <K extends MasterKey<K>> CryptoResult<byte[], K> encryptData( final MasterKeyProvider<K> provider, final byte[] plaintext) { return encryptData(provider, plaintext, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #encryptData(CryptoMaterialsManager, byte[], Map)} * with an empty {@code encryptionContext}. */ public CryptoResult<byte[], ?> encryptData( final CryptoMaterialsManager materialsManager, final byte[] plaintext) { return encryptData(materialsManager, plaintext, EMPTY_MAP); } /** * Calls {@link #encryptData(MasterKeyProvider, byte[], Map)} on the UTF-8 encoded bytes of {@code * plaintext} and base64 encodes the result. * * @deprecated Use the {@link #encryptData(MasterKeyProvider, byte[], Map)} and {@link * #decryptData(MasterKeyProvider, byte[])} APIs instead. {@code encryptString} and {@code * decryptString} work as expected if you use them together. However, to work with other * language implementations of the AWS Encryption SDK, you need to base64-decode the output of * {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public <K extends MasterKey<K>> CryptoResult<String, K> encryptString( final MasterKeyProvider<K> provider, final String plaintext, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoResult<String, K>) encryptString(new DefaultCryptoMaterialsManager(provider), plaintext, encryptionContext); } /** * Calls {@link #encryptData(CryptoMaterialsManager, byte[], Map)} on the UTF-8 encoded bytes of * {@code plaintext} and base64 encodes the result. * * @deprecated Use the {@link #encryptData(CryptoMaterialsManager, byte[], Map)} and {@link * #decryptData(CryptoMaterialsManager, byte[])} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public CryptoResult<String, ?> encryptString( CryptoMaterialsManager materialsManager, final String plaintext, final Map<String, String> encryptionContext) { final CryptoResult<byte[], ?> ctBytes = encryptData( materialsManager, plaintext.getBytes(StandardCharsets.UTF_8), encryptionContext); return new CryptoResult<>( Utils.encodeBase64String(ctBytes.getResult()), ctBytes.getMasterKeys(), ctBytes.getHeaders()); } /** * Returns the equivalent to calling {@link #encryptString(MasterKeyProvider, String, Map)} with * an empty {@code encryptionContext}. * * @deprecated Use the {@link #encryptData(MasterKeyProvider, byte[])} and {@link * #decryptData(MasterKeyProvider, byte[])} APIs instead. {@code encryptString} and {@code * decryptString} work as expected if you use them together. However, to work with other * language implementations of the AWS Encryption SDK, you need to base64-decode the output of * {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public <K extends MasterKey<K>> CryptoResult<String, K> encryptString( final MasterKeyProvider<K> provider, final String plaintext) { return encryptString(provider, plaintext, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #encryptString(CryptoMaterialsManager, String, Map)} * with an empty {@code encryptionContext}. * * @deprecated Use the {@link #encryptData(CryptoMaterialsManager, byte[])} and {@link * #decryptData(CryptoMaterialsManager, byte[])} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public CryptoResult<String, ?> encryptString( final CryptoMaterialsManager materialsManager, final String plaintext) { return encryptString(materialsManager, plaintext, EMPTY_MAP); } /** * Decrypts the provided {@code ciphertext} by requesting that the {@code provider} unwrap any * usable {@link DataKey} in the ciphertext and then decrypts the ciphertext using that {@code * DataKey}. */ public <K extends MasterKey<K>> CryptoResult<byte[], K> decryptData( final MasterKeyProvider<K> provider, final byte[] ciphertext) { return decryptData( Utils.assertNonNull(provider, "provider"), new ParsedCiphertext(ciphertext, maxEncryptedDataKeys_)); } /** * Decrypts the provided ciphertext by delegating to the provided materialsManager to obtain the * decrypted {@link DataKey}. * * @param materialsManager the {@link CryptoMaterialsManager} to use for decryption operations. * @param ciphertext the ciphertext to attempt to decrypt. * @return the {@link CryptoResult} with the decrypted data. */ public CryptoResult<byte[], ?> decryptData( final CryptoMaterialsManager materialsManager, final byte[] ciphertext) { return decryptData( Utils.assertNonNull(materialsManager, "materialsManager"), new ParsedCiphertext(ciphertext, maxEncryptedDataKeys_)); } /** @see #decryptData(MasterKeyProvider, byte[]) */ @SuppressWarnings("unchecked") public <K extends MasterKey<K>> CryptoResult<byte[], K> decryptData( final MasterKeyProvider<K> provider, final ParsedCiphertext ciphertext) { Utils.assertNonNull(provider, "provider"); return (CryptoResult<byte[], K>) decryptData(new DefaultCryptoMaterialsManager(provider), ciphertext); } /** @see #decryptData(CryptoMaterialsManager, byte[]) */ public CryptoResult<byte[], ?> decryptData( final CryptoMaterialsManager materialsManager, final ParsedCiphertext ciphertext) { Utils.assertNonNull(materialsManager, "materialsManager"); final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, ciphertext, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); final byte[] ciphertextBytes = ciphertext.getCiphertext(); final int contentLen = ciphertextBytes.length - ciphertext.getOffset(); final int outSizeEstimate = cryptoHandler.estimateOutputSize(contentLen); final byte[] out = new byte[outSizeEstimate]; final ProcessingSummary processed = cryptoHandler.processBytes(ciphertextBytes, ciphertext.getOffset(), contentLen, out, 0); if (processed.getBytesProcessed() != contentLen) { throw new BadCiphertextException( "Unable to process entire ciphertext. May have trailing data."); } int outLen = processed.getBytesWritten(); outLen += cryptoHandler.doFinal(out, outLen); final byte[] outBytes = Utils.truncate(out, outLen); //noinspection unchecked return new CryptoResult(outBytes, cryptoHandler.getMasterKeys(), cryptoHandler.getHeaders()); } /** * Base64 decodes the {@code ciphertext} prior to decryption and then treats the results as a * UTF-8 encoded string. * * @see #decryptData(MasterKeyProvider, byte[]) * @deprecated Use the {@link #decryptData(MasterKeyProvider, byte[])} and {@link * #encryptData(MasterKeyProvider, byte[], Map)} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated @SuppressWarnings("unchecked") public <K extends MasterKey<K>> CryptoResult<String, K> decryptString( final MasterKeyProvider<K> provider, final String ciphertext) { return (CryptoResult<String, K>) decryptString(new DefaultCryptoMaterialsManager(provider), ciphertext); } /** * Base64 decodes the {@code ciphertext} prior to decryption and then treats the results as a * UTF-8 encoded string. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @deprecated Use the {@link #decryptData(CryptoMaterialsManager, byte[])} and {@link * #encryptData(CryptoMaterialsManager, byte[], Map)} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public CryptoResult<String, ?> decryptString( final CryptoMaterialsManager provider, final String ciphertext) { Utils.assertNonNull(provider, "provider"); final byte[] ciphertextBytes; try { ciphertextBytes = Utils.decodeBase64String(Utils.assertNonNull(ciphertext, "ciphertext")); } catch (final IllegalArgumentException ex) { throw new BadCiphertextException("Invalid base 64", ex); } final CryptoResult<byte[], ?> ptBytes = decryptData(provider, ciphertextBytes); //noinspection unchecked return new CryptoResult( new String(ptBytes.getResult(), StandardCharsets.UTF_8), ptBytes.getMasterKeys(), ptBytes.getHeaders()); } /** * Returns a {@link CryptoOutputStream} which encrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherOutputStream */ public <K extends MasterKey<K>> CryptoOutputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final OutputStream os, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoOutputStream<K>) createEncryptingStream(new DefaultCryptoMaterialsManager(provider), os, encryptionContext); } /** * Returns a {@link CryptoOutputStream} which encrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherOutputStream */ public CryptoOutputStream<?> createEncryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os, final Map<String, String> encryptionContext) { return new CryptoOutputStream<>( os, getEncryptingStreamHandler(materialsManager, encryptionContext)); } /** * Returns the equivalent to calling {@link #createEncryptingStream(MasterKeyProvider, * OutputStream, Map)} with an empty {@code encryptionContext}. */ public <K extends MasterKey<K>> CryptoOutputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final OutputStream os) { return createEncryptingStream(provider, os, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #createEncryptingStream(CryptoMaterialsManager, * OutputStream, Map)} with an empty {@code encryptionContext}. */ public CryptoOutputStream<?> createEncryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os) { return createEncryptingStream(materialsManager, os, EMPTY_MAP); } /** * Returns a {@link CryptoInputStream} which encrypts the data after reading it from the * underlying {@link InputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherInputStream */ public <K extends MasterKey<K>> CryptoInputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final InputStream is, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoInputStream<K>) createEncryptingStream(new DefaultCryptoMaterialsManager(provider), is, encryptionContext); } /** * Returns a {@link CryptoInputStream} which encrypts the data after reading it from the * underlying {@link InputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherInputStream */ public CryptoInputStream<?> createEncryptingStream( CryptoMaterialsManager materialsManager, final InputStream is, final Map<String, String> encryptionContext) { final MessageCryptoHandler cryptoHandler = getEncryptingStreamHandler(materialsManager, encryptionContext); return new CryptoInputStream<>(is, cryptoHandler); } /** * Returns the equivalent to calling {@link #createEncryptingStream(MasterKeyProvider, * InputStream, Map)} with an empty {@code encryptionContext}. */ public <K extends MasterKey<K>> CryptoInputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final InputStream is) { return createEncryptingStream(provider, is, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #createEncryptingStream(CryptoMaterialsManager, * InputStream, Map)} with an empty {@code encryptionContext}. */ public CryptoInputStream<?> createEncryptingStream( final CryptoMaterialsManager materialsManager, final InputStream is) { return createEncryptingStream(materialsManager, is, EMPTY_MAP); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. This version only accepts unsigned messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see javax.crypto.CipherOutputStream */ public <K extends MasterKey<K>> CryptoOutputStream<K> createUnsignedMessageDecryptingStream( final MasterKeyProvider<K> provider, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream<K>(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. This version only accepts unsigned messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see javax.crypto.CipherInputStream */ public <K extends MasterKey<K>> CryptoInputStream<K> createUnsignedMessageDecryptingStream( final MasterKeyProvider<K> provider, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream<K>(is, cryptoHandler); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. This version only accepts unsigned messages. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @see javax.crypto.CipherOutputStream */ public CryptoOutputStream<?> createUnsignedMessageDecryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. This version only accepts unsigned messages. * * @see #encryptData(CryptoMaterialsManager, byte[], Map) * @see javax.crypto.CipherInputStream */ public CryptoInputStream<?> createUnsignedMessageDecryptingStream( final CryptoMaterialsManager materialsManager, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream(is, cryptoHandler); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been released to the underlying {@link * OutputStream}! This behavior can be avoided by using the non-streaming * #decryptData(MasterKeyProvider, byte[]) method instead, or * #createUnsignedMessageDecryptingStream(MasterKeyProvider, OutputStream) if you do not need to * decrypt signed messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see #createUnsignedMessageDecryptingStream(MasterKeyProvider, OutputStream) * @see javax.crypto.CipherOutputStream */ public <K extends MasterKey<K>> CryptoOutputStream<K> createDecryptingStream( final MasterKeyProvider<K> provider, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream<K>(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been produced from the {@link InputStream}! * This behavior can be avoided by using the non-streaming #decryptData(MasterKeyProvider, byte[]) * method instead, or #createUnsignedMessageDecryptingStream(MasterKeyProvider, InputStream) if * you do not need to decrypt signed messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see #createUnsignedMessageDecryptingStream(MasterKeyProvider, InputStream) * @see javax.crypto.CipherInputStream */ public <K extends MasterKey<K>> CryptoInputStream<K> createDecryptingStream( final MasterKeyProvider<K> provider, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream<K>(is, cryptoHandler); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been released to the underlying {@link * OutputStream}! This behavior can be avoided by using the non-streaming * #decryptData(CryptoMaterialsManager, byte[]) method instead, or * #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, OutputStream) if you do not need * to decrypt signed messages. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @see #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, OutputStream) * @see javax.crypto.CipherOutputStream */ public CryptoOutputStream<?> createDecryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been produced from the {@link InputStream}! * This behavior can be avoided by using the non-streaming #decryptData(CryptoMaterialsManager, * byte[]) method instead, or #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, * InputStream) if you do not need to decrypt signed messages. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @see #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, InputStream) * @see javax.crypto.CipherInputStream */ public CryptoInputStream<?> createDecryptingStream( final CryptoMaterialsManager materialsManager, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream(is, cryptoHandler); } private MessageCryptoHandler getEncryptingStreamHandler( CryptoMaterialsManager materialsManager, Map<String, String> encryptionContext) { Utils.assertNonNull(materialsManager, "materialsManager"); Utils.assertNonNull(encryptionContext, "encryptionContext"); EncryptionMaterialsRequest.Builder requestBuilder = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(getEncryptionAlgorithm()) .setCommitmentPolicy(commitmentPolicy_); return new LazyMessageCryptoHandler( info -> { // Hopefully we know the input size now, so we can pass it along to the CMM. if (info.getMaxInputSize() != -1) { requestBuilder.setPlaintextSize(info.getMaxInputSize()); } return new EncryptionHandler( getEncryptionFrameSize(), checkMaxEncryptedDataKeys( checkAlgorithm(materialsManager.getMaterialsForEncrypt(requestBuilder.build()))), commitmentPolicy_); }); } private EncryptionMaterials checkAlgorithm(EncryptionMaterials result) { if (encryptionAlgorithm_ != null && result.getAlgorithm() != encryptionAlgorithm_) { throw new AwsCryptoException( String.format( "Materials manager ignored requested algorithm; algorithm %s was set on AwsCrypto " + "but %s was selected", encryptionAlgorithm_, result.getAlgorithm())); } return result; } private EncryptionMaterials checkMaxEncryptedDataKeys(EncryptionMaterials materials) { if (maxEncryptedDataKeys_ > 0 && materials.getEncryptedDataKeys().size() > maxEncryptedDataKeys_) { throw new AwsCryptoException("Encrypted data keys exceed maxEncryptedDataKeys"); } return materials; } }
5,446
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoAlgorithm.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.CommittedKey; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.HmacKeyDerivationFunction; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Describes the cryptographic algorithms available for use in this library. * * <p>Format: CryptoAlgorithm(block size, nonce length, tag length, max content length, key algo, * key length, short value representing this algorithm, trailing signature alg, trailing signature * length) */ public enum CryptoAlgorithm { /** AES-GCM 128 */ ALG_AES_128_GCM_IV12_TAG16_NO_KDF( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 16, 0x0014, "AES", 16, false), /** AES-GCM 192 */ ALG_AES_192_GCM_IV12_TAG16_NO_KDF( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 24, 0x0046, "AES", 24, false), /** AES-GCM 256 */ ALG_AES_256_GCM_IV12_TAG16_NO_KDF( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 32, 0x0078, "AES", 32, false), /** AES-GCM 128 with HKDF-SHA256 */ ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 16, 0x0114, "HkdfSHA256", 16, true), /** AES-GCM 192 */ ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 24, 0x0146, "HkdfSHA256", 24, true), /** AES-GCM 256 */ ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 32, 0x0178, "HkdfSHA256", 32, true), /** AES-GCM 128 with ECDSA (SHA256 with the secp256r1 curve) */ ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 16, 0x0214, "HkdfSHA256", 16, true, "SHA256withECDSA", 71), /** AES-GCM 192 with ECDSA (SHA384 with the secp384r1 curve) */ ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 24, 0x0346, "HkdfSHA384", 24, true, "SHA384withECDSA", 103), /** AES-GCM 256 with ECDSA (SHA384 with the secp384r1 curve) */ ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384( 1, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 32, 0x0378, "HkdfSHA384", 32, true, "SHA384withECDSA", 103), /** * AES-GCM 256 with key commitment Note: 1.7.0 of this library only supports decryption of using * this crypto algorithm and does not support encryption with this algorithm */ ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY( 2, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 32, 0x0478, "HkdfSHA512", 32, true, null, 0, "HkdfSHA512", 32, 32, 32), /** * AES-GCM 256 with ECDSA (SHA384 with the secp384r1 curve) and key commitment Note: 1.7.0 of this * library only supports decryption of using this crypto algorithm and does not support encryption * with this algorithm */ ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384( 2, 128, 12, 16, Constants.GCM_MAX_CONTENT_LEN, "AES", 32, 0x0578, "HkdfSHA512", 32, true, "SHA384withECDSA", 103, "HkdfSHA512", 32, 32, 32); private final byte messageFormatVersion_; private final int blockSizeBits_; private final byte nonceLenBytes_; private final int tagLenBytes_; private final long maxContentLen_; private final String keyAlgo_; private final int keyLenBytes_; private final short value_; private final String trailingSigAlgo_; private final short trailingSigLen_; private final String dataKeyAlgo_; private final int dataKeyLen_; private final boolean safeToCache_; private final String keyCommitmentAlgo_; private final int commitmentLength_; private final int commitmentNonceLength_; private final int suiteDataLength_; private static final byte VERSION_1 = (byte) 1; private static final byte VERSION_2 = (byte) 2; private static final int VERSION_1_MESSAGE_ID_LEN = 16; private static final int VERSION_2_MESSAGE_ID_LEN = 32; /* * Create a mapping between the CiphertextType object and its byte value representation. Make * this a static method so the map is created when the object is created. This enables fast * lookups of the CryptoAlgorithm given its short value representation and message format version. */ private static final Map<Integer, CryptoAlgorithm> ID_MAPPING = new HashMap<>(); static { for (final CryptoAlgorithm s : EnumSet.allOf(CryptoAlgorithm.class)) { ID_MAPPING.put(fieldsToLookupKey(s.messageFormatVersion_, s.value_), s); } } CryptoAlgorithm( final int messageFormatVersion, final int blockSizeBits, final int nonceLenBytes, final int tagLenBytes, final long maxContentLen, final String keyAlgo, final int keyLenBytes, final int value, final String dataKeyAlgo, final int dataKeyLen, boolean safeToCache) { this( messageFormatVersion, blockSizeBits, nonceLenBytes, tagLenBytes, maxContentLen, keyAlgo, keyLenBytes, value, dataKeyAlgo, dataKeyLen, safeToCache, null, 0); } CryptoAlgorithm( final int messageFormatVersion, final int blockSizeBits, final int nonceLenBytes, final int tagLenBytes, final long maxContentLen, final String keyAlgo, final int keyLenBytes, final int value, final String dataKeyAlgo, final int dataKeyLen, boolean safeToCache, final String trailingSignatureAlgo, final int trailingSignatureLength) { this( messageFormatVersion, blockSizeBits, nonceLenBytes, tagLenBytes, maxContentLen, keyAlgo, keyLenBytes, value, dataKeyAlgo, dataKeyLen, safeToCache, trailingSignatureAlgo, trailingSignatureLength, null, 0, 0, 0); } CryptoAlgorithm( final int messageFormatVersion, final int blockSizeBits, final int nonceLenBytes, final int tagLenBytes, final long maxContentLen, final String keyAlgo, final int keyLenBytes, final int value, final String dataKeyAlgo, final int dataKeyLen, boolean safeToCache, final String trailingSignatureAlgo, final int trailingSignatureLength, final String keyCommitmentAlgo, final int commitmentLength, final int commitmentNonceLength, final int suiteDataLength) { if ((messageFormatVersion & 0xFF) != messageFormatVersion) { throw new IllegalArgumentException("Invalid messageFormatVersion: " + messageFormatVersion); } // All non-null key commitment algs must be the same as the kdf alg if (keyCommitmentAlgo != null && !keyCommitmentAlgo.equals(dataKeyAlgo)) { throw new IllegalArgumentException( "Invalid keyCommitmentAlgo " + keyCommitmentAlgo + ". Must be equal to dataKeyAlgo " + dataKeyAlgo + "."); } messageFormatVersion_ = (byte) (messageFormatVersion & 0xFF); blockSizeBits_ = blockSizeBits; nonceLenBytes_ = (byte) nonceLenBytes; tagLenBytes_ = tagLenBytes; keyAlgo_ = keyAlgo; keyLenBytes_ = keyLenBytes; maxContentLen_ = maxContentLen; safeToCache_ = safeToCache; if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) { throw new IllegalArgumentException("Invalid value " + value); } value_ = (short) value; dataKeyAlgo_ = dataKeyAlgo; dataKeyLen_ = dataKeyLen; trailingSigAlgo_ = trailingSignatureAlgo; if (trailingSignatureLength > Short.MAX_VALUE || trailingSignatureLength < 0) { throw new IllegalArgumentException("Invalid value " + trailingSignatureLength); } trailingSigLen_ = (short) trailingSignatureLength; keyCommitmentAlgo_ = keyCommitmentAlgo; commitmentLength_ = commitmentLength; commitmentNonceLength_ = commitmentNonceLength; suiteDataLength_ = suiteDataLength; } private static int fieldsToLookupKey(final byte messageFormatVersion, final short algorithmId) { // We pack the message format version and algorithm id into a single value. // Since the algorithm ID is a short and thus 16 bits long, we'll just // left shift the message format version by that amount. // The message format version is 8 bits, so this totals 24 bits and fits // within a standard 32 bit integer. return (messageFormatVersion << 16) | algorithmId; } /** * Returns the CryptoAlgorithm object that matches the given value assuming a message format * version of 1. * * @param value the value of the object * @return the CryptoAlgorithm object that matches the given value, null if no match is found. * @deprecated See {@link #deserialize(byte, short)} */ public static CryptoAlgorithm deserialize(final byte messageFormatVersion, final short value) { return ID_MAPPING.get(fieldsToLookupKey(messageFormatVersion, value)); } /** Returns the length of the message Id in the header for this algorithm. */ public int getMessageIdLength() { // For now this is a derived value rather than stored explicitly switch (messageFormatVersion_) { case VERSION_1: return VERSION_1_MESSAGE_ID_LEN; case VERSION_2: return VERSION_2_MESSAGE_ID_LEN; default: throw new UnsupportedOperationException( "Support for version " + messageFormatVersion_ + " not yet built."); } } /** * Returns the header nonce to use with this algorithm. null indicates that the header nonce is * not a parameter of the algorithm, and is instead stored as part of the message header. */ public byte[] getHeaderNonce() { // For now this is a derived value rather than stored explicitly switch (messageFormatVersion_) { case VERSION_1: return null; case VERSION_2: // V2 explicitly uses an IV of 0 in the header return new byte[nonceLenBytes_]; default: throw new UnsupportedOperationException( "Support for version " + messageFormatVersion_ + " not yet built."); } } /** Returns the message format version associated with this algorithm suite. */ public byte getMessageFormatVersion() { return messageFormatVersion_; } /** Returns the block size of this algorithm in bytes. */ public int getBlockSize() { return blockSizeBits_ / 8; } /** Returns the nonce length used in this algorithm in bytes. */ public byte getNonceLen() { return nonceLenBytes_; } /** Returns the tag length used in this algorithm in bytes. */ public int getTagLen() { return tagLenBytes_; } /** * Returns the maximum content length in bytes that can be processed under a single data key in * this algorithm. */ public long getMaxContentLen() { return maxContentLen_; } /** Returns the algorithm used for encrypting the plaintext data. */ public String getKeyAlgo() { return keyAlgo_; } /** Returns the length of the key used in this algorithm in bytes. */ public int getKeyLength() { return keyLenBytes_; } /** Returns the value used to encode this algorithm in the ciphertext. */ public short getValue() { return value_; } /** Returns the algorithm associated with the data key. */ public String getDataKeyAlgo() { return dataKeyAlgo_; } /** Returns the length of the data key in bytes. */ public int getDataKeyLength() { return dataKeyLen_; } /** Returns the algorithm used to calculate the trailing signature */ public String getTrailingSignatureAlgo() { return trailingSigAlgo_; } /** * Returns whether data keys used with this crypto algorithm can safely be cached and reused for a * different message. If this returns false, reuse of data keys is likely to result in severe * cryptographic weaknesses, potentially even with only a single such use. */ public boolean isSafeToCache() { return safeToCache_; } /** * Returns the length of the trailing signature generated by this algorithm. The actual trailing * signature may be shorter than this. */ public short getTrailingSignatureLength() { return trailingSigLen_; } public String getKeyCommitmentAlgo_() { return keyCommitmentAlgo_; } /** * Returns a derived value of whether a commitment value is generated with the key in order to * ensure key commitment. */ public boolean isCommitting() { return keyCommitmentAlgo_ != null; } public int getCommitmentLength() { return commitmentLength_; } public int getCommitmentNonceLength() { return commitmentNonceLength_; } public int getSuiteDataLength() { return suiteDataLength_; } public SecretKey getEncryptionKeyFromDataKey( final SecretKey dataKey, final CiphertextHeaders headers) throws InvalidKeyException { if (!dataKey.getAlgorithm().equalsIgnoreCase(getDataKeyAlgo())) { throw new InvalidKeyException( "DataKey of incorrect algorithm. Expected " + getDataKeyAlgo() + " but was " + dataKey.getAlgorithm()); } // We perform key derivation differently depending on the message format version switch (messageFormatVersion_) { case VERSION_1: return getNonCommittedEncryptionKey(dataKey, headers); case VERSION_2: return getCommittedEncryptionKey(dataKey, headers); default: throw new UnsupportedOperationException( "Support for message format version " + messageFormatVersion_ + " not yet built."); } } private SecretKey getCommittedEncryptionKey( final SecretKey dataKey, final CiphertextHeaders headers) throws InvalidKeyException { final CommittedKey committedKey = CommittedKey.generate(this, dataKey, headers.getMessageId()); if (!MessageDigest.isEqual(committedKey.getCommitment(), headers.getSuiteData())) { throw new BadCiphertextException( "Key commitment validation failed. Key identity does not match the " + "identity asserted in the message. Halting processing of this message."); } return committedKey.getKey(); } private SecretKey getNonCommittedEncryptionKey( final SecretKey dataKey, final CiphertextHeaders headers) throws InvalidKeyException { final String macAlgorithm; switch (this) { case ALG_AES_128_GCM_IV12_TAG16_NO_KDF: case ALG_AES_192_GCM_IV12_TAG16_NO_KDF: case ALG_AES_256_GCM_IV12_TAG16_NO_KDF: return dataKey; case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256: case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256: case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256: case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256: macAlgorithm = "HmacSHA256"; break; case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384: case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384: macAlgorithm = "HmacSHA384"; break; default: throw new UnsupportedOperationException("Support for " + this + " not yet built."); } if (!dataKey.getFormat().equalsIgnoreCase("RAW")) { throw new InvalidKeyException( "Currently only RAW format keys are supported for HKDF algorithms. Actual format was " + dataKey.getFormat()); } final byte[] messageId = headers.getMessageId(); final ByteBuffer info = ByteBuffer.allocate(messageId.length + 2); info.order(ByteOrder.BIG_ENDIAN); info.putShort(getValue()); info.put(messageId); final byte[] rawDataKey = dataKey.getEncoded(); if (rawDataKey.length != getDataKeyLength()) { throw new InvalidKeyException( "DataKey of incorrect length. Expected " + getDataKeyLength() + " but was " + rawDataKey.length); } final HmacKeyDerivationFunction hkdf; try { hkdf = HmacKeyDerivationFunction.getInstance(macAlgorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } hkdf.init(rawDataKey); return new SecretKeySpec(hkdf.deriveKey(info.array(), getKeyLength()), getKeyAlgo()); } }
5,447
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CommitmentPolicy.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; /** * Governs how a AwsCrypto behaves during configuration, encryption, and decryption, with respect to * key commitment. */ public enum CommitmentPolicy { /** * On encrypty, algorithm suite must NOT support key commitment; On decrypt, if a key commitment * is present on the ciphertext, then the key commitment must be valid. Key commitment will NOT be * included in ciphertext on encrypt. */ ForbidEncryptAllowDecrypt, /** * On encrypt, algorithm suite must support key commitment; On decrypt, if a key commitment is * present on the ciphertext, then the key commitment must be valid. Key commitment will be * included in ciphertext on encrypt. */ RequireEncryptAllowDecrypt, /** * Algorithm suite must support key commitment. Key commitment will be included in ciphertext on * encrypt. Valid key commitment must be present in ciphertext on decrypt. */ RequireEncryptRequireDecrypt; /** Validates that an algorithm meets the Policy's On encrypt key commitment. */ public boolean algorithmAllowedForEncrypt(CryptoAlgorithm algorithm) { switch (this) { case ForbidEncryptAllowDecrypt: return !algorithm.isCommitting(); case RequireEncryptAllowDecrypt: case RequireEncryptRequireDecrypt: return algorithm.isCommitting(); default: throw new UnsupportedOperationException( "Support for commitment policy " + this + " not yet built."); } } /** Validates that an algorithm meets the Policy's On decrypt key commitment. */ public boolean algorithmAllowedForDecrypt(CryptoAlgorithm algorithm) { switch (this) { case ForbidEncryptAllowDecrypt: case RequireEncryptAllowDecrypt: return true; case RequireEncryptRequireDecrypt: return algorithm.isCommitting(); default: throw new UnsupportedOperationException( "Support for commitment policy " + this + " not yet built."); } } }
5,448
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/package-info.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ /** * Contains {@link com.amazonaws.encryptionsdk.AwsCrypto}, the primary entry-point to the Aws * Encryption SDK. */ package com.amazonaws.encryptionsdk;
5,449
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/KmsMethods.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.kms; import java.util.List; /** Methods common to all classes which interact with KMS. */ public interface KmsMethods { /** Sets the {@code grantTokens} which should be submitted to KMS when calling it. */ public void setGrantTokens(List<String> grantTokens); /** Returns the grantTokens which this object sends to KMS when calling it. */ public List<String> getGrantTokens(); /** Adds {@code grantToken} to the list of grantTokens sent to KMS when this class calls it. */ public void addGrantToken(String grantToken); }
5,450
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/DiscoveryFilter.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; /** * This class stores the configuration for filtering AWS KMS CMK ARNs by AWS account ID and * partition. * * <p>The filter allows a KMS CMK if its partition matches {@code partition} and its accountId is * included in {@code accountIds}. */ public final class DiscoveryFilter { private final String partition_; private final Collection<String> accountIds_; public DiscoveryFilter(String partition, String... accountIds) { this(partition, Arrays.asList(accountIds)); } public DiscoveryFilter(String partition, Collection<String> accountIds) { if (partition == null || partition.isEmpty()) { throw new IllegalArgumentException( "Discovery filter cannot be configured without " + "a partition."); } else if (accountIds == null || accountIds.isEmpty()) { throw new IllegalArgumentException( "Discovery filter cannot be configured without " + "account IDs."); } else if (accountIds.contains(null) || accountIds.contains("")) { throw new IllegalArgumentException( "Discovery filter cannot be configured with " + "null or empty account IDs."); } partition_ = partition; accountIds_ = new HashSet<String>(accountIds); } public String getPartition() { return partition_; } public Collection<String> getAccountIds() { return Collections.unmodifiableSet(new HashSet<>(accountIds_)); } public boolean allowsPartitionAndAccount(String partition, String accountId) { return (partition_.equals(partition) && accountIds_.contains(accountId)); } }
5,451
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/KmsMasterKeyProvider.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import com.amazonaws.AmazonServiceException; import com.amazonaws.Request; import com.amazonaws.Response; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.MasterKeyRequest; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo; import com.amazonaws.handlers.RequestHandler2; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClient; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; /** * Provides {@link MasterKey}s backed by the AWS Key Management Service. This object is regional and * if you want to use keys from multiple regions, you'll need multiple copies of this object. * * <p>This component is not multi-Region key aware, and will treat every AWS KMS identifier as * regionally isolated. */ public class KmsMasterKeyProvider extends MasterKeyProvider<KmsMasterKey> implements KmsMethods { private static final String PROVIDER_NAME = "aws-kms"; private final List<String> keyIds_; private final List<String> grantTokens_; private final boolean isDiscovery_; private final DiscoveryFilter discoveryFilter_; private final RegionalClientSupplier regionalClientSupplier_; private final String defaultRegion_; @FunctionalInterface public interface RegionalClientSupplier { /** * Supplies an AWSKMS instance to use for a given region. The {@link KmsMasterKeyProvider} will * not cache the result of this function. * * @param regionName The region to get a client for * @return The client to use, or null if this region cannot or should not be used. */ AWSKMS getClient(String regionName); } public static class Builder implements Cloneable { private String defaultRegion_ = null; private RegionalClientSupplier regionalClientSupplier_ = null; private AWSKMSClientBuilder templateBuilder_ = null; private DiscoveryFilter discoveryFilter_ = null; Builder() { // Default access: Don't allow outside classes to extend this class } public Builder clone() { try { Builder cloned = (Builder) super.clone(); if (templateBuilder_ != null) { cloned.templateBuilder_ = cloneClientBuilder(templateBuilder_); } return cloned; } catch (CloneNotSupportedException e) { throw new Error("Impossible: CloneNotSupportedException", e); } } /** * Sets the default region. This region will be used when specifying key IDs for encryption or * in {@link KmsMasterKeyProvider#getMasterKey(String)} that are not full ARNs, but are instead * bare key IDs or aliases. * * <p>If the default region is not specified, only full key ARNs will be usable. * * @param defaultRegion The default region to use. * @return */ public Builder withDefaultRegion(String defaultRegion) { this.defaultRegion_ = defaultRegion; return this; } /** * Provides a custom factory function that will vend KMS clients. This is provided for advanced * use cases which require complete control over the client construction process. * * <p>Because the regional client supplier fully controls the client construction process, it is * not possible to configure the client through methods such as {@link * #withCredentials(AWSCredentialsProvider)} or {@link #withClientBuilder(AWSKMSClientBuilder)}; * if you try to use these in combination, an {@link IllegalStateException} will be thrown. * * @param regionalClientSupplier * @return */ public Builder withCustomClientFactory(RegionalClientSupplier regionalClientSupplier) { if (templateBuilder_ != null) { throw clientSupplierComboException(); } regionalClientSupplier_ = regionalClientSupplier; return this; } private RuntimeException clientSupplierComboException() { return new IllegalStateException( "withCustomClientFactory cannot be used in conjunction with " + "withCredentials or withClientBuilder"); } /** * Configures the {@link KmsMasterKeyProvider} to use specific credentials. If a builder was * previously set, this will override whatever credentials it set. * * @param credentialsProvider * @return */ public Builder withCredentials(AWSCredentialsProvider credentialsProvider) { if (regionalClientSupplier_ != null) { throw clientSupplierComboException(); } if (templateBuilder_ == null) { templateBuilder_ = AWSKMSClientBuilder.standard(); } templateBuilder_.setCredentials(credentialsProvider); return this; } /** * Configures the {@link KmsMasterKeyProvider} to use specific credentials. If a builder was * previously set, this will override whatever credentials it set. * * @param credentials * @return */ public Builder withCredentials(AWSCredentials credentials) { return withCredentials(new AWSStaticCredentialsProvider(credentials)); } /** * Configures the {@link KmsMasterKeyProvider} to use settings from this {@link * AWSKMSClientBuilder} to configure KMS clients. Note that the region set on this builder will * be ignored, but all other settings will be propagated into the regional clients. * * <p>This method will overwrite any credentials set using {@link * #withCredentials(AWSCredentialsProvider)}. * * @param builder * @return */ public Builder withClientBuilder(AWSKMSClientBuilder builder) { if (regionalClientSupplier_ != null) { throw clientSupplierComboException(); } final AWSKMSClientBuilder newBuilder = cloneClientBuilder(builder); this.templateBuilder_ = newBuilder; return this; } AWSKMSClientBuilder cloneClientBuilder(final AWSKMSClientBuilder builder) { // We need to copy all arguments out of the builder in case it's mutated later on. // Unfortunately AWSKMSClientBuilder doesn't support .clone() so we'll have to do it by hand. if (builder.getEndpoint() != null) { // We won't be able to set the region later if a custom endpoint is set. throw new IllegalArgumentException( "Setting endpoint configuration is not compatible with passing a " + "builder to the KmsMasterKeyProvider. Use withCustomClientFactory" + " instead."); } final AWSKMSClientBuilder newBuilder = AWSKMSClient.builder(); newBuilder.setClientConfiguration(builder.getClientConfiguration()); newBuilder.setCredentials(builder.getCredentials()); newBuilder.setEndpointConfiguration(builder.getEndpoint()); newBuilder.setMetricsCollector(builder.getMetricsCollector()); if (builder.getRequestHandlers() != null) { newBuilder.setRequestHandlers(builder.getRequestHandlers().toArray(new RequestHandler2[0])); } return newBuilder; } /** * Builds the master key provider in Discovery Mode. In Discovery Mode the KMS Master Key * Provider will attempt to decrypt using any key identifier it discovers in the encrypted * message. KMS Master Key Providers in Discovery Mode will not encrypt data keys. * * @return */ public KmsMasterKeyProvider buildDiscovery() { final boolean isDiscovery = true; RegionalClientSupplier supplier = clientFactory(); return new KmsMasterKeyProvider( supplier, defaultRegion_, emptyList(), emptyList(), isDiscovery, discoveryFilter_); } /** * Builds the master key provider in Discovery Mode with a {@link DiscoveryFilter}. In Discovery * Mode the KMS Master Key Provider will attempt to decrypt using any key identifier it * discovers in the encrypted message that is accepted by the {@code filter}. KMS Master Key * Providers in Discovery Mode will not encrypt data keys. * * @param filter * @return */ public KmsMasterKeyProvider buildDiscovery(DiscoveryFilter filter) { if (filter == null) { throw new IllegalArgumentException( "Discovery filter must not be null if specifying " + "a discovery filter."); } discoveryFilter_ = filter; return buildDiscovery(); } /** * Builds the master key provider in Strict Mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For providers that will only be used * for encryption, you can use any valid KMS key identifier. For providers that will be used for * decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not supported. * * @param keyIds * @return */ public KmsMasterKeyProvider buildStrict(List<String> keyIds) { if (keyIds == null) { throw new IllegalArgumentException( "Strict mode must be configured with a non-empty " + "list of keyIds."); } final boolean isDiscovery = false; RegionalClientSupplier supplier = clientFactory(); return new KmsMasterKeyProvider( supplier, defaultRegion_, new ArrayList<String>(keyIds), emptyList(), isDiscovery, null); } /** * Builds the master key provider in strict mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For providers that will only be used * for encryption, you can use any valid KMS key identifier. For providers that will be used for * decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not supported. * * @param keyIds * @return */ public KmsMasterKeyProvider buildStrict(String... keyIds) { return buildStrict(asList(keyIds)); } RegionalClientSupplier clientFactory() { if (regionalClientSupplier_ != null) { return regionalClientSupplier_; } // Clone again; this MKP builder might be reused to build a second MKP with different creds. AWSKMSClientBuilder builder = templateBuilder_ != null ? cloneClientBuilder(templateBuilder_) : AWSKMSClientBuilder.standard(); ConcurrentHashMap<String, AWSKMS> clientCache = new ConcurrentHashMap<>(); snoopClientCache(clientCache); return region -> { AWSKMS kms = clientCache.get(region); if (kms != null) return kms; // We can't just use computeIfAbsent as we need to avoid leaking KMS clients if we're asked // to decrypt // an EDK with a bogus region in its ARN. So we'll install a request handler to identify the // first // successful call, and cache it when we see that. SuccessfulRequestCacher cacher = new SuccessfulRequestCacher(clientCache, region); ArrayList<RequestHandler2> handlers = new ArrayList<>(); if (builder.getRequestHandlers() != null) { handlers.addAll(builder.getRequestHandlers()); } handlers.add(cacher); kms = cloneClientBuilder(builder) .withRegion(region) .withRequestHandlers(handlers.toArray(new RequestHandler2[handlers.size()])) .build(); return cacher.setClient(kms); }; } protected void snoopClientCache(ConcurrentHashMap<String, AWSKMS> map) { // no-op - this is a test hook } } static class SuccessfulRequestCacher extends RequestHandler2 { private final ConcurrentHashMap<String, AWSKMS> cache_; private final String region_; private AWSKMS client_; volatile boolean ranBefore_ = false; SuccessfulRequestCacher(final ConcurrentHashMap<String, AWSKMS> cache, final String region) { this.region_ = region; this.cache_ = cache; } public AWSKMS setClient(final AWSKMS client) { client_ = client; return client; } @Override public void afterResponse(final Request<?> request, final Response<?> response) { if (ranBefore_) return; ranBefore_ = true; cache_.putIfAbsent(region_, client_); } @Override public void afterError( final Request<?> request, final Response<?> response, final Exception e) { if (ranBefore_) return; if (e instanceof AmazonServiceException) { ranBefore_ = true; cache_.putIfAbsent(region_, client_); } } } public static Builder builder() { return new Builder(); } KmsMasterKeyProvider( RegionalClientSupplier supplier, String defaultRegion, List<String> keyIds, List<String> grantTokens, boolean isDiscovery, DiscoveryFilter discoveryFilter) { if (!isDiscovery && (keyIds == null || keyIds.isEmpty())) { throw new IllegalArgumentException( "Strict mode must be configured with a non-empty " + "list of keyIds."); } if (!isDiscovery && keyIds.contains(null)) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "null key identifier."); } if (!isDiscovery && discoveryFilter != null) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "discovery filter."); } // If we don't have a default region, we need to check that all key IDs will be usable if (!isDiscovery && defaultRegion == null) { for (String keyId : keyIds) { final AwsKmsCmkArnInfo arnInfo = parseInfoFromKeyArn(keyId); if (arnInfo == null) { throw new AwsCryptoException( "Can't use non-ARN key identifiers or aliases when " + "no default region is set"); } } } this.regionalClientSupplier_ = supplier; this.defaultRegion_ = defaultRegion; this.keyIds_ = Collections.unmodifiableList(new ArrayList<>(keyIds)); this.isDiscovery_ = isDiscovery; this.discoveryFilter_ = discoveryFilter; this.grantTokens_ = grantTokens; } private static RegionalClientSupplier defaultProvider() { return builder().clientFactory(); } /** Returns "aws-kms" */ @Override public String getDefaultProviderId() { return PROVIDER_NAME; } @Override public KmsMasterKey getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { if (!canProvide(provider)) { throw new UnsupportedProviderException(); } if (!isDiscovery_ && !keyIds_.contains(keyId)) { throw new NoSuchMasterKeyException("Key must be in supplied list of keyIds."); } final AwsKmsCmkArnInfo arnInfo = parseInfoFromKeyArn(keyId); if (isDiscovery_ && discoveryFilter_ != null && (arnInfo == null)) { throw new NoSuchMasterKeyException( "Cannot use non-ARN key identifiers or aliases if " + "discovery filter is configured."); } else if (isDiscovery_ && discoveryFilter_ != null && !discoveryFilter_.allowsPartitionAndAccount( arnInfo.getPartition(), arnInfo.getAccountId())) { throw new NoSuchMasterKeyException( "Cannot use key in partition " + arnInfo.getPartition() + " with account id " + arnInfo.getAccountId() + " with configured discovery filter."); } String regionName = defaultRegion_; if (arnInfo != null) { regionName = arnInfo.getRegion(); } String regionName_ = regionName; Supplier<AWSKMS> kmsSupplier = () -> { AWSKMS kms = regionalClientSupplier_.getClient(regionName_); if (kms == null) { throw new AwsCryptoException("Can't use keys from region " + regionName_); } return kms; }; final KmsMasterKey result = KmsMasterKey.getInstance(kmsSupplier, keyId, this); result.setGrantTokens(grantTokens_); return result; } /** Returns all CMKs provided to the constructor of this object. */ @Override public List<KmsMasterKey> getMasterKeysForEncryption(final MasterKeyRequest request) { if (keyIds_ == null) { return emptyList(); } List<KmsMasterKey> result = new ArrayList<>(keyIds_.size()); for (String id : keyIds_) { result.add(getMasterKey(id)); } return result; } @Override public DataKey<KmsMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); for (final EncryptedDataKey edk : encryptedDataKeys) { if (canProvide(edk.getProviderId())) { try { final String keyArn = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); // This will throw if we can't use this key for whatever reason return getMasterKey(keyArn) .decryptDataKey(algorithm, singletonList(edk), encryptionContext); } catch (final Exception ex) { exceptions.add(ex); } } } throw buildCannotDecryptDksException(exceptions); } /** * @deprecated This method is inherently not thread safe. Use {@link * KmsMasterKey#setGrantTokens(List)} instead. {@link KmsMasterKeyProvider}s constructed using * the builder will throw an exception on attempts to modify the list of grant tokens. */ @Deprecated @Override public void setGrantTokens(final List<String> grantTokens) { try { this.grantTokens_.clear(); this.grantTokens_.addAll(grantTokens); } catch (UnsupportedOperationException e) { throw grantTokenError(); } } @Override public List<String> getGrantTokens() { return new ArrayList<>(grantTokens_); } /** * @deprecated This method is inherently not thread safe. Use {@link #withGrantTokens(List)} or * {@link KmsMasterKey#setGrantTokens(List)} instead. {@link KmsMasterKeyProvider}s * constructed using the builder will throw an exception on attempts to modify the list of * grant tokens. */ @Deprecated @Override public void addGrantToken(final String grantToken) { try { grantTokens_.add(grantToken); } catch (UnsupportedOperationException e) { throw grantTokenError(); } } private RuntimeException grantTokenError() { return new IllegalStateException( "This master key provider is immutable. Use withGrantTokens instead."); } /** * Returns a new {@link KmsMasterKeyProvider} that is configured identically to this one, except * with the given list of grant tokens. The grant token list in the returned provider is immutable * (but can be further overridden by invoking withGrantTokens again). * * @param grantTokens * @return */ public KmsMasterKeyProvider withGrantTokens(List<String> grantTokens) { grantTokens = Collections.unmodifiableList(new ArrayList<>(grantTokens)); return new KmsMasterKeyProvider( regionalClientSupplier_, defaultRegion_, keyIds_, grantTokens, isDiscovery_, discoveryFilter_); } /** * Returns a new {@link KmsMasterKeyProvider} that is configured identically to this one, except * with the given list of grant tokens. The grant token list in the returned provider is immutable * (but can be further overridden by invoking withGrantTokens again). * * @param grantTokens * @return */ public KmsMasterKeyProvider withGrantTokens(String... grantTokens) { return withGrantTokens(asList(grantTokens)); } }
5,452
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKey.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.*; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.EncryptResult; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Supplier; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.5 // # MUST implement the Master Key Interface (../master-key- // # interface.md#interface) // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.7 // # MUST be unchanged from the Master Key interface. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.8 // # MUST be unchanged from the Master Key interface. /** * Represents a single Aws KMS key and is used to encrypt/decrypt data with {@link AwsCrypto}. This * key may be a multi region key, in which case this component is able to recognize different * regional replicas of this multi region key as the same. */ public final class AwsKmsMrkAwareMasterKey extends MasterKey<AwsKmsMrkAwareMasterKey> implements KmsMethods { private static final String USER_AGENT = VersionInfo.loadUserAgent(); private final AWSKMS kmsClient_; private final List<String> grantTokens_ = new ArrayList<>(); private final String awsKmsIdentifier_; private final MasterKeyProvider<AwsKmsMrkAwareMasterKey> sourceProvider_; private static <T extends AmazonWebServiceRequest> T updateUserAgent(T request) { request.getRequestClientOptions().appendUserAgent(USER_AGENT); return request; } /** * A light builder method. * * @see KmsMasterKey#getInstance(Supplier, String, MasterKeyProvider) * @param kms An AWS KMS Client * @param awsKmsIdentifier An identifier for an AWS KMS key. May be a raw resource. */ static AwsKmsMrkAwareMasterKey getInstance( final AWSKMS kms, final String awsKmsIdentifier, final MasterKeyProvider<AwsKmsMrkAwareMasterKey> provider) { return new AwsKmsMrkAwareMasterKey(awsKmsIdentifier, kms, provider); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # On initialization, the caller MUST provide: private AwsKmsMrkAwareMasterKey( final String awsKmsIdentifier, final AWSKMS kmsClient, final MasterKeyProvider<AwsKmsMrkAwareMasterKey> provider) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The AWS KMS key identifier MUST NOT be null or empty. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The AWS KMS // # key identifier MUST be a valid identifier (aws-kms-key-arn.md#a- // # valid-aws-kms-identifier). validAwsKmsIdentifier(awsKmsIdentifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The AWS KMS SDK client MUST not be null. if (kmsClient == null) { throw new IllegalArgumentException( "AwsKmsMrkAwareMasterKey must be configured with an AWS KMS client."); } if (provider == null) { throw new IllegalArgumentException( "AwsKmsMrkAwareMasterKey must be configured with a source provider."); } kmsClient_ = kmsClient; awsKmsIdentifier_ = awsKmsIdentifier; sourceProvider_ = provider; } @Override public String getProviderId() { return sourceProvider_.getDefaultProviderId(); } @Override public String getKeyId() { return awsKmsIdentifier_; } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The master key MUST be able to be configured with an optional list of // # Grant Tokens. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=exception // # This configuration SHOULD be on initialization and // # SHOULD be immutable. // The existing KMS Master Key // sets grants in this way, so we continue this interface. /** Clears and sets all grant tokens on this instance. This is not thread safe. */ @Override public void setGrantTokens(final List<String> grantTokens) { grantTokens_.clear(); grantTokens_.addAll(grantTokens); } @Override public List<String> getGrantTokens() { return grantTokens_; } @Override public void addGrantToken(final String grantToken) { grantTokens_.add(grantToken); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The inputs MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. /** * This is identical behavior to * * @see KmsMasterKey#generateDataKey(CryptoAlgorithm, Map) */ @Override public DataKey<AwsKmsMrkAwareMasterKey> generateDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # This // # master key MUST use the configured AWS KMS client to make an AWS KMS // # GenerateDatakey (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_GenerateDataKey.html) request constructed as follows: final GenerateDataKeyResult gdkResult = kmsClient_.generateDataKey( updateUserAgent( new GenerateDataKeyRequest() .withKeyId(awsKmsIdentifier_) .withNumberOfBytes(algorithm.getDataKeyLength()) .withEncryptionContext(encryptionContext) .withGrantTokens(grantTokens_))); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # If the call succeeds the AWS KMS Generate Data Key response's // # "Plaintext" MUST match the key derivation input length specified by // # the algorithm suite included in the input. if (gdkResult.getPlaintext().limit() != algorithm.getDataKeyLength()) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; gdkResult.getPlaintext().get(rawKey); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The response's "KeyId" // # MUST be valid. final String gdkResultKeyId = gdkResult.getKeyId(); if (parseInfoFromKeyArn(gdkResultKeyId) == null) { throw new IllegalStateException("Received an empty or invalid keyId from KMS"); } final byte[] encryptedKey = new byte[gdkResult.getCiphertextBlob().remaining()]; gdkResult.getCiphertextBlob().get(encryptedKey); final SecretKeySpec key = new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The output MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. return new DataKey<>( // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The response's "Plaintext" MUST be the plaintext in // # the output. key, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The response's cipher text blob MUST be used as the // # returned as the ciphertext for the encrypted data key in the output. encryptedKey, gdkResultKeyId.getBytes(StandardCharsets.UTF_8), this); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The inputs MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. /** @see KmsMasterKey#encryptDataKey(CryptoAlgorithm, Map, DataKey) */ @Override public DataKey<AwsKmsMrkAwareMasterKey> encryptDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext, final DataKey<?> dataKey) { final SecretKey key = dataKey.getKey(); if (!key.getFormat().equals("RAW")) { throw new IllegalArgumentException("Only RAW encoded keys are supported"); } try { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The master // # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Encrypt.html) request constructed as follows: final EncryptResult encryptResult = kmsClient_.encrypt( updateUserAgent( new EncryptRequest() .withKeyId(awsKmsIdentifier_) .withPlaintext(ByteBuffer.wrap(key.getEncoded())) .withEncryptionContext(encryptionContext) .withGrantTokens(grantTokens_))); final byte[] edk = new byte[encryptResult.getCiphertextBlob().remaining()]; encryptResult.getCiphertextBlob().get(edk); final String encryptResultKeyId = encryptResult.getKeyId(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The AWS KMS Encrypt response MUST contain a valid "KeyId". if (parseInfoFromKeyArn(encryptResultKeyId) == null) { throw new IllegalStateException("Received an empty or invalid keyId from KMS"); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The output MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. return new DataKey<>( dataKey.getKey(), // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The // # response's cipher text blob MUST be used as the "ciphertext" for the // # encrypted data key. edk, encryptResultKeyId.getBytes(StandardCharsets.UTF_8), this); } catch (final AmazonServiceException asex) { throw new AwsCryptoException(asex); } } /** * Will attempt to decrypt if awsKmsArnMatchForDecrypt returns true in {@link * AwsKmsMrkAwareMasterKey#filterEncryptedDataKeys(String, AwsKmsCmkArnInfo, EncryptedDataKey)}. * An extension of {@link KmsMasterKey#decryptDataKey(CryptoAlgorithm, Collection, Map)} but with * an awareness of the properties of multi-Region keys. */ @Override // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The inputs MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. public DataKey<AwsKmsMrkAwareMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); final String providerId = this.getProviderId(); return encryptedDataKeys.stream() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. .filter(edk -> filterEncryptedDataKeys(providerId, awsKmsIdentifier_, edk)) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # For each encrypted data key in the filtered set, one at a time, the // # master key MUST attempt to decrypt the data key. .map( edk -> { try { return decryptSingleEncryptedDataKey( this, kmsClient_, awsKmsIdentifier_, grantTokens_, algorithm, edk, encryptionContext); } catch (final AmazonServiceException amazonServiceException) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If this attempt // # results in an error, then these errors MUST be collected. exceptions.add(amazonServiceException); } return null; }) /* Need to filter null * because an Optional * of a null is crazy. * Therefore `findFirst` will throw * if it sees `null`. */ .filter(Objects::nonNull) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If the AWS KMS response satisfies the requirements then it MUST be // # use and this function MUST return and not attempt to decrypt any more // # encrypted data keys. /* Order is important. * Process the encrypted data keys in the order they exist in the encrypted message. */ .findFirst() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The output MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. .orElseThrow(() -> buildCannotDecryptDksException(exceptions)); } /** * Pure function for decrypting and encrypted data key. This is refactored out of `decryptDataKey` * to facilitate testing to ensure correctness. */ static DataKey<AwsKmsMrkAwareMasterKey> decryptSingleEncryptedDataKey( final AwsKmsMrkAwareMasterKey masterKey, final AWSKMS client, final String awsKmsIdentifier, final List<String> grantTokens, final CryptoAlgorithm algorithm, final EncryptedDataKey edk, final Map<String, String> encryptionContext) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # To decrypt the encrypted data key this master key MUST use the // # configured AWS KMS client to make an AWS KMS Decrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Decrypt.html) request constructed as follows: final DecryptResult decryptResult = client.decrypt( updateUserAgent( new DecryptRequest() .withCiphertextBlob(ByteBuffer.wrap(edk.getEncryptedDataKey())) .withEncryptionContext(encryptionContext) .withGrantTokens(grantTokens) .withKeyId(awsKmsIdentifier))); final String decryptResultKeyId = decryptResult.getKeyId(); if (decryptResultKeyId == null) { throw new IllegalStateException("Received an empty keyId from KMS"); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If the call succeeds then the response's "KeyId" MUST be equal to the // # configured AWS KMS key identifier otherwise the function MUST collect // # an error. if (!awsKmsIdentifier.equals(decryptResultKeyId)) { throw new IllegalStateException( "Received an invalid response from KMS Decrypt call: Unexpected keyId."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The response's "Plaintext"'s length MUST equal the length // # required by the requested algorithm suite otherwise the function MUST // # collect an error. if (decryptResult.getPlaintext().limit() != algorithm.getDataKeyLength()) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; decryptResult.getPlaintext().get(rawKey); return new DataKey<>( new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()), edk.getEncryptedDataKey(), edk.getProviderInformation(), masterKey); } /** * A pure function to filter encrypted data keys. This function is refactored out from * `decryptDataKey` to facilitate testing and ensure correctness. * * <p>An AWS KMS Master key should only attempt to process an Encrypted Data Key if the * information in the Encrypted Data Key matches the master keys configuration. */ static boolean filterEncryptedDataKeys( final String providerId, final String awsKmsIdentifier_, final EncryptedDataKey edk) { final String edkKeyId = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); final AwsKmsCmkArnInfo providerArnInfo = parseInfoFromKeyArn(edkKeyId); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # Additionally each provider info MUST be a valid AWS KMS ARN // # (aws-kms-key-arn.md#a-valid-aws-kms-arn) with a resource type of // # "key". if (providerArnInfo == null || !"key".equals(providerArnInfo.getResourceType())) { throw new IllegalStateException("Invalid provider info in message."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms" and the the // # function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-for- // # decrypt.md#implementation) called with the configured AWS KMS key // # identifier and the encrypted data key's provider info MUST return // # "true". return edk.getProviderId().equals(providerId) && awsKmsArnMatchForDecrypt(awsKmsIdentifier_, edkKeyId); } }
5,453
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/KmsMasterKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.kms; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.EncryptResult; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Supplier; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Represents a single Customer Master Key (CMK) and is used to encrypt/decrypt data with {@link * AwsCrypto}. * * <p>This component is not multi-Region key aware, and will treat every AWS KMS identifier as * regionally isolated. */ public final class KmsMasterKey extends MasterKey<KmsMasterKey> implements KmsMethods { private static final String USER_AGENT = VersionInfo.loadUserAgent(); private final Supplier<AWSKMS> kms_; private final MasterKeyProvider<KmsMasterKey> sourceProvider_; private final String id_; private final List<String> grantTokens_ = new ArrayList<>(); private <T extends AmazonWebServiceRequest> T updateUserAgent(T request) { request.getRequestClientOptions().appendUserAgent(USER_AGENT); return request; } static KmsMasterKey getInstance( final Supplier<AWSKMS> kms, final String id, final MasterKeyProvider<KmsMasterKey> provider) { return new KmsMasterKey(kms, id, provider); } private KmsMasterKey( final Supplier<AWSKMS> kms, final String id, final MasterKeyProvider<KmsMasterKey> provider) { kms_ = kms; id_ = id; sourceProvider_ = provider; } @Override public String getProviderId() { return sourceProvider_.getDefaultProviderId(); } @Override public String getKeyId() { return id_; } @Override public DataKey<KmsMasterKey> generateDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext) { final GenerateDataKeyResult gdkResult = kms_.get() .generateDataKey( updateUserAgent( new GenerateDataKeyRequest() .withKeyId(getKeyId()) .withNumberOfBytes(algorithm.getDataKeyLength()) .withEncryptionContext(encryptionContext) .withGrantTokens(grantTokens_))); final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; gdkResult.getPlaintext().get(rawKey); if (gdkResult.getPlaintext().remaining() > 0) { throw new IllegalStateException("Recieved an unexpected number of bytes from KMS"); } final byte[] encryptedKey = new byte[gdkResult.getCiphertextBlob().remaining()]; gdkResult.getCiphertextBlob().get(encryptedKey); final SecretKeySpec key = new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()); return new DataKey<>( key, encryptedKey, gdkResult.getKeyId().getBytes(StandardCharsets.UTF_8), this); } @Override public void setGrantTokens(final List<String> grantTokens) { grantTokens_.clear(); grantTokens_.addAll(grantTokens); } @Override public List<String> getGrantTokens() { return grantTokens_; } @Override public void addGrantToken(final String grantToken) { grantTokens_.add(grantToken); } @Override public DataKey<KmsMasterKey> encryptDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext, final DataKey<?> dataKey) { final SecretKey key = dataKey.getKey(); if (!key.getFormat().equals("RAW")) { throw new IllegalArgumentException("Only RAW encoded keys are supported"); } try { final EncryptResult encryptResult = kms_.get() .encrypt( updateUserAgent( new EncryptRequest() .withKeyId(id_) .withPlaintext(ByteBuffer.wrap(key.getEncoded())) .withEncryptionContext(encryptionContext) .withGrantTokens(grantTokens_))); final byte[] edk = new byte[encryptResult.getCiphertextBlob().remaining()]; encryptResult.getCiphertextBlob().get(edk); return new DataKey<>( dataKey.getKey(), edk, encryptResult.getKeyId().getBytes(StandardCharsets.UTF_8), this); } catch (final AmazonServiceException asex) { throw new AwsCryptoException(asex); } } @Override public DataKey<KmsMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); for (final EncryptedDataKey edk : encryptedDataKeys) { try { final String edkKeyId = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); if (!edkKeyId.equals(id_)) { continue; } final DecryptResult decryptResult = kms_.get() .decrypt( updateUserAgent( new DecryptRequest() .withCiphertextBlob(ByteBuffer.wrap(edk.getEncryptedDataKey())) .withEncryptionContext(encryptionContext) .withGrantTokens(grantTokens_) .withKeyId(edkKeyId))); if (decryptResult.getKeyId() == null) { throw new IllegalStateException("Received an empty keyId from KMS"); } if (decryptResult.getKeyId().equals(id_)) { final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; decryptResult.getPlaintext().get(rawKey); if (decryptResult.getPlaintext().remaining() > 0) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } return new DataKey<>( new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()), edk.getEncryptedDataKey(), edk.getProviderInformation(), this); } } catch (final AmazonServiceException awsex) { exceptions.add(awsex); } } throw buildCannotDecryptDksException(exceptions); } }
5,454
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKeyProvider.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.*; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo; import com.amazonaws.handlers.RequestHandler2; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClient; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.5 // # MUST implement the Master Key Provider Interface (../master-key- // # provider-interface.md#interface) /** * Represents a list Aws KMS keys and is used to encrypt/decrypt data with {@link AwsCrypto}. Some * of these keys may be multi region keys, in which case this component is able to recognize * different regional replicas of this multi region key as the same. */ public final class AwsKmsMrkAwareMasterKeyProvider extends MasterKeyProvider<AwsKmsMrkAwareMasterKey> { private static final String PROVIDER_NAME = "aws-kms"; private final List<String> keyIds_; private final List<String> grantTokens_; private final boolean isDiscovery_; private final DiscoveryFilter discoveryFilter_; private final String discoveryMrkRegion_; private final KmsMasterKeyProvider.RegionalClientSupplier regionalClientSupplier_; private final String defaultRegion_; public static class Builder implements Cloneable { private String defaultRegion_ = getSdkDefaultRegion(); private Optional<KmsMasterKeyProvider.RegionalClientSupplier> regionalClientSupplier_ = Optional.empty(); private AWSKMSClientBuilder templateBuilder_ = null; private DiscoveryFilter discoveryFilter_ = null; private String discoveryMrkRegion_ = this.defaultRegion_; Builder() { // Default access: Don't allow outside classes to extend this class } public Builder clone() { try { AwsKmsMrkAwareMasterKeyProvider.Builder cloned = (AwsKmsMrkAwareMasterKeyProvider.Builder) super.clone(); if (templateBuilder_ != null) { cloned.templateBuilder_ = cloneClientBuilder(templateBuilder_); } return cloned; } catch (CloneNotSupportedException e) { throw new Error("Impossible: CloneNotSupportedException", e); } } /** * Sets the default region. This region will be used when specifying key IDs for encryption or * in {@link AwsKmsMrkAwareMasterKeyProvider#getMasterKey(String)} that are not full ARNs, but * are instead bare key IDs or aliases. * * <p>If the default region is not specified, the AWS SDK default region will be used. * * @see KmsMasterKeyProvider.Builder#withDefaultRegion(String) * @param defaultRegion The default region to use. */ public AwsKmsMrkAwareMasterKeyProvider.Builder withDefaultRegion(String defaultRegion) { this.defaultRegion_ = defaultRegion; return this; } /** * Sets the region contacted for multi-region keys when in Discovery mode. This region will be * used when a multi-region key is discovered on decrypt by {@link * AwsKmsMrkAwareMasterKeyProvider#getMasterKey(String)}. * * <p> * * @param discoveryMrkRegion The region to contact to attempt to decrypt multi-region keys. */ public AwsKmsMrkAwareMasterKeyProvider.Builder withDiscoveryMrkRegion( String discoveryMrkRegion) { this.discoveryMrkRegion_ = discoveryMrkRegion; return this; } /** * Provides a custom factory function that will vend KMS clients. This is provided for advanced * use cases which require complete control over the client construction process. * * <p>Because the regional client supplier fully controls the client construction process, it is * not possible to configure the client through methods such as {@link * #withCredentials(AWSCredentialsProvider)} or {@link #withClientBuilder(AWSKMSClientBuilder)}; * if you try to use these in combination, an {@link IllegalStateException} will be thrown. * * @see * KmsMasterKeyProvider.Builder#withCustomClientFactory(KmsMasterKeyProvider.RegionalClientSupplier) */ public AwsKmsMrkAwareMasterKeyProvider.Builder withCustomClientFactory( KmsMasterKeyProvider.RegionalClientSupplier regionalClientSupplier) { if (templateBuilder_ != null) { throw clientSupplierComboException(); } regionalClientSupplier_ = Optional.of(regionalClientSupplier); return this; } private RuntimeException clientSupplierComboException() { return new IllegalStateException( "withCustomClientFactory cannot be used in conjunction with " + "withCredentials or withClientBuilder"); } /** * Configures the {@link AwsKmsMrkAwareMasterKeyProvider} to use specific credentials. If a * builder was previously set, this will override whatever credentials it set. * * @see KmsMasterKeyProvider.Builder#withCredentials(AWSCredentialsProvider) */ public AwsKmsMrkAwareMasterKeyProvider.Builder withCredentials( AWSCredentialsProvider credentialsProvider) { if (regionalClientSupplier_.isPresent()) { throw clientSupplierComboException(); } if (templateBuilder_ == null) { templateBuilder_ = AWSKMSClientBuilder.standard(); } templateBuilder_.setCredentials(credentialsProvider); return this; } /** * Configures the {@link AwsKmsMrkAwareMasterKeyProvider} to use specific credentials. If a * builder was previously set, this will override whatever credentials it set. * * @see KmsMasterKeyProvider.Builder#withCredentials(AWSCredentials) */ public AwsKmsMrkAwareMasterKeyProvider.Builder withCredentials(AWSCredentials credentials) { return withCredentials(new AWSStaticCredentialsProvider(credentials)); } /** * Configures the {@link AwsKmsMrkAwareMasterKeyProvider} to use settings from this {@link * AWSKMSClientBuilder} to configure KMS clients. Note that the region set on this builder will * be ignored, but all other settings will be propagated into the regional clients. * * <p>This method will overwrite any credentials set using {@link * #withCredentials(AWSCredentialsProvider)}. * * @see KmsMasterKeyProvider.Builder#withClientBuilder(AWSKMSClientBuilder) */ public AwsKmsMrkAwareMasterKeyProvider.Builder withClientBuilder(AWSKMSClientBuilder builder) { if (regionalClientSupplier_.isPresent()) { throw clientSupplierComboException(); } final AWSKMSClientBuilder newBuilder = cloneClientBuilder(builder); this.templateBuilder_ = newBuilder; return this; } /** * Builds the master key provider in Discovery Mode. In Discovery Mode the KMS Master Key * Provider will attempt to decrypt using any key identifier it discovers in the encrypted * message. KMS Master Key Providers in Discovery Mode will not encrypt data keys. * * @see KmsMasterKeyProvider.Builder#buildDiscovery() */ public AwsKmsMrkAwareMasterKeyProvider buildDiscovery() { final boolean isDiscovery = true; return new AwsKmsMrkAwareMasterKeyProvider( // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The regional client // # supplier MUST be defined in discovery mode. regionalClientSupplier_.orElse( clientFactory(new ConcurrentHashMap<>(), templateBuilder_)), defaultRegion_, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The key id list MUST be empty in discovery mode. emptyList(), emptyList(), isDiscovery, discoveryFilter_, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # In // # discovery mode if a default MRK Region is not configured the AWS SDK // # Default Region MUST be used. discoveryMrkRegion_ == null ? defaultRegion_ : discoveryMrkRegion_); } /** * Builds the master key provider in Discovery Mode with a {@link DiscoveryFilter}. In Discovery * Mode the KMS Master Key Provider will attempt to decrypt using any key identifier it * discovers in the encrypted message that is accepted by the {@code filter}. KMS Master Key * Providers in Discovery Mode will not encrypt data keys. * * @see KmsMasterKeyProvider.Builder#buildDiscovery(DiscoveryFilter) */ public AwsKmsMrkAwareMasterKeyProvider buildDiscovery(DiscoveryFilter filter) { discoveryFilter_ = filter; return buildDiscovery(); } /** * Builds the master key provider in Strict Mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For Master Key Providers that will only * be used for encryption, you can use any valid KMS key identifier. For providers that will be * used for decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not * supported. * * @see KmsMasterKeyProvider.Builder#buildStrict(List) */ public AwsKmsMrkAwareMasterKeyProvider buildStrict(List<String> keyIds) { final boolean isDiscovery = false; return new AwsKmsMrkAwareMasterKeyProvider( regionalClientSupplier_.orElse( clientFactory(new ConcurrentHashMap<>(), templateBuilder_)), defaultRegion_, new ArrayList<String>(keyIds), emptyList(), isDiscovery, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # A discovery filter MUST NOT be configured in strict mode. null, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # A default MRK Region MUST NOT be configured in strict mode. null); } /** * Builds the master key provider in strict mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For Master Key Providers that will only * be used for encryption, you can use any valid KMS key identifier. For providers that will be * used for decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not * supported. * * @see KmsMasterKeyProvider.Builder#buildStrict(String...) */ public AwsKmsMrkAwareMasterKeyProvider buildStrict(String... keyIds) { return buildStrict(asList(keyIds)); } static KmsMasterKeyProvider.RegionalClientSupplier clientFactory( ConcurrentHashMap<String, AWSKMS> clientCache, AWSKMSClientBuilder templateBuilder) { // Clone again; this MKP builder might be reused to build a second MKP with different creds. AWSKMSClientBuilder builder = templateBuilder != null ? cloneClientBuilder(templateBuilder) : AWSKMSClientBuilder.standard(); return region -> { if (clientCache.containsKey(region)) { return clientCache.get(region); } // We can't just use computeIfAbsent as we need to avoid leaking KMS clients if we're asked // to decrypt // an EDK with a bogus region in its ARN. So we'll install a request handler to identify the // first // successful call, and cache it when we see that. final KmsMasterKeyProvider.SuccessfulRequestCacher cacher = new KmsMasterKeyProvider.SuccessfulRequestCacher(clientCache, region); final ArrayList<RequestHandler2> handlers = new ArrayList<>(); if (builder.getRequestHandlers() != null) { handlers.addAll(builder.getRequestHandlers()); } handlers.add(cacher); final AWSKMS kms = cloneClientBuilder(builder) .withRegion(region) .withRequestHandlers(handlers.toArray(new RequestHandler2[handlers.size()])) .build(); return cacher.setClient(kms); }; } static AWSKMSClientBuilder cloneClientBuilder(final AWSKMSClientBuilder builder) { // We need to copy all arguments out of the builder in case it's mutated later on. // Unfortunately AWSKMSClientBuilder doesn't support .clone() so we'll have to do it by hand. if (builder.getEndpoint() != null) { // We won't be able to set the region later if a custom endpoint is set. throw new IllegalArgumentException( "Setting endpoint configuration is not compatible with passing a " + "builder to the KmsMasterKeyProvider. Use withCustomClientFactory" + " instead."); } final AWSKMSClientBuilder newBuilder = AWSKMSClient.builder(); newBuilder.setClientConfiguration(builder.getClientConfiguration()); newBuilder.setCredentials(builder.getCredentials()); newBuilder.setEndpointConfiguration(builder.getEndpoint()); newBuilder.setMetricsCollector(builder.getMetricsCollector()); if (builder.getRequestHandlers() != null) { newBuilder.setRequestHandlers(builder.getRequestHandlers().toArray(new RequestHandler2[0])); } return newBuilder; } /** * The AWS SDK has a default process for evaluating the default Region. This returns null if no * default region is found. Because a default region _may_ not be needed. */ private static String getSdkDefaultRegion() { try { return new com.amazonaws.regions.DefaultAwsRegionProviderChain().getRegion(); } catch (SdkClientException ex) { return null; } } } public static AwsKmsMrkAwareMasterKeyProvider.Builder builder() { return new AwsKmsMrkAwareMasterKeyProvider.Builder(); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # On initialization the caller MUST provide: private AwsKmsMrkAwareMasterKeyProvider( KmsMasterKeyProvider.RegionalClientSupplier supplier, String defaultRegion, List<String> keyIds, List<String> grantTokens, boolean isDiscovery, DiscoveryFilter discoveryFilter, String discoveryMrkRegion) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The key id list MUST NOT be empty or null in strict mode. if (!isDiscovery && (keyIds == null || keyIds.isEmpty())) { throw new IllegalArgumentException( "Strict mode must be configured with a non-empty " + "list of keyIds."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The key id // # list MUST NOT contain any null or empty string values. if (!isDiscovery && (keyIds.contains(null) || keyIds.contains(""))) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "null key identifier."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # All AWS KMS // # key identifiers are be passed to Assert AWS KMS MRK are unique (aws- // # kms-mrk-are-unique.md#Implementation) and the function MUST return // # success. assertMrksAreUnique(keyIds); if (!isDiscovery && defaultRegion == null && keyIds.stream() .map(identifier -> parseInfoFromKeyArn(identifier)) .anyMatch(info -> info == null)) { throw new AwsCryptoException( "Can't use non-ARN key identifiers or aliases when " + "no default region is set"); } /* Precondition (untested): Discovery filter is only valid in discovery mode. */ if (!isDiscovery && discoveryFilter != null) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "discovery filter."); } /* Precondition (untested): Discovery mode can not have any keys to filter. */ if (isDiscovery && !keyIds.isEmpty()) { throw new IllegalArgumentException("Discovery mode can not be configured with keys."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # If an AWS SDK Default Region can not be // # obtained initialization MUST fail. if (isDiscovery && discoveryMrkRegion == null) { throw new IllegalArgumentException("Discovery MRK region can not be null."); } this.regionalClientSupplier_ = supplier; this.defaultRegion_ = defaultRegion; this.keyIds_ = Collections.unmodifiableList(new ArrayList<>(keyIds)); this.isDiscovery_ = isDiscovery; this.discoveryFilter_ = discoveryFilter; this.discoveryMrkRegion_ = discoveryMrkRegion; this.grantTokens_ = grantTokens; } // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # The caller MUST provide: /** Refactored into a pure function to facilitate testing and correctness. */ static void assertMrksAreUnique(List<String> keyIdentifiers) { List<String> duplicateMultiRegionKeyIdentifiers = keyIdentifiers.stream() /* Collect a map of resource to identifier. * This lets me group duplicates by "resource". * This is because the identifier can be either an ARN or a raw identifier. * By having the both the key id and the identifier I can ensure the uniqueness of * the key id and the error message to the caller can contain both identifiers * to facilitate debugging. */ .collect( Collectors.groupingBy( AwsKmsMrkAwareMasterKeyProvider::getResourceForResourceTypeKey)) .entrySet() .stream() // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # If there are zero duplicate resource ids between the multi-region // # keys, this function MUST exit successfully .filter(maybeDuplicate -> maybeDuplicate.getValue().size() > 1) // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # If the list does not contain any multi-Region keys (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) this function MUST // # exit successfully. // .filter(maybeMrk -> isMRK(maybeMrk.getKey())) /* Flatten the duplicate identifiers into a single list. */ .flatMap(mrkEntry -> mrkEntry.getValue().stream()) .collect(Collectors.toList()); // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # If any duplicate multi-region resource ids exist, this function MUST // # yield an error that includes all identifiers with duplicate resource // # ids not only the first duplicate found. if (duplicateMultiRegionKeyIdentifiers.size() > 1) { throw new IllegalArgumentException( "Duplicate multi-region keys are not allowed:\n" + String.join(", ", duplicateMultiRegionKeyIdentifiers)); } } /** * Helper method for * * @see AwsKmsMrkAwareMasterKeyProvider#assertMrksAreUnique(List) * <p>Refoactored into a pure function to simplify testing and ensure correctness. */ static String getResourceForResourceTypeKey(String identifier) { final AwsKmsCmkArnInfo info = parseInfoFromKeyArn(identifier); if (info == null) return identifier; if (!info.getResourceType().equals("key")) { return identifier; } return info.getResource(); } /** Returns "aws-kms" */ @Override public String getDefaultProviderId() { return PROVIDER_NAME; } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # The input MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. /** * Added flexibility in matching multi-Region keys from different regions. * * @see KmsMasterKey#getMasterKey(String, String) */ @Override public AwsKmsMrkAwareMasterKey getMasterKey(final String providerId, final String requestedKeyArn) throws UnsupportedProviderException, NoSuchMasterKeyException { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # The function MUST only provide master keys if the input provider id // # equals "aws-kms". if (!canProvide(providerId)) { throw new UnsupportedProviderException(); } /* There SHOULD only be one match. * An unambiguous multi-region key for the family * of related multi-region keys is required. * See `assertMrksAreUnique`. * However, in the case of single region keys or aliases, * duplicates _are_ possible. */ Optional<String> matchedArn = keyIds_.stream().filter(t -> awsKmsArnMatchForDecrypt(t, requestedKeyArn)).findFirst(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In strict mode, the requested AWS KMS key ARN MUST // # match a member of the configured key ids by using AWS KMS MRK Match // # for Decrypt (aws-kms-mrk-match-for-decrypt.md#implementation) // # otherwise this function MUST error. if (!isDiscovery_ && !matchedArn.isPresent()) { throw new NoSuchMasterKeyException("Key must be in supplied list of keyIds."); } final AwsKmsCmkArnInfo requestedKeyArnInfo = parseInfoFromKeyArn(requestedKeyArn); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In discovery mode, the requested // # AWS KMS key identifier MUST be a well formed AWS KMS ARN. if (isDiscovery_ && requestedKeyArnInfo == null) { throw new NoSuchMasterKeyException( "Cannot use AWS KMS identifiers " + "when in discovery mode."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In // # discovery mode if a discovery filter is configured the requested AWS // # KMS key ARN's "partition" MUST match the discovery filter's // # "partition" and the AWS KMS key ARN's "account" MUST exist in the // # discovery filter's account id set. if (isDiscovery_ && discoveryFilter_ != null && !discoveryFilter_.allowsPartitionAndAccount( requestedKeyArnInfo.getPartition(), requestedKeyArnInfo.getAccountId())) { throw new NoSuchMasterKeyException( "Cannot use key in partition " + requestedKeyArnInfo.getPartition() + " with account id " + requestedKeyArnInfo.getAccountId() + " with configured discovery filter."); } final String regionName_ = extractRegion( defaultRegion_, discoveryMrkRegion_, matchedArn, requestedKeyArnInfo, isDiscovery_); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # An AWS KMS client // # MUST be obtained by calling the regional client supplier with this // # AWS Region. AWSKMS kms = regionalClientSupplier_.getClient(regionName_); String keyIdentifier = isDiscovery_ // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In discovery mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with ? requestedKeyArnInfo.toString(regionName_) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In strict mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with : matchedArn.get(); final AwsKmsMrkAwareMasterKey result = AwsKmsMrkAwareMasterKey.getInstance(kms, keyIdentifier, this); result.setGrantTokens(grantTokens_); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # The output MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. return result; } /** * Select the correct region from multiple default configurations and potentially related * multi-Region keys from different regions. * * <p>Refactored into a pure function to facilitate testing and ensure correctness. */ static String extractRegion( final String defaultRegion, final String discoveryMrkRegion, final Optional<String> matchedArn, final AwsKmsCmkArnInfo requestedKeyArnInfo, final boolean isDiscovery) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # If the requested AWS KMS key identifier is not a well formed ARN the // # AWS Region MUST be the configured default region this SHOULD be // # obtained from the AWS SDK. if (requestedKeyArnInfo == null) return defaultRegion; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # Otherwise if the requested AWS KMS key // # identifier is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key), then AWS Region MUST // # be the region from the AWS KMS key ARN stored in the provider info // # from the encrypted data key. if (!isMRK(requestedKeyArnInfo.getResource()) || !requestedKeyArnInfo.getResourceType().equals("key")) { return requestedKeyArnInfo.getRegion(); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # Otherwise if the mode is discovery then // # the AWS Region MUST be the discovery MRK region. if (isDiscovery) return discoveryMrkRegion; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # Finally if the // # provider info is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) the AWS Region MUST // # be the region from the AWS KMS key in the configured key ids matched // # to the requested AWS KMS key by using AWS KMS MRK Match for Decrypt // # (aws-kms-mrk-match-for-decrypt.md#implementation). return parseInfoFromKeyArn(matchedArn.get()).getRegion(); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # The input MUST be the same as the Master Key Provider Get Master Keys // # For Encryption (../master-key-provider-interface.md#get-master-keys- // # for-encryption) interface. /** * Returns all CMKs provided to the constructor of this object. * * @see KmsMasterKey#getMasterKeysForEncryption(MasterKeyRequest) */ @Override public List<AwsKmsMrkAwareMasterKey> getMasterKeysForEncryption(final MasterKeyRequest request) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # If the configured mode is discovery the function MUST return an empty // # list. if (isDiscovery_) { return emptyList(); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # If the configured mode is strict this function MUST return a // # list of master keys obtained by calling Get Master Key (aws-kms-mrk- // # aware-master-key-provider.md#get-master-key) for each AWS KMS key // # identifier in the configured key ids List<AwsKmsMrkAwareMasterKey> result = new ArrayList<>(keyIds_.size()); for (String id : keyIds_) { result.add(getMasterKey(id)); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # The output MUST be the same as the Master Key Provider Get Master // # Keys For Encryption (../master-key-provider-interface.md#get-master- // # keys-for-encryption) interface. return result; } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # The input MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. /** * @see KmsMasterKey#decryptDataKey(CryptoAlgorithm, Collection, Map) * @throws AwsCryptoException */ @Override public DataKey<AwsKmsMrkAwareMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); return encryptedDataKeys.stream() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. .filter( edk -> { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms". if (!canProvide(edk.getProviderId())) return false; final String providerInfo = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); final AwsKmsCmkArnInfo providerArnInfo = parseInfoFromKeyArn(providerInfo); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # Additionally // # each provider info MUST be a valid AWS KMS ARN (aws-kms-key-arn.md#a- // # valid-aws-kms-arn) with a resource type of "key". if (providerArnInfo == null || !"key".equals(providerArnInfo.getResourceType())) { throw new IllegalStateException("Invalid provider info in message."); } return true; }) .map( edk -> { try { final String keyArn = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # For each encrypted data key in the filtered set, one at a time, the // # master key provider MUST call Get Master Key (aws-kms-mrk-aware- // # master-key-provider.md#get-master-key) with the encrypted data key's // # provider info as the AWS KMS key ARN. // This will throw if we can't use this key for whatever reason return getMasterKey(edk.getProviderId(), keyArn) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # It MUST call Decrypt Data Key // # (aws-kms-mrk-aware-master-key.md#decrypt-data-key) on this master key // # with the input algorithm, this single encrypted data key, and the // # input encryption context. .decryptDataKey(algorithm, singletonList(edk), encryptionContext); } catch (final Exception ex) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # If this attempt results in an error, then // # these errors MUST be collected. exceptions.add(ex); return null; } }) /* Need to filter null because an Optional of a null is crazy. * `findFirst` will throw if it sees `null`. */ .filter(Objects::nonNull) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # If the decrypt data key call is // # successful, then this function MUST return this result and not // # attempt to decrypt any more encrypted data keys. .findFirst() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # The output MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. .orElseThrow(() -> buildCannotDecryptDksException(exceptions)); } public List<String> getGrantTokens() { return new ArrayList<>(grantTokens_); } /** * Returns a new {@link AwsKmsMrkAwareMasterKeyProvider} that is configured identically to this * one, except with the given list of grant tokens. The grant token list in the returned provider * is immutable (but can be further overridden by invoking withGrantTokens again). */ public AwsKmsMrkAwareMasterKeyProvider withGrantTokens(List<String> grantTokens) { grantTokens = Collections.unmodifiableList(new ArrayList<>(grantTokens)); return new AwsKmsMrkAwareMasterKeyProvider( regionalClientSupplier_, defaultRegion_, keyIds_, grantTokens, isDiscovery_, discoveryFilter_, discoveryMrkRegion_); } /** * Returns a new {@link AwsKmsMrkAwareMasterKeyProvider} that is configured identically to this * one, except with the given list of grant tokens. The grant token list in the returned provider * is immutable (but can be further overridden by invoking withGrantTokens again). */ public AwsKmsMrkAwareMasterKeyProvider withGrantTokens(String... grantTokens) { return withGrantTokens(asList(grantTokens)); } }
5,455
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kms/package-info.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ /** * Contains logic necessary to create {@link com.amazonaws.encryptionsdk.MasterKey}s backed by AWS * KMS keys. */ package com.amazonaws.encryptionsdk.kms;
5,456
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/jce/KeyStoreProvider.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.jce; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.MasterKeyRequest; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.security.KeyStore.Entry; import java.security.KeyStore.PrivateKeyEntry; import java.security.KeyStore.ProtectionParameter; import java.security.KeyStore.SecretKeyEntry; import java.security.KeyStore.TrustedCertificateEntry; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableEntryException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; /** * This {@link MasterKeyProvider} provides keys backed by a JCE {@link KeyStore}. Please see {@link * #decryptDataKey(CryptoAlgorithm, Collection, Map)} for an of how decryption is managed and see * {@link #getMasterKeysForEncryption(MasterKeyRequest)} for an explanation of how encryption is * managed. */ public class KeyStoreProvider extends MasterKeyProvider<JceMasterKey> { private final String providerName_; private final KeyStore keystore_; private final ProtectionParameter protection_; private final String wrappingAlgorithm_; private final String keyAlgorithm_; private final List<String> aliasNames_; /** * Creates an instance of this class using {@code wrappingAlgorithm} which will work <em>for * decrypt only</em>. */ public KeyStoreProvider( final KeyStore keystore, final ProtectionParameter protection, final String providerName, final String wrappingAlgorithm) { this(keystore, protection, providerName, wrappingAlgorithm, new String[0]); } /** * Creates an instance of this class using {@code wrappingAlgorithm} which will encrypt data to * the keys specified by {@code aliasNames}. */ public KeyStoreProvider( final KeyStore keystore, final ProtectionParameter protection, final String providerName, final String wrappingAlgorithm, final String... aliasNames) { keystore_ = keystore; protection_ = protection; wrappingAlgorithm_ = wrappingAlgorithm; aliasNames_ = Arrays.asList(aliasNames); providerName_ = providerName; keyAlgorithm_ = wrappingAlgorithm.split("/", 2)[0].toUpperCase(); } /** * Returns a {@link JceMasterKey} corresponding to the entry in the {@link KeyStore} with the * specified alias and compatible algorithm. */ @Override public JceMasterKey getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { if (!canProvide(provider)) { throw new UnsupportedProviderException(); } final JceMasterKey result = internalGetMasterKey(provider, keyId); if (result == null) { throw new NoSuchMasterKeyException(); } else { return result; } } private JceMasterKey internalGetMasterKey(final String provider, final String keyId) { final Entry entry; try { entry = keystore_.getEntry(keyId, keystore_.isKeyEntry(keyId) ? protection_ : null); } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { throw new UnsupportedProviderException(e); } if (entry == null) { throw new NoSuchMasterKeyException(); } if (entry instanceof SecretKeyEntry) { final SecretKeyEntry skEntry = (SecretKeyEntry) entry; if (!skEntry.getSecretKey().getAlgorithm().equals(keyAlgorithm_)) { return null; } return JceMasterKey.getInstance(skEntry.getSecretKey(), provider, keyId, wrappingAlgorithm_); } else if (entry instanceof PrivateKeyEntry) { final PrivateKeyEntry pkEntry = (PrivateKeyEntry) entry; if (!pkEntry.getPrivateKey().getAlgorithm().equals(keyAlgorithm_)) { return null; } return JceMasterKey.getInstance( pkEntry.getCertificate().getPublicKey(), pkEntry.getPrivateKey(), provider, keyId, wrappingAlgorithm_); } else if (entry instanceof TrustedCertificateEntry) { final TrustedCertificateEntry certEntry = (TrustedCertificateEntry) entry; if (!certEntry.getTrustedCertificate().getPublicKey().getAlgorithm().equals(keyAlgorithm_)) { return null; } return JceMasterKey.getInstance( certEntry.getTrustedCertificate().getPublicKey(), null, provider, keyId, wrappingAlgorithm_); } else { throw new NoSuchMasterKeyException(); } } /** Returns "JavaKeyStore". */ @Override public String getDefaultProviderId() { return providerName_; } /** * Returns {@link JceMasterKey}s corresponding to the {@code aliasNames} passed into the * constructor. */ @Override public List<JceMasterKey> getMasterKeysForEncryption(final MasterKeyRequest request) { if (aliasNames_ != null) { final List<JceMasterKey> result = new ArrayList<>(); for (final String alias : aliasNames_) { result.add(getMasterKey(alias)); } return result; } else { return Collections.emptyList(); } } /** * Attempts to decrypts the {@code encryptedDataKeys} by first iterating through all {@code * aliasNames} specified in the constructor and then over <em>all other compatible keys</em> in * the {@link KeyStore}. This includes {@code TrustedCertificates} as well as standard key * entries. */ @Override public DataKey<JceMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); for (final EncryptedDataKey edk : encryptedDataKeys) { try { if (canProvide(edk.getProviderId())) { final String alias = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); if (keystore_.isKeyEntry(alias)) { final DataKey<JceMasterKey> result = getMasterKey(alias) .decryptDataKey(algorithm, Collections.singletonList(edk), encryptionContext); if (result != null) { return result; } } } } catch (final Exception ex) { exceptions.add(ex); } } throw buildCannotDecryptDksException(exceptions); } }
5,457
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/jce/JceMasterKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.jce; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.JceKeyCipher; import com.amazonaws.encryptionsdk.internal.Utils; import java.nio.charset.StandardCharsets; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Represents a {@link MasterKey} backed by one (or more) JCE {@link Key}s. Instances of this should * only be acquired using {@link #getInstance(SecretKey, String, String, String)} or {@link * #getInstance(PublicKey, PrivateKey, String, String, String)}. */ public class JceMasterKey extends MasterKey<JceMasterKey> { private final String providerName_; private final String keyId_; private final byte[] keyIdBytes_; private final JceKeyCipher jceKeyCipher_; /** * Returns a {@code JceMasterKey} backed by the symmetric key {@code key} using {@code * wrappingAlgorithm}. Currently "{@code AES/GCM/NoPadding}" is the only supported value for * symmetric {@code wrappingAlgorithm}s. * * @param key key used to wrap/unwrap (encrypt/decrypt) {@link DataKey}s * @param provider * @param keyId * @param wrappingAlgorithm * @return */ public static JceMasterKey getInstance( final SecretKey key, final String provider, final String keyId, final String wrappingAlgorithm) { switch (wrappingAlgorithm.toUpperCase()) { case "AES/GCM/NOPADDING": return new JceMasterKey(provider, keyId, JceKeyCipher.aesGcm(key)); default: throw new IllegalArgumentException("Right now only AES/GCM/NoPadding is supported"); } } /** * Returns a {@code JceMasterKey} backed by the asymmetric key pair {@code unwrappingKey} and * {@code wrappingKey} using {@code wrappingAlgorithm}. Currently only RSA algorithms are * supported for asymmetric {@code wrappingAlgorithm}s. If {@code unwrappingKey} is {@code null} * then the returned {@link JceMasterKey} can only be used for encryption. * * @param wrappingKey key used to wrap (encrypt) {@link DataKey}s * @param unwrappingKey (Optional) key used to unwrap (decrypt) {@link DataKey}s. */ public static JceMasterKey getInstance( final PublicKey wrappingKey, final PrivateKey unwrappingKey, final String provider, final String keyId, final String wrappingAlgorithm) { if (wrappingAlgorithm.toUpperCase().startsWith("RSA/ECB/")) { return new JceMasterKey( provider, keyId, JceKeyCipher.rsa(wrappingKey, unwrappingKey, wrappingAlgorithm)); } throw new UnsupportedOperationException( "Currently only RSA asymmetric algorithms are supported"); } protected JceMasterKey( final String providerName, final String keyId, final JceKeyCipher jceKeyCipher) { providerName_ = providerName; keyId_ = keyId; keyIdBytes_ = keyId_.getBytes(StandardCharsets.UTF_8); jceKeyCipher_ = jceKeyCipher; } @Override public String getProviderId() { return providerName_; } @Override public String getKeyId() { return keyId_; } @Override public DataKey<JceMasterKey> generateDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext) { final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; Utils.getSecureRandom().nextBytes(rawKey); EncryptedDataKey encryptedDataKey = jceKeyCipher_.encryptKey(rawKey, keyId_, providerName_, encryptionContext); return new DataKey<>( new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()), encryptedDataKey.getEncryptedDataKey(), encryptedDataKey.getProviderInformation(), this); } @Override public DataKey<JceMasterKey> encryptDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext, final DataKey<?> dataKey) { final SecretKey key = dataKey.getKey(); if (!key.getFormat().equals("RAW")) { throw new IllegalArgumentException( "Can only re-encrypt data keys which are in RAW format, not " + dataKey.getKey().getFormat()); } if (!key.getAlgorithm().equalsIgnoreCase(algorithm.getDataKeyAlgo())) { throw new IllegalArgumentException( "Incorrect key algorithm. Expected " + key.getAlgorithm() + " but got " + algorithm.getKeyAlgo()); } EncryptedDataKey encryptedDataKey = jceKeyCipher_.encryptKey(key.getEncoded(), keyId_, providerName_, encryptionContext); return new DataKey<>( key, encryptedDataKey.getEncryptedDataKey(), encryptedDataKey.getProviderInformation(), this); } @Override public DataKey<JceMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); // Find an encrypted key who's provider and info match us for (final EncryptedDataKey edk : encryptedDataKeys) { try { if (edk.getProviderId().equals(getProviderId()) && Utils.arrayPrefixEquals( edk.getProviderInformation(), keyIdBytes_, keyIdBytes_.length)) { final byte[] decryptedKey = jceKeyCipher_.decryptKey(edk, keyId_, encryptionContext); // Validate that the decrypted key length is as expected if (decryptedKey.length == algorithm.getDataKeyLength()) { return new DataKey<>( new SecretKeySpec(decryptedKey, algorithm.getDataKeyAlgo()), edk.getEncryptedDataKey(), edk.getProviderInformation(), this); } } } catch (final Exception ex) { exceptions.add(ex); } } throw buildCannotDecryptDksException(exceptions); } }
5,458
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/jce/package-info.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ /** * Contains logic necessary to create {@link com.amazonaws.encryptionsdk.MasterKey}s with raw * cryptographic keys, {@link java.security.Key}s, or {@link java.security.KeyStore}. */ package com.amazonaws.encryptionsdk.jce;
5,459
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/RegionalClientSupplier.java
package com.amazonaws.encryptionsdk.kmssdkv2; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; @FunctionalInterface public interface RegionalClientSupplier { /** * Supplies an {@link KmsClient} instance to use for a given {@link Region}. The {@link * KmsMasterKeyProvider} will not cache the result of this function. * * <p>Note: The AWS Encryption SDK for Java does not support the {@code KmsAsyncClient} interface. * * @param region The region to get a client for * @return The client to use, or null if this region cannot or should not be used. */ KmsClient getClient(Region region); }
5,460
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/KmsMasterKeyProvider.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.kms.KmsMethods; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.KmsClientBuilder; /** * Provides {@link MasterKey}s backed by the AWS Key Management Service. This object is regional and * if you want to use keys from multiple regions, you'll need multiple copies of this object. * * <p>This component is not multi-Region key aware, and will treat every AWS KMS identifier as * regionally isolated. */ public class KmsMasterKeyProvider extends MasterKeyProvider<KmsMasterKey> implements KmsMethods { private static final String PROVIDER_NAME = "aws-kms"; private final List<String> keyIds_; private final List<String> grantTokens_; private final boolean isDiscovery_; private final DiscoveryFilter discoveryFilter_; private final RegionalClientSupplier regionalClientSupplier_; private final Region defaultRegion_; public static class Builder implements Cloneable { private Region defaultRegion_ = null; private Supplier<KmsClientBuilder> builderSupplier_ = null; private RegionalClientSupplier regionalClientSupplier_ = null; private DiscoveryFilter discoveryFilter_ = null; Builder() { // Default access: Don't allow outside classes to extend this class } public Builder clone() { try { Builder cloned = (Builder) super.clone(); cloned.builderSupplier_ = builderSupplier_; return cloned; } catch (CloneNotSupportedException e) { throw new Error("Impossible: CloneNotSupportedException", e); } } /** * Sets the default region. This region will be used when specifying key IDs for encryption or * in {@link KmsMasterKeyProvider#getMasterKey(String)} that are not full ARNs, but are instead * bare key IDs or aliases. * * <p>If the default region is not specified, only full key ARNs will be usable. * * @param defaultRegion The default region to use. * @return */ public Builder defaultRegion(Region defaultRegion) { this.defaultRegion_ = defaultRegion; return this; } /** * Provides a custom factory function that will vend KMS clients. This is provided for advanced * use cases which require complete control over the client construction process. * * <p>Because the regional client supplier fully controls the client construction process, it is * not possible to configure the client through methods such as {@link * #builderSupplier(Supplier)}; if you try to use these in combination, an {@link * IllegalStateException} will be thrown. * * <p>Note: The AWS Encryption SDK for Java does not support the {@code KmsAsyncClient} * interface. * * @param regionalClientSupplier * @return */ public Builder customRegionalClientSupplier(RegionalClientSupplier regionalClientSupplier) { if (builderSupplier_ != null) { throw clientSupplierComboException(); } regionalClientSupplier_ = regionalClientSupplier; return this; } /** * Configures the {@link KmsMasterKeyProvider} to use settings from this {@link * KmsClientBuilder} to configure KMS clients. Note that the region set on this builder will be * ignored, but all other settings will be propagated into the regional clients. * * <p>Trying to use this method in combination with {@link * #customRegionalClientSupplier(RegionalClientSupplier)} will cause an {@link * IllegalStateException} to be thrown. * * <p>Note: The AWS Encryption SDK for Java does not support the {@code KmsAsyncClient} * interface. * * @param supplier Should return a new {@link KmsClientBuilder} on each invocation. * @return */ public Builder builderSupplier(Supplier<KmsClientBuilder> supplier) { if (regionalClientSupplier_ != null) { throw clientSupplierComboException(); } this.builderSupplier_ = supplier; return this; } private RuntimeException clientSupplierComboException() { return new IllegalStateException( "only one of builderSupplier and customRegionalClientSupplier may be used"); } /** * Builds the master key provider in Discovery Mode. In Discovery Mode the KMS Master Key * Provider will attempt to decrypt using any key identifier it discovers in the encrypted * message. KMS Master Key Providers in Discovery Mode will not encrypt data keys. * * @return */ public KmsMasterKeyProvider buildDiscovery() { final boolean isDiscovery = true; RegionalClientSupplier supplier = clientFactory(); return new KmsMasterKeyProvider( supplier, defaultRegion_, emptyList(), emptyList(), isDiscovery, discoveryFilter_); } /** * Builds the master key provider in Discovery Mode with a {@link DiscoveryFilter}. In Discovery * Mode the KMS Master Key Provider will attempt to decrypt using any key identifier it * discovers in the encrypted message that is accepted by the {@code filter}. KMS Master Key * Providers in Discovery Mode will not encrypt data keys. * * @param filter * @return */ public KmsMasterKeyProvider buildDiscovery(DiscoveryFilter filter) { if (filter == null) { throw new IllegalArgumentException( "Discovery filter must not be null if specifying " + "a discovery filter."); } discoveryFilter_ = filter; return buildDiscovery(); } /** * Builds the master key provider in Strict Mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For providers that will only be used * for encryption, you can use any valid KMS key identifier. For providers that will be used for * decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not supported. * * @param keyIds * @return */ public KmsMasterKeyProvider buildStrict(List<String> keyIds) { if (keyIds == null) { throw new IllegalArgumentException( "Strict mode must be configured with a non-empty " + "list of keyIds."); } final boolean isDiscovery = false; RegionalClientSupplier supplier = clientFactory(); return new KmsMasterKeyProvider( supplier, defaultRegion_, new ArrayList<>(keyIds), emptyList(), isDiscovery, null); } /** * Builds the master key provider in strict mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For providers that will only be used * for encryption, you can use any valid KMS key identifier. For providers that will be used for * decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not supported. * * @param keyIds * @return */ public KmsMasterKeyProvider buildStrict(String... keyIds) { return buildStrict(asList(keyIds)); } RegionalClientSupplier clientFactory() { if (regionalClientSupplier_ != null) { return regionalClientSupplier_; } ConcurrentHashMap<Region, KmsClient> clientCache = new ConcurrentHashMap<>(); snoopClientCache(clientCache); return region -> { KmsClient client = clientCache.get(region); if (client != null) return client; KmsClientBuilder builder = builderSupplier_ != null ? builderSupplier_.get() : KmsClient.builder(); // We can't just use computeIfAbsent as we need to avoid leaking KMS clients if we're asked // to decrypt // an EDK with a bogus region in its ARN. So we'll install a request handler to identify the // first // successful call, and cache it when we see that. RequestClientCacher cacher = new RequestClientCacher(clientCache, region); ClientOverrideConfiguration overrideConfig = builder.overrideConfiguration().toBuilder().addExecutionInterceptor(cacher).build(); client = builder.region(region).overrideConfiguration(overrideConfig).build(); return cacher.setClient(client); }; } protected void snoopClientCache(ConcurrentHashMap<Region, KmsClient> map) { // no-op - this is a test hook } } public static Builder builder() { return new Builder(); } KmsMasterKeyProvider( RegionalClientSupplier supplier, Region defaultRegion, List<String> keyIds, List<String> grantTokens, boolean isDiscovery, DiscoveryFilter discoveryFilter) { if (!isDiscovery && (keyIds == null || keyIds.isEmpty())) { throw new IllegalArgumentException( "Strict mode must be configured with a non-empty " + "list of keyIds."); } if (!isDiscovery && keyIds.contains(null)) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "null key identifier."); } if (!isDiscovery && discoveryFilter != null) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "discovery filter."); } // If we don't have a default region, we need to check that all key IDs will be usable if (!isDiscovery && defaultRegion == null) { for (String keyId : keyIds) { final AwsKmsCmkArnInfo arnInfo = parseInfoFromKeyArn(keyId); if (arnInfo == null) { throw new AwsCryptoException( "Can't use non-ARN key identifiers or aliases when " + "no default region is set"); } } } this.regionalClientSupplier_ = supplier; this.defaultRegion_ = defaultRegion; this.keyIds_ = Collections.unmodifiableList(new ArrayList<>(keyIds)); this.isDiscovery_ = isDiscovery; this.discoveryFilter_ = discoveryFilter; this.grantTokens_ = grantTokens; } /** Returns "aws-kms" */ @Override public String getDefaultProviderId() { return PROVIDER_NAME; } @Override public KmsMasterKey getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { if (!canProvide(provider)) { throw new UnsupportedProviderException(); } if (!isDiscovery_ && !keyIds_.contains(keyId)) { throw new NoSuchMasterKeyException("Key must be in supplied list of keyIds."); } final AwsKmsCmkArnInfo arnInfo = parseInfoFromKeyArn(keyId); if (isDiscovery_ && discoveryFilter_ != null && (arnInfo == null)) { throw new NoSuchMasterKeyException( "Cannot use non-ARN key identifiers or aliases if " + "discovery filter is configured."); } else if (isDiscovery_ && discoveryFilter_ != null && !discoveryFilter_.allowsPartitionAndAccount( arnInfo.getPartition(), arnInfo.getAccountId())) { throw new NoSuchMasterKeyException( "Cannot use key in partition " + arnInfo.getPartition() + " with account id " + arnInfo.getAccountId() + " with configured discovery filter."); } Region region = defaultRegion_; if (arnInfo != null) { region = Region.of(arnInfo.getRegion()); } final Region region_ = region; Supplier<KmsClient> kmsSupplier = () -> { KmsClient client = regionalClientSupplier_.getClient(region_); if (client == null) { throw new AwsCryptoException("Can't use keys from region " + region_.id()); } return client; }; final KmsMasterKey result = KmsMasterKey.getInstance(kmsSupplier, keyId, this); result.setGrantTokens(grantTokens_); return result; } /** Returns all CMKs provided to the constructor of this object. */ @Override public List<KmsMasterKey> getMasterKeysForEncryption(final MasterKeyRequest request) { if (keyIds_ == null) { return emptyList(); } List<KmsMasterKey> result = new ArrayList<>(keyIds_.size()); for (String id : keyIds_) { result.add(getMasterKey(id)); } return result; } @Override public DataKey<KmsMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); for (final EncryptedDataKey edk : encryptedDataKeys) { if (canProvide(edk.getProviderId())) { try { final String keyArn = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); // This will throw if we can't use this key for whatever reason return getMasterKey(keyArn) .decryptDataKey(algorithm, singletonList(edk), encryptionContext); } catch (final Exception ex) { exceptions.add(ex); } } } throw buildCannotDecryptDksException(exceptions); } /** * @deprecated This method is inherently not thread safe. Use {@link * KmsMasterKey#setGrantTokens(List)} instead. {@link KmsMasterKeyProvider}s constructed using * the builder will throw an exception on attempts to modify the list of grant tokens. */ @Deprecated @Override public void setGrantTokens(final List<String> grantTokens) { try { this.grantTokens_.clear(); this.grantTokens_.addAll(grantTokens); } catch (UnsupportedOperationException e) { throw grantTokenError(); } } @Override public List<String> getGrantTokens() { return new ArrayList<>(grantTokens_); } /** * @deprecated This method is inherently not thread safe. Use {@link #withGrantTokens(List)} or * {@link KmsMasterKey#setGrantTokens(List)} instead. {@link KmsMasterKeyProvider}s * constructed using the builder will throw an exception on attempts to modify the list of * grant tokens. */ @Deprecated @Override public void addGrantToken(final String grantToken) { try { grantTokens_.add(grantToken); } catch (UnsupportedOperationException e) { throw grantTokenError(); } } private RuntimeException grantTokenError() { return new IllegalStateException( "This master key provider is immutable. Use withGrantTokens instead."); } /** * Returns a new {@link KmsMasterKeyProvider} that is configured identically to this one, except * with the given list of grant tokens. The grant token list in the returned provider is immutable * (but can be further overridden by invoking withGrantTokens again). * * @param grantTokens * @return */ public KmsMasterKeyProvider withGrantTokens(List<String> grantTokens) { grantTokens = Collections.unmodifiableList(new ArrayList<>(grantTokens)); return new KmsMasterKeyProvider( regionalClientSupplier_, defaultRegion_, keyIds_, grantTokens, isDiscovery_, discoveryFilter_); } /** * Returns a new {@link KmsMasterKeyProvider} that is configured identically to this one, except * with the given list of grant tokens. The grant token list in the returned provider is immutable * (but can be further overridden by invoking withGrantTokens again). * * @param grantTokens * @return */ public KmsMasterKeyProvider withGrantTokens(String... grantTokens) { return withGrantTokens(asList(grantTokens)); } }
5,461
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKey.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.*; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.KmsMethods; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Consumer; import java.util.function.Supplier; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.*; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.5 // # MUST implement the Master Key Interface (../master-key- // # interface.md#interface) // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.7 // # MUST be unchanged from the Master Key interface. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.8 // # MUST be unchanged from the Master Key interface. /** * Represents a single Aws KMS key and is used to encrypt/decrypt data with {@link AwsCrypto}. This * key may be a multi region key, in which case this component is able to recognize different * regional replicas of this multi region key as the same. */ public final class AwsKmsMrkAwareMasterKey extends MasterKey<AwsKmsMrkAwareMasterKey> implements KmsMethods { static final ApiName API_NAME = ApiName.builder().name(VersionInfo.apiName()).version(VersionInfo.versionNumber()).build(); private static final Consumer<AwsRequestOverrideConfiguration.Builder> API_NAME_INTERCEPTOR = builder -> builder.addApiName(API_NAME); private final KmsClient kmsClient_; private final List<String> grantTokens_ = new ArrayList<>(); private final String awsKmsIdentifier_; private final MasterKeyProvider<AwsKmsMrkAwareMasterKey> sourceProvider_; /** * A light builder method. * * @see KmsMasterKey#getInstance(Supplier, String, MasterKeyProvider) * @param kms An AWS KMS Client * @param awsKmsIdentifier An identifier for an AWS KMS key. May be a raw resource. */ static AwsKmsMrkAwareMasterKey getInstance( final KmsClient kms, final String awsKmsIdentifier, final MasterKeyProvider<AwsKmsMrkAwareMasterKey> provider) { return new AwsKmsMrkAwareMasterKey(awsKmsIdentifier, kms, provider); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # On initialization, the caller MUST provide: private AwsKmsMrkAwareMasterKey( final String awsKmsIdentifier, final KmsClient kmsClient, final MasterKeyProvider<AwsKmsMrkAwareMasterKey> provider) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The AWS KMS key identifier MUST NOT be null or empty. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The AWS KMS // # key identifier MUST be a valid identifier (aws-kms-key-arn.md#a- // # valid-aws-kms-identifier). validAwsKmsIdentifier(awsKmsIdentifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The AWS KMS SDK client MUST not be null. if (kmsClient == null) { throw new IllegalArgumentException( "AwsKmsMrkAwareMasterKey must be configured with an AWS KMS client."); } /* Precondition: A provider is required. */ if (provider == null) { throw new IllegalArgumentException( "AwsKmsMrkAwareMasterKey must be configured with a source provider."); } kmsClient_ = kmsClient; awsKmsIdentifier_ = awsKmsIdentifier; sourceProvider_ = provider; } @Override public String getProviderId() { return sourceProvider_.getDefaultProviderId(); } @Override public String getKeyId() { return awsKmsIdentifier_; } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // # The master key MUST be able to be configured with an optional list of // # Grant Tokens. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=exception // # This configuration SHOULD be on initialization and // # SHOULD be immutable. // The existing KMS Master Key // sets grants in this way, so we continue this interface. /** Clears and sets all grant tokens on this instance. This is not thread safe. */ @Override public void setGrantTokens(final List<String> grantTokens) { grantTokens_.clear(); grantTokens_.addAll(grantTokens); } @Override public List<String> getGrantTokens() { return grantTokens_; } @Override public void addGrantToken(final String grantToken) { grantTokens_.add(grantToken); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The inputs MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. /** * This is identical behavior to * * @see KmsMasterKey#generateDataKey(CryptoAlgorithm, Map) */ @Override public DataKey<AwsKmsMrkAwareMasterKey> generateDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # This // # master key MUST use the configured AWS KMS client to make an AWS KMS // # GenerateDatakey (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_GenerateDataKey.html) request constructed as follows: final GenerateDataKeyResponse gdkResponse = kmsClient_.generateDataKey( GenerateDataKeyRequest.builder() .overrideConfiguration(API_NAME_INTERCEPTOR) .keyId(awsKmsIdentifier_) .numberOfBytes(algorithm.getDataKeyLength()) .encryptionContext(encryptionContext) .grantTokens(grantTokens_) .build()); final ByteBuffer plaintextBuffer = gdkResponse.plaintext().asByteBuffer(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # If the call succeeds the AWS KMS Generate Data Key response's // # "Plaintext" MUST match the key derivation input length specified by // # the algorithm suite included in the input. if (plaintextBuffer.limit() != algorithm.getDataKeyLength()) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; plaintextBuffer.get(rawKey); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The response's "KeyId" // # MUST be valid. final String gdkResponseKeyId = gdkResponse.keyId(); /* Exceptional Postcondition: Must have an AWS KMS ARN from AWS KMS generateDataKey. */ if (parseInfoFromKeyArn(gdkResponseKeyId) == null) { throw new IllegalStateException("Received an empty or invalid keyId from KMS"); } final ByteBuffer ciphertextBlobBuffer = gdkResponse.ciphertextBlob().asByteBuffer(); final byte[] encryptedKey = new byte[ciphertextBlobBuffer.remaining()]; ciphertextBlobBuffer.get(encryptedKey); final SecretKeySpec key = new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The output MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. return new DataKey<>( // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The response's "Plaintext" MUST be the plaintext in // # the output. key, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // # The response's cipher text blob MUST be used as the // # returned as the ciphertext for the encrypted data key in the output. encryptedKey, gdkResponseKeyId.getBytes(StandardCharsets.UTF_8), this); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The inputs MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. /** @see KmsMasterKey#encryptDataKey(CryptoAlgorithm, Map, DataKey) */ @Override public DataKey<AwsKmsMrkAwareMasterKey> encryptDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext, final DataKey<?> dataKey) { final SecretKey key = dataKey.getKey(); /* Precondition: The key format MUST be RAW. */ if (!key.getFormat().equals("RAW")) { throw new IllegalArgumentException("Only RAW encoded keys are supported"); } try { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The master // # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Encrypt.html) request constructed as follows: final EncryptResponse encryptResponse = kmsClient_.encrypt( EncryptRequest.builder() .overrideConfiguration(API_NAME_INTERCEPTOR) .keyId(awsKmsIdentifier_) .plaintext(SdkBytes.fromByteArray(key.getEncoded())) .encryptionContext(encryptionContext) .grantTokens(grantTokens_) .build()); final ByteBuffer ciphertextBlobBuffer = encryptResponse.ciphertextBlob().asByteBuffer(); final byte[] edk = new byte[ciphertextBlobBuffer.remaining()]; ciphertextBlobBuffer.get(edk); final String encryptResultKeyId = encryptResponse.keyId(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The AWS KMS Encrypt response MUST contain a valid "KeyId". /* Postcondition: Must have an AWS KMS ARN from AWS KMS encrypt. */ if (parseInfoFromKeyArn(encryptResultKeyId) == null) { throw new IllegalStateException("Received an empty or invalid keyId from KMS"); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The output MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. return new DataKey<>( dataKey.getKey(), // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // # The // # response's cipher text blob MUST be used as the "ciphertext" for the // # encrypted data key. edk, encryptResultKeyId.getBytes(StandardCharsets.UTF_8), this); } catch (final AwsServiceException asex) { throw new AwsCryptoException(asex); } } /** * Will attempt to decrypt if awsKmsArnMatchForDecrypt returns true in {@link * AwsKmsMrkAwareMasterKey#filterEncryptedDataKeys(String, String, EncryptedDataKey)}. An * extension of {@link KmsMasterKey#decryptDataKey(CryptoAlgorithm, Collection, Map)} but with an * awareness of the properties of multi-Region keys. */ @Override // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The inputs MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. public DataKey<AwsKmsMrkAwareMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); final String providerId = this.getProviderId(); return encryptedDataKeys.stream() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. .filter(edk -> filterEncryptedDataKeys(providerId, awsKmsIdentifier_, edk)) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # For each encrypted data key in the filtered set, one at a time, the // # master key MUST attempt to decrypt the data key. .map( edk -> { try { return decryptSingleEncryptedDataKey( this, kmsClient_, awsKmsIdentifier_, grantTokens_, algorithm, edk, encryptionContext); } catch (final AwsServiceException amazonServiceException) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If this attempt // # results in an error, then these errors MUST be collected. exceptions.add(amazonServiceException); } return null; }) /* Need to filter null * because an Optional * of a null is crazy. * Therefore `findFirst` will throw * if it sees `null`. */ .filter(Objects::nonNull) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If the AWS KMS response satisfies the requirements then it MUST be // # use and this function MUST return and not attempt to decrypt any more // # encrypted data keys. /* Order is important. * Process the encrypted data keys in the order they exist in the encrypted message. */ .findFirst() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The output MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. /* Exceptional Postcondition: Master key was unable to decrypt. */ .orElseThrow(() -> buildCannotDecryptDksException(exceptions)); } /** * Pure function for decrypting and encrypted data key. This is refactored out of `decryptDataKey` * to facilitate testing to ensure correctness. */ static DataKey<AwsKmsMrkAwareMasterKey> decryptSingleEncryptedDataKey( final AwsKmsMrkAwareMasterKey masterKey, final KmsClient client, final String awsKmsIdentifier, final List<String> grantTokens, final CryptoAlgorithm algorithm, final EncryptedDataKey edk, final Map<String, String> encryptionContext) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # To decrypt the encrypted data key this master key MUST use the // # configured AWS KMS client to make an AWS KMS Decrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Decrypt.html) request constructed as follows: final DecryptResponse decryptResponse = client.decrypt( DecryptRequest.builder() .overrideConfiguration(API_NAME_INTERCEPTOR) .ciphertextBlob(SdkBytes.fromByteArray(edk.getEncryptedDataKey())) .encryptionContext(encryptionContext) .grantTokens(grantTokens) .keyId(awsKmsIdentifier) .build()); final String decryptResponseKeyId = decryptResponse.keyId(); /* Exceptional Postcondition: Must have a CMK ARN from AWS KMS to match. */ if (decryptResponseKeyId == null) { throw new IllegalStateException("Received an empty keyId from KMS"); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # If the call succeeds then the response's "KeyId" MUST be equal to the // # configured AWS KMS key identifier otherwise the function MUST collect // # an error. if (!awsKmsIdentifier.equals(decryptResponseKeyId)) { throw new IllegalStateException( "Received an invalid response from KMS Decrypt call: Unexpected keyId."); } final ByteBuffer plaintextBuffer = decryptResponse.plaintext().asByteBuffer(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # The response's "Plaintext"'s length MUST equal the length // # required by the requested algorithm suite otherwise the function MUST // # collect an error. if (plaintextBuffer.limit() != algorithm.getDataKeyLength()) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; plaintextBuffer.get(rawKey); return new DataKey<>( new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()), edk.getEncryptedDataKey(), edk.getProviderInformation(), masterKey); } /** * A pure function to filter encrypted data keys. This function is refactored out from * `decryptDataKey` to facilitate testing and ensure correctness. * * <p>An AWS KMS Master key should only attempt to process an Encrypted Data Key if the * information in the Encrypted Data Key matches the master keys configuration. */ static boolean filterEncryptedDataKeys( final String providerId, final String awsKmsIdentifier_, final EncryptedDataKey edk) { final String edkKeyId = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); final AwsKmsCmkArnInfo providerArnInfo = parseInfoFromKeyArn(edkKeyId); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # Additionally each provider info MUST be a valid AWS KMS ARN // # (aws-kms-key-arn.md#a-valid-aws-kms-arn) with a resource type of // # "key". if (providerArnInfo == null || !"key".equals(providerArnInfo.getResourceType())) { throw new IllegalStateException("Invalid provider info in message."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms" and the the // # function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-for- // # decrypt.md#implementation) called with the configured AWS KMS key // # identifier and the encrypted data key's provider info MUST return // # "true". return edk.getProviderId().equals(providerId) && awsKmsArnMatchForDecrypt(awsKmsIdentifier_, edkKeyId); } }
5,462
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/KmsMasterKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.kmssdkv2; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.KmsMethods; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.*; /** * Represents a single Customer Master Key (CMK) and is used to encrypt/decrypt data with {@link * AwsCrypto}. * * <p>This component is not multi-Region key aware, and will treat every AWS KMS identifier as * regionally isolated. */ public final class KmsMasterKey extends MasterKey<KmsMasterKey> implements KmsMethods { private static final ApiName API_NAME = ApiName.builder().name(VersionInfo.apiName()).version(VersionInfo.versionNumber()).build(); private static final Consumer<AwsRequestOverrideConfiguration.Builder> API_NAME_INTERCEPTOR = builder -> builder.addApiName(API_NAME); private final Supplier<KmsClient> clientSupplier_; private final MasterKeyProvider<KmsMasterKey> sourceProvider_; private final String id_; private final List<String> grantTokens_ = new ArrayList<>(); static KmsMasterKey getInstance( final Supplier<KmsClient> clientSupplier, final String id, final MasterKeyProvider<KmsMasterKey> provider) { return new KmsMasterKey(clientSupplier, id, provider); } private KmsMasterKey( final Supplier<KmsClient> clientSupplier, final String id, final MasterKeyProvider<KmsMasterKey> provider) { clientSupplier_ = clientSupplier; id_ = id; sourceProvider_ = provider; } @Override public String getProviderId() { return sourceProvider_.getDefaultProviderId(); } @Override public String getKeyId() { return id_; } @Override public DataKey<KmsMasterKey> generateDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext) { final GenerateDataKeyResponse gdkResponse = clientSupplier_ .get() .generateDataKey( GenerateDataKeyRequest.builder() .overrideConfiguration(API_NAME_INTERCEPTOR) .keyId(getKeyId()) .numberOfBytes(algorithm.getDataKeyLength()) .encryptionContext(encryptionContext) .grantTokens(grantTokens_) .build()); final ByteBuffer plaintextBuffer = gdkResponse.plaintext().asByteBuffer(); if (plaintextBuffer.limit() != algorithm.getDataKeyLength()) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; plaintextBuffer.get(rawKey); final ByteBuffer ciphertextBlobBuffer = gdkResponse.ciphertextBlob().asByteBuffer(); final byte[] encryptedKey = new byte[ciphertextBlobBuffer.remaining()]; ciphertextBlobBuffer.get(encryptedKey); final String gdkResponseKeyId = gdkResponse.keyId(); final SecretKeySpec key = new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()); return new DataKey<>( key, encryptedKey, gdkResponseKeyId.getBytes(StandardCharsets.UTF_8), this); } @Override public void setGrantTokens(final List<String> grantTokens) { grantTokens_.clear(); grantTokens_.addAll(grantTokens); } @Override public List<String> getGrantTokens() { return grantTokens_; } @Override public void addGrantToken(final String grantToken) { grantTokens_.add(grantToken); } @Override public DataKey<KmsMasterKey> encryptDataKey( final CryptoAlgorithm algorithm, final Map<String, String> encryptionContext, final DataKey<?> dataKey) { final SecretKey key = dataKey.getKey(); if (!key.getFormat().equals("RAW")) { throw new IllegalArgumentException("Only RAW encoded keys are supported"); } try { final EncryptResponse encryptResponse = clientSupplier_ .get() .encrypt( EncryptRequest.builder() .overrideConfiguration(API_NAME_INTERCEPTOR) .keyId(id_) .plaintext(SdkBytes.fromByteArray(key.getEncoded())) .encryptionContext(encryptionContext) .grantTokens(grantTokens_) .build()); final ByteBuffer ciphertextBlobBuffer = encryptResponse.ciphertextBlob().asByteBuffer(); final byte[] edk = new byte[ciphertextBlobBuffer.remaining()]; ciphertextBlobBuffer.get(edk); final String encryptResultKeyId = encryptResponse.keyId(); return new DataKey<>( dataKey.getKey(), edk, encryptResultKeyId.getBytes(StandardCharsets.UTF_8), this); } catch (final AwsServiceException asex) { throw new AwsCryptoException(asex); } } @Override public DataKey<KmsMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); for (final EncryptedDataKey edk : encryptedDataKeys) { try { final String edkKeyId = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); if (!edkKeyId.equals(id_)) { continue; } final DecryptResponse decryptResponse = clientSupplier_ .get() .decrypt( DecryptRequest.builder() .overrideConfiguration(API_NAME_INTERCEPTOR) .ciphertextBlob(SdkBytes.fromByteArray(edk.getEncryptedDataKey())) .encryptionContext(encryptionContext) .grantTokens(grantTokens_) .keyId(edkKeyId) .build()); final String decryptResponseKeyId = decryptResponse.keyId(); if (decryptResponseKeyId == null) { throw new IllegalStateException("Received an empty keyId from KMS"); } if (decryptResponseKeyId.equals(id_)) { final ByteBuffer plaintextBuffer = decryptResponse.plaintext().asByteBuffer(); if (plaintextBuffer.limit() != algorithm.getDataKeyLength()) { throw new IllegalStateException("Received an unexpected number of bytes from KMS"); } final byte[] rawKey = new byte[algorithm.getDataKeyLength()]; plaintextBuffer.get(rawKey); return new DataKey<>( new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()), edk.getEncryptedDataKey(), edk.getProviderInformation(), this); } } catch (final AwsServiceException awsex) { exceptions.add(awsex); } } throw buildCannotDecryptDksException(exceptions); } }
5,463
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/RequestClientCacher.java
package com.amazonaws.encryptionsdk.kmssdkv2; import java.util.concurrent.ConcurrentHashMap; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; class RequestClientCacher implements ExecutionInterceptor { private final ConcurrentHashMap<Region, KmsClient> cache_; private final Region region_; private KmsClient client_; volatile boolean ranBefore_ = false; RequestClientCacher(final ConcurrentHashMap<Region, KmsClient> cache, final Region region) { this.region_ = region; this.cache_ = cache; } public KmsClient setClient(final KmsClient client) { client_ = client; return client; } @Override public void afterExecution( Context.AfterExecution context, ExecutionAttributes executionAttributes) { if (ranBefore_) { return; } ranBefore_ = true; cache_.putIfAbsent(region_, client_); } @Override public void onExecutionFailure( Context.FailedExecution context, ExecutionAttributes executionAttributes) { if (ranBefore_) { return; } if (!(context.exception() instanceof AwsServiceException)) { return; } ranBefore_ = true; cache_.putIfAbsent(region_, client_); } }
5,464
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKeyProvider.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.*; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; import java.util.stream.Collectors; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.KmsClientBuilder; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.5 // # MUST implement the Master Key Provider Interface (../master-key- // # provider-interface.md#interface) /** * Represents a list Aws KMS keys and is used to encrypt/decrypt data with {@link AwsCrypto}. Some * of these keys may be multi region keys, in which case this component is able to recognize * different regional replicas of this multi region key as the same. */ public final class AwsKmsMrkAwareMasterKeyProvider extends MasterKeyProvider<AwsKmsMrkAwareMasterKey> { private static final String PROVIDER_NAME = "aws-kms"; private final List<String> keyIds_; private final List<String> grantTokens_; private final boolean isDiscovery_; private final DiscoveryFilter discoveryFilter_; private final Region discoveryMrkRegion_; private final RegionalClientSupplier regionalClientSupplier_; private final Region defaultRegion_; public static class Builder implements Cloneable { private Region defaultRegion_ = getSdkDefaultRegion(); private Supplier<KmsClientBuilder> builderSupplier_ = null; private RegionalClientSupplier regionalClientSupplier_ = null; private DiscoveryFilter discoveryFilter_ = null; private Region discoveryMrkRegion_ = this.defaultRegion_; Builder() { // Default access: Don't allow outside classes to extend this class } public Builder clone() { try { Builder cloned = (Builder) super.clone(); cloned.builderSupplier_ = builderSupplier_; return cloned; } catch (CloneNotSupportedException e) { throw new Error("Impossible: CloneNotSupportedException", e); } } /** * Sets the default region. This region will be used when specifying key IDs for encryption or * in {@link AwsKmsMrkAwareMasterKeyProvider#getMasterKey(String)} that are not full ARNs, but * are instead bare key IDs or aliases. * * <p>If the default region is not specified, the AWS SDK default region will be used. * * @see KmsMasterKeyProvider.Builder#defaultRegion(Region) * @param defaultRegion The default region to use. */ public Builder defaultRegion(Region defaultRegion) { this.defaultRegion_ = defaultRegion; return this; } /** * Sets the region contacted for multi-region keys when in Discovery mode. This region will be * used when a multi-region key is discovered on decrypt by {@link * AwsKmsMrkAwareMasterKeyProvider#getMasterKey(String)}. * * <p> * * @param discoveryMrkRegion The region to contact to attempt to decrypt multi-region keys. */ public Builder discoveryMrkRegion(Region discoveryMrkRegion) { this.discoveryMrkRegion_ = discoveryMrkRegion; return this; } /** * Provides a custom factory function that will vend KMS clients. This is provided for advanced * use cases which require complete control over the client construction process. * * <p>Because the regional client supplier fully controls the client construction process, it is * not possible to configure the client through methods such as {@link * #builderSupplier(Supplier)}; if you try to use these in combination, an {@link * IllegalStateException} will be thrown. * * <p>Note: The AWS Encryption SDK for Java does not support the {@code KmsAsyncClient} * interface. * * @see KmsMasterKeyProvider.Builder#customRegionalClientSupplier(RegionalClientSupplier) */ public Builder customRegionalClientSupplier(RegionalClientSupplier regionalClientSupplier) { if (builderSupplier_ != null) { throw clientSupplierComboException(); } regionalClientSupplier_ = regionalClientSupplier; return this; } /** * Configures the {@link AwsKmsMrkAwareMasterKeyProvider} to use settings from this {@link * KmsClientBuilder} to configure KMS clients. Note that the region set on this builder will be * ignored, but all other settings will be propagated into the regional clients. * * <p>Note: The AWS Encryption SDK for Java does not support the {@code KmsAsyncClient} * interface. * * @see KmsMasterKeyProvider.Builder#builderSupplier(Supplier) */ public Builder builderSupplier(Supplier<KmsClientBuilder> supplier) { if (regionalClientSupplier_ != null) { throw clientSupplierComboException(); } this.builderSupplier_ = supplier; return this; } private RuntimeException clientSupplierComboException() { return new IllegalStateException( "only one of builderSupplier and customRegionalClientSupplier may be used"); } /** * Builds the master key provider in Discovery Mode. In Discovery Mode the KMS Master Key * Provider will attempt to decrypt using any key identifier it discovers in the encrypted * message. KMS Master Key Providers in Discovery Mode will not encrypt data keys. * * @see KmsMasterKeyProvider.Builder#buildDiscovery() */ public AwsKmsMrkAwareMasterKeyProvider buildDiscovery() { final boolean isDiscovery = true; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The regional client // # supplier MUST be defined in discovery mode. RegionalClientSupplier clientSupplier = regionalClientSupplier_; if (clientSupplier == null) { clientSupplier = clientFactory(new ConcurrentHashMap<>(), builderSupplier_); } return new AwsKmsMrkAwareMasterKeyProvider( clientSupplier, defaultRegion_, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The key id list MUST be empty in discovery mode. emptyList(), emptyList(), isDiscovery, discoveryFilter_, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # In // # discovery mode if a default MRK Region is not configured the AWS SDK // # Default Region MUST be used. discoveryMrkRegion_ == null ? defaultRegion_ : discoveryMrkRegion_); } /** * Builds the master key provider in Discovery Mode with a {@link DiscoveryFilter}. In Discovery * Mode the KMS Master Key Provider will attempt to decrypt using any key identifier it * discovers in the encrypted message that is accepted by the {@code filter}. KMS Master Key * Providers in Discovery Mode will not encrypt data keys. * * @see KmsMasterKeyProvider.Builder#buildDiscovery(DiscoveryFilter) */ public AwsKmsMrkAwareMasterKeyProvider buildDiscovery(DiscoveryFilter filter) { discoveryFilter_ = filter; return buildDiscovery(); } /** * Builds the master key provider in Strict Mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For Master Key Providers that will only * be used for encryption, you can use any valid KMS key identifier. For providers that will be * used for decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not * supported. * * @see KmsMasterKeyProvider.Builder#buildStrict(List) */ public AwsKmsMrkAwareMasterKeyProvider buildStrict(List<String> keyIds) { final boolean isDiscovery = false; RegionalClientSupplier clientSupplier = regionalClientSupplier_; if (clientSupplier == null) { clientSupplier = clientFactory(new ConcurrentHashMap<>(), builderSupplier_); } return new AwsKmsMrkAwareMasterKeyProvider( clientSupplier, defaultRegion_, new ArrayList<>(keyIds), emptyList(), isDiscovery, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # A discovery filter MUST NOT be configured in strict mode. null, // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # A default MRK Region MUST NOT be configured in strict mode. null); } /** * Builds the master key provider in strict mode. KMS Master Key Providers in Strict Mode will * only attempt to decrypt using key ARNs listed in {@code keyIds}. KMS Master Key Providers in * Strict Mode will encrypt data keys using the keys listed in {@code keyIds} * * <p>In Strict Mode, one or more CMKs must be provided. For Master Key Providers that will only * be used for encryption, you can use any valid KMS key identifier. For providers that will be * used for decryption, you must use the key ARN; key ids, alias names, and alias ARNs are not * supported. * * @see KmsMasterKeyProvider.Builder#buildStrict(String...) */ public AwsKmsMrkAwareMasterKeyProvider buildStrict(String... keyIds) { return buildStrict(asList(keyIds)); } static RegionalClientSupplier clientFactory( ConcurrentHashMap<Region, KmsClient> clientCache, Supplier<KmsClientBuilder> builderSupplier) { return region -> { /* Check for early return (Postcondition): If a client already exists, use that. */ if (clientCache.containsKey(region)) { return clientCache.get(region); } KmsClientBuilder builder = builderSupplier != null ? builderSupplier.get() : KmsClient.builder(); // We can't just use computeIfAbsent as we need to avoid leaking KMS clients if we're asked // to decrypt // an EDK with a bogus region in its ARN. So we'll install a request handler to identify the // first // successful call, and cache it when we see that. final RequestClientCacher cacher = new RequestClientCacher(clientCache, region); KmsClient client = builder .region(region) .overrideConfiguration(config -> config.addExecutionInterceptor(cacher)) .build(); return cacher.setClient(client); }; } /** * The AWS SDK has a default process for evaluating the default Region. This returns null if no * default region is found. Because a default region _may_ not be needed. */ private static Region getSdkDefaultRegion() { try { return new DefaultAwsRegionProviderChain().getRegion(); } catch (SdkClientException ex) { return null; } } } public static Builder builder() { return new Builder(); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # On initialization the caller MUST provide: private AwsKmsMrkAwareMasterKeyProvider( RegionalClientSupplier supplier, Region defaultRegion, List<String> keyIds, List<String> grantTokens, boolean isDiscovery, DiscoveryFilter discoveryFilter, Region discoveryMrkRegion) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The key id list MUST NOT be empty or null in strict mode. if (!isDiscovery && (keyIds == null || keyIds.isEmpty())) { throw new IllegalArgumentException( "Strict mode must be configured with a non-empty " + "list of keyIds."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # The key id // # list MUST NOT contain any null or empty string values. if (!isDiscovery && (keyIds.contains(null) || keyIds.contains(""))) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "null key identifier."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # All AWS KMS // # key identifiers are be passed to Assert AWS KMS MRK are unique (aws- // # kms-mrk-are-unique.md#Implementation) and the function MUST return // # success. assertMrksAreUnique(keyIds); /* Precondition: A region is required to contact AWS KMS. * This is an edge case because the default region will be the same as the SDK default, * but it is still possible. */ if (!isDiscovery && defaultRegion == null && keyIds.stream().map(AwsKmsCmkArnInfo::parseInfoFromKeyArn).anyMatch(Objects::isNull)) { throw new AwsCryptoException( "Can't use non-ARN key identifiers or aliases when " + "no default region is set"); } /* Precondition: Discovery filter is only valid in discovery mode. */ if (!isDiscovery && discoveryFilter != null) { throw new IllegalArgumentException( "Strict mode cannot be configured with a " + "discovery filter."); } /* Precondition: Discovery mode can not have any keys to filter. */ if (isDiscovery && !keyIds.isEmpty()) { throw new IllegalArgumentException("Discovery mode can not be configured with keys."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // # If an AWS SDK Default Region can not be // # obtained initialization MUST fail. if (isDiscovery && discoveryMrkRegion == null) { throw new IllegalArgumentException("Discovery MRK region can not be null."); } this.regionalClientSupplier_ = supplier; this.defaultRegion_ = defaultRegion; this.keyIds_ = Collections.unmodifiableList(new ArrayList<>(keyIds)); this.isDiscovery_ = isDiscovery; this.discoveryFilter_ = discoveryFilter; this.discoveryMrkRegion_ = discoveryMrkRegion; this.grantTokens_ = grantTokens; } // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # The caller MUST provide: /** Refactored into a pure function to facilitate testing and correctness. */ static void assertMrksAreUnique(List<String> keyIdentifiers) { List<String> duplicateMultiRegionKeyIdentifiers = keyIdentifiers.stream() /* Collect a map of resource to identifier. * This lets me group duplicates by "resource". * This is because the identifier can be either an ARN or a raw identifier. * By having the both the key id and the identifier I can ensure the uniqueness of * the key id and the error message to the caller can contain both identifiers * to facilitate debugging. */ .collect( Collectors.groupingBy( AwsKmsMrkAwareMasterKeyProvider::getResourceForResourceTypeKey)) .entrySet() .stream() // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # If there are zero duplicate resource ids between the multi-region // # keys, this function MUST exit successfully .filter(maybeDuplicate -> maybeDuplicate.getValue().size() > 1) // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # If the list does not contain any multi-Region keys (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) this function MUST // # exit successfully. // /* Postcondition: Filter out duplicate resources that are not multi-region keys. * I expect only have duplicates of specific multi-region keys. * In JSON something like * { * "mrk-edb7fe6942894d32ac46dbb1c922d574" : [ * "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", * "arn:aws:kms:us-east-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574" * ] * } */ .filter(maybeMrk -> isMRK(maybeMrk.getKey())) /* Flatten the duplicate identifiers into a single list. */ .flatMap(mrkEntry -> mrkEntry.getValue().stream()) .collect(Collectors.toList()); // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // # If any duplicate multi-region resource ids exist, this function MUST // # yield an error that includes all identifiers with duplicate resource // # ids not only the first duplicate found. if (duplicateMultiRegionKeyIdentifiers.size() > 1) { throw new IllegalArgumentException( "Duplicate multi-region keys are not allowed:\n" + String.join(", ", duplicateMultiRegionKeyIdentifiers)); } } /** * Helper method for * * @see AwsKmsMrkAwareMasterKeyProvider#assertMrksAreUnique(List) * <p>Refoactored into a pure function to simplify testing and ensure correctness. */ static String getResourceForResourceTypeKey(String identifier) { final AwsKmsCmkArnInfo info = parseInfoFromKeyArn(identifier); /* Check for early return (Postcondition): Non-ARNs may be raw resources. * Raw aliases ('alias/my-key') * or key ids ('mrk-edb7fe6942894d32ac46dbb1c922d574'). */ if (info == null) return identifier; /* Check for early return (Postcondition): Return the identifier for non-key resource types. * I only care about duplicate multi-region *keys*. * Any other resource type * should get filtered out. * I return the entire identifier * on the off chance that * a customer has created * an alias with a name `mrk-*`. * This way such an alias * can never accidentally * collided with an existing multi-region key * or a duplicate alias. */ if (!info.getResourceType().equals("key")) { return identifier; } /* Postcondition: Return the key id. * This will be used * to find different regional replicas of * the same multi-region key * because the key id for replicas is always the same. */ return info.getResource(); } /** Returns "aws-kms" */ @Override public String getDefaultProviderId() { return PROVIDER_NAME; } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # The input MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. /** * Added flexibility in matching multi-Region keys from different regions. * * @see KmsMasterKey#getMasterKey(String, String) */ @Override public AwsKmsMrkAwareMasterKey getMasterKey(final String providerId, final String requestedKeyArn) throws UnsupportedProviderException, NoSuchMasterKeyException { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # The function MUST only provide master keys if the input provider id // # equals "aws-kms". if (!canProvide(providerId)) { throw new UnsupportedProviderException(); } /* There SHOULD only be one match. * An unambiguous multi-region key for the family * of related multi-region keys is required. * See `assertMrksAreUnique`. * However, in the case of single region keys or aliases, * duplicates _are_ possible. */ Optional<String> matchedArn = keyIds_.stream().filter(t -> awsKmsArnMatchForDecrypt(t, requestedKeyArn)).findFirst(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In strict mode, the requested AWS KMS key ARN MUST // # match a member of the configured key ids by using AWS KMS MRK Match // # for Decrypt (aws-kms-mrk-match-for-decrypt.md#implementation) // # otherwise this function MUST error. if (!isDiscovery_ && !matchedArn.isPresent()) { throw new NoSuchMasterKeyException("Key must be in supplied list of keyIds."); } final AwsKmsCmkArnInfo requestedKeyArnInfo = parseInfoFromKeyArn(requestedKeyArn); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In discovery mode, the requested // # AWS KMS key identifier MUST be a well formed AWS KMS ARN. /* Precondition: Discovery mode requires requestedKeyArn be an ARN. * This function is called on the encrypt path. * It _may_ be the case that a raw key id, for example, was configured. */ if (isDiscovery_ && requestedKeyArnInfo == null) { throw new NoSuchMasterKeyException( "Cannot use AWS KMS identifiers " + "when in discovery mode."); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In // # discovery mode if a discovery filter is configured the requested AWS // # KMS key ARN's "partition" MUST match the discovery filter's // # "partition" and the AWS KMS key ARN's "account" MUST exist in the // # discovery filter's account id set. if (isDiscovery_ && discoveryFilter_ != null && !discoveryFilter_.allowsPartitionAndAccount( requestedKeyArnInfo.getPartition(), requestedKeyArnInfo.getAccountId())) { throw new NoSuchMasterKeyException( "Cannot use key in partition " + requestedKeyArnInfo.getPartition() + " with account id " + requestedKeyArnInfo.getAccountId() + " with configured discovery filter."); } final Region region_ = extractRegion( defaultRegion_, discoveryMrkRegion_, matchedArn, requestedKeyArnInfo, isDiscovery_); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # An AWS KMS client // # MUST be obtained by calling the regional client supplier with this // # AWS Region. KmsClient client = regionalClientSupplier_.getClient(region_); String keyIdentifier = isDiscovery_ // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In discovery mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with ? requestedKeyArnInfo.toString(region_.id()) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # In strict mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with : matchedArn.get(); final AwsKmsMrkAwareMasterKey result = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, this); result.setGrantTokens(grantTokens_); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # The output MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. return result; } /** * Select the correct region from multiple default configurations and potentially related * multi-Region keys from different regions. * * <p>Refactored into a pure function to facilitate testing and ensure correctness. */ static Region extractRegion( final Region defaultRegion, final Region discoveryMrkRegion, final Optional<String> matchedArn, final AwsKmsCmkArnInfo requestedKeyArnInfo, final boolean isDiscovery) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # If the requested AWS KMS key identifier is not a well formed ARN the // # AWS Region MUST be the configured default region this SHOULD be // # obtained from the AWS SDK. if (requestedKeyArnInfo == null) return defaultRegion; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # Otherwise if the requested AWS KMS key // # identifier is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key), then AWS Region MUST // # be the region from the AWS KMS key ARN stored in the provider info // # from the encrypted data key. if (!isMRK(requestedKeyArnInfo.getResource()) || !requestedKeyArnInfo.getResourceType().equals("key")) { return Region.of(requestedKeyArnInfo.getRegion()); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # Otherwise if the mode is discovery then // # the AWS Region MUST be the discovery MRK region. if (isDiscovery) return discoveryMrkRegion; // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // # Finally if the // # provider info is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) the AWS Region MUST // # be the region from the AWS KMS key in the configured key ids matched // # to the requested AWS KMS key by using AWS KMS MRK Match for Decrypt // # (aws-kms-mrk-match-for-decrypt.md#implementation). return Region.of(parseInfoFromKeyArn(matchedArn.get()).getRegion()); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # The input MUST be the same as the Master Key Provider Get Master Keys // # For Encryption (../master-key-provider-interface.md#get-master-keys- // # for-encryption) interface. /** * Returns all CMKs provided to the constructor of this object. * * @see KmsMasterKey#getMasterKeysForEncryption(MasterKeyRequest) */ @Override public List<AwsKmsMrkAwareMasterKey> getMasterKeysForEncryption(final MasterKeyRequest request) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # If the configured mode is discovery the function MUST return an empty // # list. if (isDiscovery_) { return emptyList(); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # If the configured mode is strict this function MUST return a // # list of master keys obtained by calling Get Master Key (aws-kms-mrk- // # aware-master-key-provider.md#get-master-key) for each AWS KMS key // # identifier in the configured key ids List<AwsKmsMrkAwareMasterKey> result = new ArrayList<>(keyIds_.size()); for (String id : keyIds_) { result.add(getMasterKey(id)); } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // # The output MUST be the same as the Master Key Provider Get Master // # Keys For Encryption (../master-key-provider-interface.md#get-master- // # keys-for-encryption) interface. return result; } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # The input MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. /** * @see KmsMasterKey#decryptDataKey(CryptoAlgorithm, Collection, Map) * @throws AwsCryptoException */ @Override public DataKey<AwsKmsMrkAwareMasterKey> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); return encryptedDataKeys.stream() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. .filter( edk -> { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms". if (!canProvide(edk.getProviderId())) return false; final String providerInfo = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); final AwsKmsCmkArnInfo providerArnInfo = parseInfoFromKeyArn(providerInfo); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # Additionally // # each provider info MUST be a valid AWS KMS ARN (aws-kms-key-arn.md#a- // # valid-aws-kms-arn) with a resource type of "key". if (providerArnInfo == null || !"key".equals(providerArnInfo.getResourceType())) { throw new IllegalStateException("Invalid provider info in message."); } return true; }) .map( edk -> { try { final String keyArn = new String(edk.getProviderInformation(), StandardCharsets.UTF_8); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # For each encrypted data key in the filtered set, one at a time, the // # master key provider MUST call Get Master Key (aws-kms-mrk-aware- // # master-key-provider.md#get-master-key) with the encrypted data key's // # provider info as the AWS KMS key ARN. // This will throw if we can't use this key for whatever reason return getMasterKey(edk.getProviderId(), keyArn) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # It MUST call Decrypt Data Key // # (aws-kms-mrk-aware-master-key.md#decrypt-data-key) on this master key // # with the input algorithm, this single encrypted data key, and the // # input encryption context. .decryptDataKey(algorithm, singletonList(edk), encryptionContext); } catch (final Exception ex) { // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # If this attempt results in an error, then // # these errors MUST be collected. exceptions.add(ex); return null; } }) /* Need to filter null because an Optional of a null is crazy. * `findFirst` will throw if it sees `null`. */ .filter(Objects::nonNull) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # If the decrypt data key call is // # successful, then this function MUST return this result and not // # attempt to decrypt any more encrypted data keys. .findFirst() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // # The output MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. .orElseThrow(() -> buildCannotDecryptDksException(exceptions)); } public List<String> getGrantTokens() { return new ArrayList<>(grantTokens_); } /** * Returns a new {@link AwsKmsMrkAwareMasterKeyProvider} that is configured identically to this * one, except with the given list of grant tokens. The grant token list in the returned provider * is immutable (but can be further overridden by invoking withGrantTokens again). */ public AwsKmsMrkAwareMasterKeyProvider withGrantTokens(List<String> grantTokens) { grantTokens = Collections.unmodifiableList(new ArrayList<>(grantTokens)); return new AwsKmsMrkAwareMasterKeyProvider( regionalClientSupplier_, defaultRegion_, keyIds_, grantTokens, isDiscovery_, discoveryFilter_, discoveryMrkRegion_); } /** * Returns a new {@link AwsKmsMrkAwareMasterKeyProvider} that is configured identically to this * one, except with the given list of grant tokens. The grant token list in the returned provider * is immutable (but can be further overridden by invoking withGrantTokens again). */ public AwsKmsMrkAwareMasterKeyProvider withGrantTokens(String... grantTokens) { return withGrantTokens(asList(grantTokens)); } }
5,465
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/kmssdkv2/package-info.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ /** * Contains logic necessary to create {@link com.amazonaws.encryptionsdk.MasterKey}s backed by AWS * KMS keys. */ package com.amazonaws.encryptionsdk.kmssdkv2;
5,466
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/multi/MultipleProviderFactory.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.multi; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.MasterKeyRequest; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.Utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; /** * Constructs {@link MasterKeyProvider}s which are backed by any number of other {@link * MasterKeyProvider}s. The returned provider will have the following properties: * * <ul> * <li>{@link MasterKeyProvider#getMasterKeysForEncryption(MasterKeyRequest)} will result in the * union of all responses from the backing providers. Likewise, * <li>{@link MasterKeyProvider#decryptDataKey(CryptoAlgorithm, Collection, Map)} will succeed if * and only if at least one backing provider can successfully decrypt the {@link DataKey}s. * <li>{@link MasterKeyProvider#getDefaultProviderId()} is delegated to the first backing * provider. * <li>{@link MasterKeyProvider#getMasterKey(String, String)} will attempt to find the appropriate * backing provider to return a {@link MasterKey}. * </ul> * * All methods in this factory return identical results and exist only for different degrees of * type-safety. */ public class MultipleProviderFactory { private MultipleProviderFactory() { // Prevent instantiation } public static <K extends MasterKey<K>> MasterKeyProvider<K> buildMultiProvider( final Class<K> masterKeyClass, final List<? extends MasterKeyProvider<? extends K>> providers) { return new MultiProvider<K>(providers); } @SafeVarargs public static <K extends MasterKey<K>, P extends MasterKeyProvider<? extends K>> MasterKeyProvider<K> buildMultiProvider(final Class<K> masterKeyClass, final P... providers) { return buildMultiProvider(masterKeyClass, Arrays.asList(providers)); } @SuppressWarnings({"rawtypes", "unchecked"}) public static MasterKeyProvider<?> buildMultiProvider( final List<? extends MasterKeyProvider<?>> providers) { return new MultiProvider(providers); } @SafeVarargs public static <P extends MasterKeyProvider<?>> MasterKeyProvider<?> buildMultiProvider( final P... providers) { return buildMultiProvider(Arrays.asList(providers)); } private static class MultiProvider<K extends MasterKey<K>> extends MasterKeyProvider<K> { private final List<? extends MasterKeyProvider<? extends K>> providers_; private MultiProvider(final List<? extends MasterKeyProvider<? extends K>> providers) { Utils.assertNonNull(providers, "providers"); if (providers.isEmpty()) { throw new IllegalArgumentException("providers must not be empty"); } providers_ = new ArrayList<>(providers); } @Override public String getDefaultProviderId() { return providers_.get(0).getDefaultProviderId(); } @Override public K getMasterKey(final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { for (final MasterKeyProvider<? extends K> prov : providers_) { try { final K result = prov.getMasterKey(keyId); if (result != null) { return result; } } catch (final NoSuchMasterKeyException ex) { // swallow and continue } } throw new NoSuchMasterKeyException(); } @Override public K getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { boolean foundProvider = false; for (final MasterKeyProvider<? extends K> prov : providers_) { if (prov.canProvide(provider)) { foundProvider = true; try { final K result = prov.getMasterKey(provider, keyId); if (result != null) { return result; } } catch (final NoSuchMasterKeyException ex) { // swallow and continue } } } if (foundProvider) { throw new NoSuchMasterKeyException(); } else { throw new UnsupportedProviderException(provider); } } @Override public List<K> getMasterKeysForEncryption(final MasterKeyRequest request) { final List<K> result = new ArrayList<>(); for (final MasterKeyProvider<? extends K> prov : providers_) { result.addAll(prov.getMasterKeysForEncryption(request)); } return result; } @SuppressWarnings("unchecked") @Override public DataKey<K> decryptDataKey( final CryptoAlgorithm algorithm, final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException { final List<Exception> exceptions = new ArrayList<>(); for (final MasterKeyProvider<? extends K> prov : providers_) { try { final DataKey<? extends K> result = prov.decryptDataKey(algorithm, encryptedDataKeys, encryptionContext); if (result != null) { return (DataKey<K>) result; } } catch (final Exception ex) { exceptions.add(ex); } } throw buildCannotDecryptDksException(exceptions); } } }
5,467
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/multi/package-info.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ /** * Contains logic necessary to create {@link com.amazonaws.encryptionsdk.MasterKeyProvider}s which * are backed by multiple {@code MasterKeyProviders}. */ package com.amazonaws.encryptionsdk.multi;
5,468
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/AwsKmsCmkArnInfo.java
package com.amazonaws.encryptionsdk.internal; import java.util.Arrays; /** * A class to parse and handle AWS KMS identifiers. Mostly AWS KMS ARNs but raw resources are also * used in the AWS Encryption SDK. */ public final class AwsKmsCmkArnInfo { private static final String arnLiteral = "arn"; private static final String kmsServiceName = "kms"; /** * Takes an AWS KMS identifier that may or may not be an ARN and attempts to parse the identifier * as an ARN. If the identifier is not an ARN, it returns null. This is an expected condition, not * an error. * * @param keyArn The string to parse */ public static AwsKmsCmkArnInfo parseInfoFromKeyArn(final String keyArn) { /* Precondition: keyArn must be a string. */ if (keyArn == null || keyArn.isEmpty()) return null; final String[] parts = AwsKmsArnParts.splitArn(keyArn); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # MUST start with string "arn" if (!arnLiteral.equals(parts[AwsKmsArnParts.ArnLiteral.index()])) { return null; } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The service MUST be the string "kms" if (!kmsServiceName.equals(parts[AwsKmsArnParts.Service.index()])) { return null; } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The partition MUST be a non-empty // // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The region MUST be a non-empty string // // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The account MUST be a non-empty string // final boolean emptyParts = Arrays.stream(parts).anyMatch(String::isEmpty); if (emptyParts || AwsKmsArnParts.values().length != parts.length) return null; // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The resource section MUST be non-empty and MUST be split by a // # single "/" any additional "/" are included in the resource id String[] resourceParts = AwsKmsArnParts.Resource.splitResourceParts(parts[AwsKmsArnParts.ResourceParts.index()]); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The resource id MUST be a non-empty string if (Arrays.stream(resourceParts).anyMatch(String::isEmpty) || AwsKmsArnParts.Resource.values().length > resourceParts.length) { return null; } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // # The resource type MUST be either "alias" or "key" if (!("key".equals(resourceParts[AwsKmsArnParts.Resource.ResourceType.index()]) || "alias".equals(resourceParts[AwsKmsArnParts.Resource.ResourceType.index()]))) { return null; } return new AwsKmsCmkArnInfo( parts[AwsKmsArnParts.Partition.index()], parts[AwsKmsArnParts.Region.index()], parts[AwsKmsArnParts.Account.index()], resourceParts[AwsKmsArnParts.Resource.ResourceType.index()], resourceParts[AwsKmsArnParts.Resource.Resource.index()]); } /** * Takes a string an will throw if this identifier is invalid Raw resources like a key ID or alias * `mrk-edb7fe6942894d32ac46dbb1c922d574`, `alias/my-alias` or ARNs like * arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574 * arn:aws:kms:us-west-2:111122223333:alias/my-alias * * @param identifier an identifier that is an ARN or raw resource */ public static void validAwsKmsIdentifier(final String identifier) { /* Exceptional Postcondition: Null or empty string is not a valid identifier. */ if (identifier == null || identifier.isEmpty()) { throw new IllegalArgumentException("Null or empty string is not a valid Aws KMS identifier."); } /* Exceptional Postcondition: Things that start with `arn:` MUST be ARNs. */ if (identifier.startsWith("arn:") && parseInfoFromKeyArn(identifier) == null) { throw new IllegalArgumentException("Invalid ARN used as an identifier."); } ; /* Postcondition: Raw alias starts with `alias/`. */ if (identifier.startsWith("alias/")) return; /* Postcondition: There are no requirements on key ids. * Even thought they look like UUID, this is not required. * Take multi region keys: mrk-edb7fe6942894d32ac46dbb1c922d574 */ return; } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // # This function MUST take a single AWS KMS identifier /** * Identifies Multi Region AWS KMS keys. This can misidentify an alias that starts with "mrk-". */ public static boolean isMRK(final String resource) { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // # If the input starts with "arn:", this MUST return the output of // # identifying an an AWS KMS multi-Region ARN (aws-kms-key- // # arn.md#identifying-an-an-aws-kms-multi-region-arn) called with this // # input. if (resource.startsWith("arn:")) return isMRK(parseInfoFromKeyArn(resource)); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // # If the input starts with "alias/", this an AWS KMS alias and // # not a multi-Region key id and MUST return false. if (resource.startsWith("alias/")) return false; // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // # If the input starts // # with "mrk-", this is a multi-Region key id and MUST return true. // // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // # If // # the input does not start with any of the above, this is not a multi- // # Region key id and MUST return false. return resource.startsWith("mrk-"); } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // # This function MUST take a single AWS KMS ARN /** * Identifies Multi Region AWS KMS keys. The resource type check is to protect against the edge * case where an alias starts with `mrk-` * e.g. * arn:aws:kms:us-west-2:111122223333:alias/mrk-someOtherName */ public static boolean isMRK(final AwsKmsCmkArnInfo arn) { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // # If the input is an invalid AWS KMS ARN this function MUST error. if (arn == null) throw new Error("Invalid Arn"); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // # If resource type is "alias", this is an AWS KMS alias ARN and MUST // # return false. // // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // # If resource type is "key" and resource ID starts with // # "mrk-", this is a AWS KMS multi-Region key ARN and MUST return true. // // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // # If resource type is "key" and resource ID does not start with "mrk-", // # this is a (single-region) AWS KMS key ARN and MUST return false. return isMRK(arn.getResource()) && arn.getResourceType().equals("key"); } // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // # The caller MUST provide: /** * Tell if two different AWS KMS ARNs match. For identical keys this is trivial, but multi-Region * keys can match across regions. */ public static boolean awsKmsArnMatchForDecrypt( final String configuredKeyIdentifier, final String providerInfoKeyIdentifier) { // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // # If both identifiers are identical, this function MUST return "true". if (configuredKeyIdentifier.equals(providerInfoKeyIdentifier)) return true; final AwsKmsCmkArnInfo configuredArnInfo = parseInfoFromKeyArn(configuredKeyIdentifier); final AwsKmsCmkArnInfo providerInfoKeyArnInfo = parseInfoFromKeyArn(providerInfoKeyIdentifier); /* Check for early return (Postcondition): Both identifiers are not ARNs and not equal, therefore they can not match. */ if (providerInfoKeyArnInfo == null || configuredArnInfo == null) return false; // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // # Otherwise if either input is not identified as a multi-Region key // # (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then // # this function MUST return "false". if (!isMRK(configuredArnInfo) || !isMRK(providerInfoKeyArnInfo)) return false; // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // # Otherwise if both inputs are // # identified as a multi-Region keys (aws-kms-key-arn.md#identifying-an- // # aws-kms-multi-region-key), this function MUST return the result of // # comparing the "partition", "service", "accountId", "resourceType", // # and "resource" parts of both ARN inputs. // Service is not matched because AwsKmsCmkArnInfo only allows a service of `kms`. return configuredArnInfo.getPartition().equals(providerInfoKeyArnInfo.getPartition()) && configuredArnInfo.getAccountId().equals(providerInfoKeyArnInfo.getAccountId()) && configuredArnInfo.getResourceType().equals(providerInfoKeyArnInfo.getResourceType()) && configuredArnInfo.getResource().equals(providerInfoKeyArnInfo.getResource()); } private final String partition_; private final String accountId_; private final String region_; private final String resource_; private final String resourceType_; /** Data structure to hold the parts of an AWS KMS ARN */ AwsKmsCmkArnInfo( String partition, String region, String accountId, String resourceType, String resource) { partition_ = partition; region_ = region; accountId_ = accountId; resourceType_ = resourceType; resource_ = resource; } public String getPartition() { return partition_; } public String getAccountId() { return accountId_; } public String getRegion() { return region_; } public String getResourceType() { return resourceType_; } public String getResource() { return resource_; } /** Returns the well-formed ARN this object describes. */ @Override public String toString() { return toString(region_); } /** * AWS KMS multi-Region keys can have replicas in other region. A compatible ARN in a different * Region may be required. * * @param mrkRegion The region to use instead of the region in the ARN */ public String toString(String mrkRegion) { return String.join( AwsKmsArnParts.Delimiter, arnLiteral, partition_, kmsServiceName, mrkRegion, accountId_, String.join(AwsKmsArnParts.Resource.ResourceDelimiter, resourceType_, resource_)); } /** * Structure information about an ARN. This structure is only expecting to process AWS KMS ARNs * see https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more * details. */ enum AwsKmsArnParts { ArnLiteral(0), Partition(1), Service(2), Region(3), Account(4), ResourceParts(5); int index_; AwsKmsArnParts(int i) { index_ = i; } int index() { return index_; } public static String[] splitArn(String arn) { return arn.split(AwsKmsArnParts.Delimiter, AwsKmsArnParts.values().length); } static String Delimiter = ":"; /** * Structure information about the resource part of an ARN This structure is only expecting to * process AWS KMS ARNs see * https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details. * * <p>Of note, is that the ARN specification lets the `/` also be a `:` however AWS KMS does not * support this. AWS KMS _only_ uses `/` to delimit the resource type and resource. */ enum Resource { ResourceType(0), Resource(1); static String ResourceDelimiter = "/"; int index_; Resource(int i) { index_ = i; } int index() { return index_; } public static String[] splitResourceParts(String resource) { return resource.split(ResourceDelimiter, 2); } } } }
5,469
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/RsaJceKeyCipher.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import java.security.GeneralSecurityException; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.MGF1ParameterSpec; import java.util.Map; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Cipher; import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; import org.apache.commons.lang3.ArrayUtils; /** A JceKeyCipher based on RSA. */ class RsaJceKeyCipher extends JceKeyCipher { private static final Logger LOGGER = Logger.getLogger(RsaJceKeyCipher.class.getName()); // MGF1 with SHA-224 isn't really supported, but we include it in the regex because we need it // for proper handling of the algorithm. private static final Pattern SUPPORTED_TRANSFORMATIONS = Pattern.compile( "RSA/ECB/(?:PKCS1Padding|OAEPWith(SHA-(?:1|224|256|384|512))AndMGF1Padding)", Pattern.CASE_INSENSITIVE); private final AlgorithmParameterSpec parameterSpec_; private final String transformation_; RsaJceKeyCipher(PublicKey wrappingKey, PrivateKey unwrappingKey, String transformation) { super(wrappingKey, unwrappingKey); final Matcher matcher = SUPPORTED_TRANSFORMATIONS.matcher(transformation); if (matcher.matches()) { final String hashUnknownCase = matcher.group(1); if (hashUnknownCase != null) { // OAEP mode a.k.a PKCS #1v2 final String hash = hashUnknownCase.toUpperCase(); transformation_ = "RSA/ECB/OAEPPadding"; final MGF1ParameterSpec mgf1Spec; switch (hash) { case "SHA-1": mgf1Spec = MGF1ParameterSpec.SHA1; break; case "SHA-224": LOGGER.warning(transformation + " is not officially supported by the JceMasterKey"); mgf1Spec = MGF1ParameterSpec.SHA224; break; case "SHA-256": mgf1Spec = MGF1ParameterSpec.SHA256; break; case "SHA-384": mgf1Spec = MGF1ParameterSpec.SHA384; break; case "SHA-512": mgf1Spec = MGF1ParameterSpec.SHA512; break; default: throw new IllegalArgumentException("Unsupported algorithm: " + transformation); } parameterSpec_ = new OAEPParameterSpec(hash, "MGF1", mgf1Spec, PSource.PSpecified.DEFAULT); } else { // PKCS #1 v1.x transformation_ = transformation; parameterSpec_ = null; } } else { LOGGER.warning(transformation + " is not officially supported by the JceMasterKey"); // Unsupported transformation, just use exactly what we are given transformation_ = transformation; parameterSpec_ = null; } } @Override WrappingData buildWrappingCipher(Key key, Map<String, String> encryptionContext) throws GeneralSecurityException { final Cipher cipher = Cipher.getInstance(transformation_); cipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec_); return new WrappingData(cipher, ArrayUtils.EMPTY_BYTE_ARRAY); } @Override Cipher buildUnwrappingCipher( Key key, byte[] extraInfo, int offset, Map<String, String> encryptionContext) throws GeneralSecurityException { if (extraInfo.length != offset) { throw new IllegalArgumentException("Extra info must be empty for RSA keys"); } final Cipher cipher = Cipher.getInstance(transformation_); cipher.init(Cipher.DECRYPT_MODE, key, parameterSpec_); return cipher; } }
5,470
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/EncryptionContextSerializer.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; /** * This class provides methods that serialize and deserialize the encryption context provided as a * map containing key-value pairs comprised of strings. */ public class EncryptionContextSerializer { private EncryptionContextSerializer() { // Prevent instantiation } /** * Serialize the encryption context provided as a map containing key-value pairs comprised of * strings into a byte array. * * @param encryptionContext the map containing the encryption context to serialize. * @return serialized bytes of the encryption context. */ public static byte[] serialize(Map<String, String> encryptionContext) { if (encryptionContext == null) return null; if (encryptionContext.size() == 0) { return new byte[0]; } // Make sure we don't accidentally overwrite anything. encryptionContext = Collections.unmodifiableMap(encryptionContext); if (encryptionContext.size() > Short.MAX_VALUE) { throw new AwsCryptoException( "The number of entries in encryption context exceeds the allowed maximum " + Short.MAX_VALUE); } final ByteBuffer result = ByteBuffer.allocate(Short.MAX_VALUE); result.order(ByteOrder.BIG_ENDIAN); // write the number of key-value entries first result.putShort((short) encryptionContext.size()); try { final CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder(); // ensure all failures in encoder are reported. encoder.onMalformedInput(CodingErrorAction.REPORT); encoder.onUnmappableCharacter(CodingErrorAction.REPORT); final SortedMap<ByteBuffer, ByteBuffer> binaryEntries = new TreeMap<>(new Utils.ComparingByteBuffers()); for (Entry<String, String> mapEntry : encryptionContext.entrySet()) { if (mapEntry.getKey() == null || mapEntry.getValue() == null) { throw new AwsCryptoException( "All keys and values in encryption context must be non-null."); } if (mapEntry.getKey().isEmpty() || mapEntry.getValue().isEmpty()) { throw new AwsCryptoException( "All keys and values in encryption context must be non-empty."); } final ByteBuffer keyBytes = encoder.encode(CharBuffer.wrap(mapEntry.getKey())); final ByteBuffer valueBytes = encoder.encode(CharBuffer.wrap(mapEntry.getValue())); // check for duplicate entries. if (binaryEntries.put(keyBytes, valueBytes) != null) { throw new AwsCryptoException("Encryption context contains duplicate entries."); } if (keyBytes.limit() > Short.MAX_VALUE || valueBytes.limit() > Short.MAX_VALUE) { throw new AwsCryptoException( "All keys and values in encryption context must be shorter than " + Short.MAX_VALUE); } } for (final Entry<ByteBuffer, ByteBuffer> entry : binaryEntries.entrySet()) { // actual serialization happens here result.putShort((short) entry.getKey().limit()); result.put(entry.getKey()); result.putShort((short) entry.getValue().limit()); result.put(entry.getValue()); } // get and return the bytes that have been serialized Utils.flip(result); final byte[] encryptionContextBytes = new byte[result.limit()]; result.get(encryptionContextBytes); return encryptionContextBytes; } catch (CharacterCodingException e) { throw new IllegalArgumentException( "Encryption context contains an invalid unicode character"); } catch (BufferOverflowException e) { throw new AwsCryptoException( "The number of bytes in encryption context exceeds the allowed maximum " + Short.MAX_VALUE, e); } } /** * Deserialize the provided byte array into a map containing key-value pairs comprised of strings. * * @param b the bytes to deserialize into a map representing the encryption context. * @return the map containing key-value pairs comprised of strings. */ public static Map<String, String> deserialize(final byte[] b) { try { if (b == null) { return null; } if (b.length == 0) { return (Collections.<String, String>emptyMap()); } final ByteBuffer encryptionContextBytes = ByteBuffer.wrap(b); // retrieve the number of entries first final int entryCount = encryptionContextBytes.getShort(); if (entryCount <= 0 || entryCount > Short.MAX_VALUE) { throw new AwsCryptoException( "The number of entries in encryption context must be greater than 0 and smaller than " + Short.MAX_VALUE); } final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder(); // ensure all failures in decoder are reported. decoder.onMalformedInput(CodingErrorAction.REPORT); decoder.onUnmappableCharacter(CodingErrorAction.REPORT); final Map<String, String> result = new HashMap<>(entryCount); for (int i = 0; i < entryCount; i++) { // retrieve key final int keyLen = encryptionContextBytes.getShort(); if (keyLen <= 0 || keyLen > Short.MAX_VALUE) { throw new AwsCryptoException( "Key length must be greater than 0 and smaller than " + Short.MAX_VALUE); } final ByteBuffer keyBytes = encryptionContextBytes.slice(); Utils.limit(keyBytes, keyLen); Utils.position(encryptionContextBytes, encryptionContextBytes.position() + keyLen); final int valueLen = encryptionContextBytes.getShort(); if (valueLen <= 0 || valueLen > Short.MAX_VALUE) { throw new AwsCryptoException( "Value length must be greater than 0 and smaller than " + Short.MAX_VALUE); } // retrieve value final ByteBuffer valueBytes = encryptionContextBytes.slice(); Utils.limit(valueBytes, valueLen); Utils.position(encryptionContextBytes, encryptionContextBytes.position() + valueLen); final CharBuffer keyChars = decoder.decode(keyBytes); final CharBuffer valueChars = decoder.decode(valueBytes); // check for duplicate entries. if (result.put(keyChars.toString(), valueChars.toString()) != null) { throw new AwsCryptoException("Encryption context contains duplicate entries."); } } return result; } catch (CharacterCodingException e) { throw new IllegalArgumentException( "Encryption context contains an invalid unicode character"); } catch (BufferUnderflowException e) { throw new AwsCryptoException("Invalid encryption context. Expected more bytes.", e); } } }
5,471
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/BlockEncryptionHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.model.CipherBlockHeaders; import java.io.ByteArrayOutputStream; import javax.crypto.Cipher; import javax.crypto.SecretKey; /** * The block encryption handler is an implementation of {@link MessageCryptoHandler} that provides * methods to encrypt content and store it in a single block. * * <p>In this SDK, content encrypted by this class is decrypted by the {@link * BlockDecryptionHandler}. */ class BlockEncryptionHandler implements CryptoHandler { private final SecretKey encryptionKey_; private final CryptoAlgorithm cryptoAlgo_; private final int nonceLen_; private final byte[] messageId_; private final int tagLenBytes_; private final ByteArrayOutputStream bytesToEncryptStream_ = new ByteArrayOutputStream(1024); private boolean complete_ = false; /** * Construct an encryption handler for encrypting bytes and storing them in a single block. * * @param encryptionKey the key to use for encrypting the plaintext * @param nonceLen the length of the nonce to use when encrypting the plaintext * @param cryptoAlgo the crypto algorithm to use for encrypting the plaintext * @param messageId the byte array containing the message identifier that is used in binding the * encrypted content to the headers in the ciphertext. */ public BlockEncryptionHandler( final SecretKey encryptionKey, final int nonceLen, final CryptoAlgorithm cryptoAlgo, final byte[] messageId) { encryptionKey_ = encryptionKey; cryptoAlgo_ = cryptoAlgo; nonceLen_ = nonceLen; messageId_ = messageId.clone(); tagLenBytes_ = cryptoAlgo_.getTagLen(); } /** * Encrypt the block of bytes provide in {@code in} and copy the resulting ciphertext bytes into * {@code out}. * * @param in the input byte array containing plaintext bytes. * @param off the offset into {@code in} where the data to be encrypted starts. * @param len the number of bytes to be encrypted. * @param out the output buffer the encrypted bytes are copied into. * @param outOff the offset into the output byte array the encrypted data starts at. * @return the number of bytes written to {@code out} and the number of bytes processed */ @Override public ProcessingSummary processBytes( final byte[] in, final int off, final int len, final byte[] out, final int outOff) { bytesToEncryptStream_.write(in, off, len); return new ProcessingSummary(0, len); } /** * Finish encryption of the plaintext bytes. * * @param out space for any resulting output data. * @param outOff offset into {@code out} to start copying the data at. * @return number of bytes written into {@code out}. * @throws BadCiphertextException thrown by the underlying cipher handler. */ @Override public int doFinal(final byte[] out, final int outOff) throws BadCiphertextException { complete_ = true; return writeEncryptedBlock( bytesToEncryptStream_.toByteArray(), 0, bytesToEncryptStream_.size(), out, outOff); } /** * Return the size of the output buffer required for a processBytes plus a doFinal with an input * size of {@code inLen} bytes. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and doFinal with {@code inLen} * bytes of input. */ @Override public int estimateOutputSize(final int inLen) { int outSize = 0; outSize += nonceLen_ + tagLenBytes_; // include long for storing size of content outSize += Long.SIZE / Byte.SIZE; // include any buffered bytes outSize += bytesToEncryptStream_.size(); if (inLen > 0) { outSize += inLen; } return outSize; } @Override public int estimatePartialOutputSize(int inLen) { return 0; } @Override public int estimateFinalOutputSize() { return estimateOutputSize(0); } /** * This method encrypts the provided bytes, creates the headers for the block, and assembles the * block containing the headers and the encrypted bytes. * * @param in the input byte array. * @param inOff the offset into {@code in} array where the data to be encrypted starts. * @param inLen the number of bytes to be encrypted. * @param out the output buffer the encrypted bytes is copied into. * @param outOff the offset into the output byte array the encrypted data starts at. * @return the number of bytes written to {@code out}. * @throws BadCiphertextException thrown by the underlying cipher handler. */ private int writeEncryptedBlock( final byte[] input, final int off, final int len, final byte[] out, final int outOff) throws BadCiphertextException { if (out.length == 0) { return 0; } int outLen = 0; final int seqNum = 1; // always 1 for single block case final byte[] contentAad = Utils.generateContentAad(messageId_, Constants.SINGLE_BLOCK_STRING_ID, seqNum, len); final byte[] nonce = getNonce(); final byte[] encryptedBytes = new CipherHandler(encryptionKey_, Cipher.ENCRYPT_MODE, cryptoAlgo_) .cipherData(nonce, contentAad, input, off, len); // create the cipherblock headers now for the encrypted data final int encryptedContentLen = encryptedBytes.length - tagLenBytes_; final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce, encryptedContentLen); final byte[] cipherBlockHeaderBytes = cipherBlockHeaders.toByteArray(); // assemble the headers and the encrypted bytes into a single block System.arraycopy( cipherBlockHeaderBytes, 0, out, outOff + outLen, cipherBlockHeaderBytes.length); outLen += cipherBlockHeaderBytes.length; System.arraycopy(encryptedBytes, 0, out, outOff + outLen, encryptedBytes.length); outLen += encryptedBytes.length; return outLen; } private byte[] getNonce() { final byte[] nonce = new byte[nonceLen_]; // The IV for the non-framed encryption case is generated as if we were encrypting a message // with a single // frame. nonce[nonce.length - 1] = 1; return nonce; } @Override public boolean isComplete() { return complete_; } }
5,472
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/ProcessingSummary.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; public class ProcessingSummary { public static final ProcessingSummary ZERO = new ProcessingSummary(0, 0); private final int bytesWritten; private final int bytesProcessed; public ProcessingSummary(final int bytesWritten, final int bytesProcessed) { this.bytesWritten = bytesWritten; this.bytesProcessed = bytesProcessed; } public int getBytesProcessed() { return bytesProcessed; } public int getBytesWritten() { return bytesWritten; } }
5,473
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/BlockDecryptionHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.model.CipherBlockHeaders; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; /** * The block decryption handler is an implementation of CryptoHandler that provides methods to * decrypt content encrypted and stored in a single block. * * <p>In this SDK, this class decrypts content that is encrypted by {@link BlockEncryptionHandler}. */ class BlockDecryptionHandler implements CryptoHandler { private final SecretKey decryptionKey_; private final short nonceLen_; private final CryptoAlgorithm cryptoAlgo_; private final byte[] messageId_; private final CipherBlockHeaders blockHeaders_; private final byte[] bytesToDecrypt_ = new byte[0]; private byte[] unparsedBytes_ = new byte[0]; private boolean complete_ = false; /** * Construct a decryption handler for decrypting bytes stored in a single block. * * @param decryptionKey the key to use for decrypting the ciphertext * @param nonceLen the length to use when parsing the nonce in the block headers. * @param cryptoAlgo the crypto algorithm to use for decrypting the ciphertext * @param messageId the byte array containing the message identifier that is used in binding the * encrypted content to the headers in the ciphertext. */ public BlockDecryptionHandler( final SecretKey decryptionKey, final short nonceLen, final CryptoAlgorithm cryptoAlgo, final byte[] messageId) { decryptionKey_ = decryptionKey; nonceLen_ = nonceLen; cryptoAlgo_ = cryptoAlgo; messageId_ = messageId; blockHeaders_ = new CipherBlockHeaders(); } /** * Decrypt the ciphertext bytes provided in {@code in} containing the encrypted bytes of the * plaintext stored in a single block. The decrypted bytes are copied into {@code out} starting at * {@code outOff}. * * <p>This method performs two operations: parses the headers of the single block structure in the * ciphertext and processes the encrypted content following the headers and decrypts it. * * @param in the input byte array. * @param off the offset into the in array where the data to be decrypted starts. * @param len the number of bytes to be decrypted. * @param out the output buffer the decrypted plaintext bytes go into. * @param outOff the offset into the output byte array the decrypted data starts at. * @return the number of bytes written to out. * @throws AwsCryptoException if the content type found in the headers is not of single-block * type. */ @Override public synchronized ProcessingSummary processBytes( final byte[] in, final int off, final int len, final byte[] out, final int outOff) throws AwsCryptoException { if (complete_) { throw new AwsCryptoException("Ciphertext has already been processed."); } final byte[] bytesToParse = new byte[unparsedBytes_.length + len]; // If there were previously unparsed bytes, add them as the first // set of bytes to be parsed in this call. System.arraycopy(unparsedBytes_, 0, bytesToParse, 0, unparsedBytes_.length); System.arraycopy(in, off, bytesToParse, unparsedBytes_.length, len); long parsedBytes = 0; // Parse available bytes. Stop parsing when there aren't enough // bytes to complete parsing of the : // - the blockcipher headers // - encrypted content while (!complete_ && parsedBytes < bytesToParse.length) { blockHeaders_.setNonceLength(nonceLen_); parsedBytes += blockHeaders_.deserialize(bytesToParse, (int) parsedBytes); if (parsedBytes > Integer.MAX_VALUE) { throw new AwsCryptoException( "Integer overflow of the total bytes to parse and decrypt occured."); } // if we have all header fields, process the encrypted content. if (blockHeaders_.isComplete() == true) { if (blockHeaders_.getContentLength() > Integer.MAX_VALUE) { throw new AwsCryptoException("Content length exceeds the maximum allowed value."); } int protectedContentLen = (int) blockHeaders_.getContentLength(); // include the tag which is added by the underlying cipher. protectedContentLen += cryptoAlgo_.getTagLen(); if ((bytesToParse.length - parsedBytes) < protectedContentLen) { // if we don't have all of the encrypted bytes, break // until they become available. break; } byte[] plaintext = decryptContent(bytesToParse, (int) parsedBytes, protectedContentLen); System.arraycopy(plaintext, 0, out, outOff, plaintext.length); complete_ = true; return new ProcessingSummary( plaintext.length, (int) (parsedBytes + protectedContentLen) - unparsedBytes_.length); } else { // if there aren't enough bytes to parse the block headers, // we can't continue parsing. break; } } // buffer remaining bytes for parsing in the next round. unparsedBytes_ = Arrays.copyOfRange(bytesToParse, (int) parsedBytes, bytesToParse.length); return new ProcessingSummary(0, len); } /** * Finish processing of the bytes by decrypting the ciphertext. * * @param out space for any resulting output data. * @param outOff offset into {@code out} to start copying the data at. * @return number of bytes written into {@code out}. * @throws BadCiphertextException if the bytes do not decrypt correctly. */ @Override public synchronized int doFinal(final byte[] out, final int outOff) throws BadCiphertextException { if (!complete_) { throw new BadCiphertextException("Unable to process entire ciphertext."); } return 0; } /** * Return the size of the output buffer required for a processBytes plus a doFinal with an input * of inLen bytes. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and doFinal with len bytes of * input. */ @Override public synchronized int estimateOutputSize(final int inLen) { // include any buffered bytes int outSize = bytesToDecrypt_.length + unparsedBytes_.length; if (inLen > 0) { outSize += inLen; } return outSize; } @Override public int estimatePartialOutputSize(int inLen) { return estimateOutputSize(inLen); } @Override public int estimateFinalOutputSize() { return estimateOutputSize(0); } /** * Returns the plaintext bytes of the encrypted content. * * @param input the input bytes containing the content * @param off the offset into the input array where the data to be decrypted starts. * @param len the number of bytes to be decrypted. * @return the plaintext bytes of the encrypted content. * @throws BadCiphertextException if the MAC tag verification fails or an invalid header value is * found. */ private byte[] decryptContent(final byte[] input, final int off, final int len) throws BadCiphertextException { if (blockHeaders_.isComplete() == false) { return new byte[0]; } final byte[] nonce = blockHeaders_.getNonce(); final int seqNum = 1; // always 1 for single block case. final byte[] contentAad = Utils.generateContentAad( messageId_, Constants.SINGLE_BLOCK_STRING_ID, seqNum, blockHeaders_.getContentLength()); final CipherHandler cipherHandler = new CipherHandler(decryptionKey_, Cipher.DECRYPT_MODE, cryptoAlgo_); return cipherHandler.cipherData(nonce, contentAad, input, off, len); } @Override public boolean isComplete() { return complete_; } }
5,474
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/PrimitivesParser.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.exception.ParseException; import java.io.DataOutput; import java.io.IOException; /** * This class implements methods for parsing the primitives ( {@code byte, short, int, long}) in * Java from a byte array. */ // @ non_null_by_default public class PrimitivesParser { /** * Construct a long value using 8 bytes starting at the specified offset. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the parsed long value. */ // @ private normal_behavior // @ requires 0 <= off && off <= b.length - Long.BYTES; // @ ensures \result == // Long.asLong(b[off],b[off+1],b[off+2],b[off+3],b[off+4],b[off+5],b[off+6],b[off+7]); // @ pure spec_public private static long getLong(final byte[] b, final int off) { return ((b[off + 7] & 0xFFL)) + ((b[off + 6] & 0xFFL) << 8) + ((b[off + 5] & 0xFFL) << 16) + ((b[off + 4] & 0xFFL) << 24) + ((b[off + 3] & 0xFFL) << 32) + ((b[off + 2] & 0xFFL) << 40) + ((b[off + 1] & 0xFFL) << 48) + (((long) b[off]) << 56); } /** * Construct an integer value using 4 bytes starting at the specified offset. * * @param b the byte array containing the integer value. * @param off the offset in the byte array to use when parsing. * @return the constructed integer value. */ // @ private normal_behavior // @ requires 0 <= off && off <= b.length - Integer.BYTES; // @ ensures \result == Integer.asInt(b[off],b[off+1],b[off+2],b[off+3]); // @ pure spec_public private static int getInt(final byte[] b, final int off) { return ((b[off + 3] & 0xFF)) + ((b[off + 2] & 0xFF) << 8) + ((b[off + 1] & 0xFF) << 16) + ((b[off] & 0xFF) << 24); } /** * Construct a short value using 4 bytes starting at the specified offset. * * @param b the byte array containing the short value. * @param off the offset in the byte array to use when parsing. * @return the constructed short value. */ // @ private normal_behavior // @ requires 0 <= off && off <= b.length - Short.BYTES; // @ ensures \result == Short.asShort(b[off],b[off+1]); // @ pure spec_public private static short getShort(final byte[] b, final int off) { return (short) ((b[off + 1] & 0xFF) + ((b[off] & 0xFF) << 8)); } /** * Parse a long primitive type in the provided bytes. It looks for 8 bytes in the provided bytes * starting at the specified off. * * <p>If successful, it returns the value of the parsed long type. On failure, it throws a parse * exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the parsed long value. * @throws ParseException if there are not sufficient bytes. */ // @ public normal_behavior // @ requires 0 <= off && off <= b.length - Long.BYTES; // @ ensures \result == // Long.asLong(b[off],b[off+1],b[off+2],b[off+3],b[off+4],b[off+5],b[off+6],b[off+7]); // @ also private exceptional_behavior // @ requires b.length - Long.BYTES < off; // @ signals_only ParseException; // @ pure public static long parseLong(final byte[] b, final int off) throws ParseException { final int size = Long.SIZE / Byte.SIZE; final int len = b.length - off; if (len >= size) { return getLong(b, off); } else { throw new ParseException("Not enough bytes to parse a long."); } } /** * Parse an integer primitive type in the provided bytes. It looks for 4 bytes in the provided * bytes starting at the specified off. * * <p>If successful, it returns the value of the parsed integer type. On failure, it throws a * parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the parsed integer value. * @throws ParseException if there are not sufficient bytes. */ // @ public normal_behavior // @ requires 0 <= off && off <= b.length - Integer.BYTES; // @ ensures \result == Integer.asInt(b[off],b[off+1],b[off+2],b[off+3]); // @ also private exceptional_behavior // @ requires b.length - Integer.BYTES < off; // @ signals_only ParseException; // @ pure public static int parseInt(final byte[] b, final int off) throws ParseException { final int size = Integer.SIZE / Byte.SIZE; final int len = b.length - off; if (len >= size) { return getInt(b, off); } else { throw new ParseException("Not enough bytes to parse an integer."); } } /** * Parse a short primitive type in the provided bytes. It looks for 2 bytes in the provided bytes * starting at the specified off. * * <p>If successful, it returns the value of the parsed short type. On failure, it throws a parse * exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the parsed short value. * @throws ParseException if there are not sufficient bytes. */ // @ public normal_behavior // @ requires 0 <= off && off <= b.length - Short.BYTES; // @ ensures \result == Short.asShort(b[off],b[off+1]); // @ also private exceptional_behavior // @ requires b.length - Short.BYTES < off; // @ signals_only ParseException; // @ pure public static short parseShort(final byte[] b, final int off) { final short size = Short.SIZE / Byte.SIZE; final int len = b.length - off; if (len >= size) { return getShort(b, off); } else { throw new ParseException("Not enough bytes to parse a short."); } } /** * Equivalent to {@link #parseShort(byte[], int)} except the 2 bytes are treated as an unsigned * value (and thus returned as an into to avoid overflow). */ // @ public normal_behavior // @ requires 0 <= off && off <= b.length - Short.BYTES; // @ ensures \result == Short.asUnsignedToInt(Short.asShort(b[off], b[off+1])); // @ ensures \result >= 0 && \result <= Constants.UNSIGNED_SHORT_MAX_VAL; // @ also private exceptional_behavior // @ requires b.length - Short.BYTES < off; // @ signals_only ParseException; // @ pure public static int parseUnsignedShort(final byte[] b, final int off) { final int signedResult = parseShort(b, off); if (signedResult >= 0) { return signedResult; } else { return Constants.UNSIGNED_SHORT_MAX_VAL + 1 + signedResult; } } /** Writes 2 bytes containing the unsigned value {@code uShort} to {@code out}. */ // @ // left as TODO because OpenJML/Specs does not have sufficiently detailed // @ // specs for java.io.DataOutput // @ public normal_behavior // @ requires 0 <= uShort && uShort < -Short.MIN_VALUE-Short.MIN_VALUE; // @// assignable TODO ... // @// ensures TODO ... public static void writeUnsignedShort(final DataOutput out, final int uShort) throws IOException { if (uShort < 0 || uShort > Constants.UNSIGNED_SHORT_MAX_VAL) { throw new IllegalArgumentException( "Unsigned shorts must be between 0 and " + Constants.UNSIGNED_SHORT_MAX_VAL); } if (uShort < Short.MAX_VALUE) { out.writeShort(uShort); } else { out.writeShort(uShort - Constants.UNSIGNED_SHORT_MAX_VAL - 1); } } /** * Parse a single byte in the provided bytes. It looks for a byte in the provided bytes starting * at the specified off. * * <p>If successful, it returns the value of the parsed byte. On failure, it throws a parse * exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the parsed byte value. * @throws ParseException if there are not sufficient bytes. */ // @ public normal_behavior // @ requires 0 <= off && off <= b.length - Byte.BYTES; // @ ensures \result == b[off]; // @ also private exceptional_behavior // @ requires b.length - Byte.BYTES < off; // @ signals_only ParseException; // @ pure public static byte parseByte(final byte[] b, final int off) { final int size = 1; final int len = b.length - off; if (len >= size) { return b[off]; } else { throw new ParseException("Not enough bytes to parse a byte."); } } }
5,475
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/JceKeyCipher.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.Key; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; import org.apache.commons.lang3.ArrayUtils; /** Abstract class for encrypting and decrypting JCE data keys. */ public abstract class JceKeyCipher { private final Key wrappingKey; private final Key unwrappingKey; private static final Charset KEY_NAME_ENCODING = StandardCharsets.UTF_8; /** * Returns a new instance of a JceKeyCipher based on the Advanced Encryption Standard in * Galois/Counter Mode. * * @param secretKey The secret key to use for encrypt/decrypt operations. * @return The JceKeyCipher. */ public static JceKeyCipher aesGcm(SecretKey secretKey) { return new AesGcmJceKeyCipher(secretKey); } /** * Returns a new instance of a JceKeyCipher based on RSA. * * @param wrappingKey The public key to use for encrypting the key. * @param unwrappingKey The private key to use for decrypting the key. * @param transformation The transformation. * @return The JceKeyCipher. */ public static JceKeyCipher rsa( PublicKey wrappingKey, PrivateKey unwrappingKey, String transformation) { return new RsaJceKeyCipher(wrappingKey, unwrappingKey, transformation); } JceKeyCipher(Key wrappingKey, Key unwrappingKey) { this.wrappingKey = wrappingKey; this.unwrappingKey = unwrappingKey; } abstract WrappingData buildWrappingCipher(Key key, Map<String, String> encryptionContext) throws GeneralSecurityException; abstract Cipher buildUnwrappingCipher( Key key, byte[] extraInfo, int offset, Map<String, String> encryptionContext) throws GeneralSecurityException; /** * Encrypts the given key, incorporating the given keyName and encryptionContext. * * @param key The key to encrypt. * @param keyName A UTF-8 encoded representing a name for the key. * @param keyNamespace A UTF-8 encoded value that namespaces the key. * @param encryptionContext A key-value mapping of arbitrary, non-secret, UTF-8 encoded strings * used during encryption and decryption to provide additional authenticated data (AAD). * @return The encrypted data key. */ public EncryptedDataKey encryptKey( final byte[] key, final String keyName, final String keyNamespace, final Map<String, String> encryptionContext) { final byte[] keyNameBytes = keyName.getBytes(KEY_NAME_ENCODING); try { final JceKeyCipher.WrappingData wData = buildWrappingCipher(wrappingKey, encryptionContext); final Cipher cipher = wData.cipher; final byte[] encryptedKey = cipher.doFinal(key); final byte[] provInfo; if (wData.extraInfo.length == 0) { provInfo = keyNameBytes; } else { provInfo = new byte[keyNameBytes.length + wData.extraInfo.length]; System.arraycopy(keyNameBytes, 0, provInfo, 0, keyNameBytes.length); System.arraycopy(wData.extraInfo, 0, provInfo, keyNameBytes.length, wData.extraInfo.length); } return new KeyBlob(keyNamespace, provInfo, encryptedKey); } catch (final GeneralSecurityException gsex) { throw new AwsCryptoException(gsex); } } /** * Decrypts the given encrypted data key. * * @param edk The encrypted data key. * @param keyName A UTF-8 encoded String representing a name for the key. * @param encryptionContext A key-value mapping of arbitrary, non-secret, UTF-8 encoded strings * used during encryption and decryption to provide additional authenticated data (AAD). * @return The decrypted key. * @throws GeneralSecurityException If a problem occurred decrypting the key. */ public byte[] decryptKey( final EncryptedDataKey edk, final String keyName, final Map<String, String> encryptionContext) throws GeneralSecurityException { final byte[] keyNameBytes = keyName.getBytes(KEY_NAME_ENCODING); final Cipher cipher = buildUnwrappingCipher( unwrappingKey, edk.getProviderInformation(), keyNameBytes.length, encryptionContext); return cipher.doFinal(edk.getEncryptedDataKey()); } static class WrappingData { public final Cipher cipher; public final byte[] extraInfo; WrappingData(final Cipher cipher, final byte[] extraInfo) { this.cipher = cipher; this.extraInfo = extraInfo != null ? extraInfo : ArrayUtils.EMPTY_BYTE_ARRAY; } } }
5,476
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/Utils.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import java.io.Serializable; import java.math.BigInteger; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Arrays; import java.util.Comparator; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang3.ArrayUtils; import org.bouncycastle.util.encoders.Base64; /** Internal utility methods. */ public final class Utils { // SecureRandom objects can both be expensive to initialize and incur synchronization costs. // This allows us to minimize both initializations and keep SecureRandom usage thread local // to avoid lock contention. private static final ThreadLocal<SecureRandom> LOCAL_RANDOM = new ThreadLocal<SecureRandom>() { @Override protected SecureRandom initialValue() { final SecureRandom rnd = new SecureRandom(); rnd.nextBoolean(); // Force seeding return rnd; } }; private Utils() { // Prevent instantiation } /* * In some areas we need to be able to assign a total order over Java objects - generally with some primary sort, * but we need a fallback sort that always works in order to ensure that we don't falsely claim objects A and B * are equal just because the primary sort declares them to have equal rank. * * To do this, we'll define a fallback sort that assigns an arbitrary order to all objects. This order is * implemented by first comparing hashcode, and in the rare case where we are asked to compare two objects with * equal hashcode, we explicitly assign an index to them - using a WeakHashMap to track this index - and sort * based on this index. */ private static AtomicLong FALLBACK_COUNTER = new AtomicLong(0); private static WeakHashMap<Object, Long> FALLBACK_COMPARATOR_MAP = new WeakHashMap<>(); private static synchronized long getFallbackObjectId(Object object) { return FALLBACK_COMPARATOR_MAP.computeIfAbsent( object, ignored -> FALLBACK_COUNTER.incrementAndGet()); } /** * Provides an <i>arbitrary</i> but consistent total ordering over all objects. This comparison * function will return 0 if and only if a == b, and otherwise will return arbitrarily either -1 * or 1, but will do so in a way that results in a consistent total order. * * @param a * @param b * @return -1 or 1 (consistently) if a != b; 0 if a == b. */ public static int compareObjectIdentity(Object a, Object b) { if (a == b) { return 0; } if (a == null) { return -1; } if (b == null) { return 1; } int hashCompare = Integer.compare(System.identityHashCode(a), System.identityHashCode(b)); if (hashCompare != 0) { return hashCompare; } // Unfortunately these objects have identical hashcodes, so we need to find some other way to // compare them. // We'll do this by mapping them to an incrementing counter, and comparing their assigned IDs // instead. int fallbackCompare = Long.compare(getFallbackObjectId(a), getFallbackObjectId(b)); if (fallbackCompare == 0) { throw new AssertionError("Failed to assign unique order to objects"); } return fallbackCompare; } public static long saturatingAdd(long a, long b) { long r = a + b; if (a > 0 && b > 0 && r < a) { return Long.MAX_VALUE; } if (a < 0 && b < 0 && r > a) { return Long.MIN_VALUE; } // If the signs between a and b differ, overflow is impossible. return r; } /** * Comparator that performs a lexicographical comparison of byte arrays, treating them as * unsigned. */ public static class ComparingByteArrays implements Comparator<byte[]>, Serializable { // We don't really need to be serializable, but it doesn't hurt, and FindBugs gets annoyed if // we're not. private static final long serialVersionUID = 0xdf641037ffe509e2L; @Override public int compare(byte[] o1, byte[] o2) { return new ComparingByteBuffers().compare(ByteBuffer.wrap(o1), ByteBuffer.wrap(o2)); } } public static class ComparingByteBuffers implements Comparator<ByteBuffer>, Serializable { private static final long serialVersionUID = 0xa3c4a7300fbbf043L; @Override public int compare(ByteBuffer o1, ByteBuffer o2) { o1 = o1.slice(); o2 = o2.slice(); int commonLength = Math.min(o1.remaining(), o2.remaining()); for (int i = 0; i < commonLength; i++) { // Perform zero-extension as we want to treat the bytes as unsigned int v1 = o1.get(i) & 0xFF; int v2 = o2.get(i) & 0xFF; if (v1 != v2) { return v1 - v2; } } // The longer buffer is bigger (0x00 comes after end-of-buffer) return o1.remaining() - o2.remaining(); } } /** * Throws {@link NullPointerException} with message {@code paramName} if {@code object} is null. * * @param object value to be null-checked * @param paramName message for the potential {@link NullPointerException} * @return {@code object} * @throws NullPointerException if {@code object} is null */ public static <T> T assertNonNull(final T object, final String paramName) throws NullPointerException { if (object == null) { throw new NullPointerException(paramName + " must not be null"); } return object; } /** * Returns a possibly truncated version of {@code arr} which is guaranteed to be exactly {@code * len} elements long. If {@code arr} is already exactly {@code len} elements long, then {@code * arr} is returned without copy or modification. If {@code arr} is longer than {@code len}, then * a truncated copy is returned. If {@code arr} is shorter than {@code len} then this throws an * {@link IllegalArgumentException}. */ public static byte[] truncate(final byte[] arr, final int len) throws IllegalArgumentException { if (arr.length == len) { return arr; } else if (arr.length > len) { return Arrays.copyOf(arr, len); } else { throw new IllegalArgumentException("arr is not at least " + len + " elements long"); } } public static SecureRandom getSecureRandom() { return LOCAL_RANDOM.get(); } /** * Generate the AAD bytes to use when encrypting/decrypting content. The generated AAD is a block * of bytes containing the provided message identifier, the string identifier, the sequence * number, and the length of the content. * * @param messageId the unique message identifier for the ciphertext. * @param idString the string describing the type of content processed. * @param seqNum the sequence number. * @param len the length of the content. * @return the bytes containing the generated AAD. */ static byte[] generateContentAad( final byte[] messageId, final String idString, final int seqNum, final long len) { final byte[] idBytes = idString.getBytes(StandardCharsets.UTF_8); final int aadLen = messageId.length + idBytes.length + Integer.SIZE / Byte.SIZE + Long.SIZE / Byte.SIZE; final ByteBuffer aad = ByteBuffer.allocate(aadLen); aad.put(messageId); aad.put(idBytes); aad.putInt(seqNum); aad.putLong(len); return aad.array(); } static IllegalArgumentException cannotBeNegative(String field) { return new IllegalArgumentException(field + " cannot be negative"); } /** * Equivalent to calling {@link ByteBuffer#flip()} but in a manner which is safe when compiled on * Java 9 or newer but used on Java 8 or older. */ public static ByteBuffer flip(final ByteBuffer buff) { ((Buffer) buff).flip(); return buff; } /** * Equivalent to calling {@link ByteBuffer#clear()} but in a manner which is safe when compiled on * Java 9 or newer but used on Java 8 or older. */ public static ByteBuffer clear(final ByteBuffer buff) { ((Buffer) buff).clear(); return buff; } /** * Equivalent to calling {@link ByteBuffer#position(int)} but in a manner which is safe when * compiled on Java 9 or newer but used on Java 8 or older. */ public static ByteBuffer position(final ByteBuffer buff, final int newPosition) { ((Buffer) buff).position(newPosition); return buff; } /** * Equivalent to calling {@link ByteBuffer#limit(int)} but in a manner which is safe when compiled * on Java 9 or newer but used on Java 8 or older. */ public static ByteBuffer limit(final ByteBuffer buff, final int newLimit) { ((Buffer) buff).limit(newLimit); return buff; } /** * Takes a Base64-encoded String, decodes it, and returns contents as a byte array. * * @param encoded Base64 encoded String * @return decoded data as a byte array */ public static byte[] decodeBase64String(final String encoded) { return encoded.isEmpty() ? ArrayUtils.EMPTY_BYTE_ARRAY : Base64.decode(encoded); } /** * Takes data in a byte array, encodes them in Base64, and returns the result as a String. * * @param data The data to encode. * @return Base64 string that encodes the {@code data}. */ public static String encodeBase64String(final byte[] data) { return Base64.toBase64String(data); } /** * Removes the leading zero sign byte from the byte array representation of a BigInteger (if * present) and left pads with zeroes to produce a byte array of the given length. * * @param bigInteger The BigInteger to convert to a byte array * @param length The length of the byte array, must be at least as long as the BigInteger byte * array without the sign byte * @return The byte array */ public static byte[] bigIntegerToByteArray(final BigInteger bigInteger, final int length) { byte[] rawBytes = bigInteger.toByteArray(); // If rawBytes is already the correct length, return it. if (rawBytes.length == length) { return rawBytes; } // If we're exactly one byte too large, but we have a leading zero byte, remove it and return. if (rawBytes.length == length + 1 && rawBytes[0] == 0) { return Arrays.copyOfRange(rawBytes, 1, rawBytes.length); } if (rawBytes.length > length) { throw new IllegalArgumentException( "Length must be at least as long as the BigInteger byte array " + "without the sign byte"); } final byte[] paddedResult = new byte[length]; System.arraycopy(rawBytes, 0, paddedResult, length - rawBytes.length, rawBytes.length); return paddedResult; } /** * Returns true if the prefix of the given length for the input arrays are equal. This method will * return as soon as the first difference is found, and is thus not constant-time. * * @param a The first array. * @param b The second array. * @param length The length of the prefix to compare. * @return True if the prefixes are equal, false otherwise. */ public static boolean arrayPrefixEquals(final byte[] a, final byte[] b, final int length) { if (a == null || b == null || a.length < length || b.length < length) { return false; } for (int x = 0; x < length; x++) { if (a[x] != b[x]) { return false; } } return true; } }
5,477
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/TrailingSignatureAlgorithm.java
package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.internal.Utils.bigIntegerToByteArray; import static com.amazonaws.encryptionsdk.internal.Utils.encodeBase64String; import static java.math.BigInteger.ONE; import static java.math.BigInteger.ZERO; import static org.apache.commons.lang3.Validate.isInstanceOf; import static org.apache.commons.lang3.Validate.notNull; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import java.math.BigInteger; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.interfaces.ECPublicKey; import java.security.spec.ECFieldFp; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidParameterSpecException; import java.util.Arrays; /** * Provides a consistent interface across various trailing signature algorithms. * * <p>NOTE: This is not a stable API and may undergo breaking changes in the future. */ public abstract class TrailingSignatureAlgorithm { private TrailingSignatureAlgorithm() { /* Do not allow arbitrary subclasses */ } public abstract String getMessageDigestAlgorithm(); public abstract String getRawSignatureAlgorithm(); public abstract String getHashAndSignAlgorithm(); public abstract PublicKey deserializePublicKey(String keyString); public abstract String serializePublicKey(PublicKey key); public abstract KeyPair generateKey() throws GeneralSecurityException; /* Standards for Efficient Cryptography over a prime field */ private static final String SEC_PRIME_FIELD_PREFIX = "secp"; private static final class ECDSASignatureAlgorithm extends TrailingSignatureAlgorithm { private final ECGenParameterSpec ecSpec; private final ECParameterSpec ecParameterSpec; private final String messageDigestAlgorithm; private final String hashAndSignAlgorithm; private static final String ELLIPTIC_CURVE_ALGORITHM = "EC"; /* Constants used by SEC-1 v2 point compression and decompression algorithms */ private static final BigInteger TWO = BigInteger.valueOf(2); private static final BigInteger THREE = BigInteger.valueOf(3); private static final BigInteger FOUR = BigInteger.valueOf(4); private ECDSASignatureAlgorithm( ECGenParameterSpec ecSpec, String messageDigestAlgorithm, String hashAndSignAlgorithm) { if (!ecSpec.getName().startsWith(SEC_PRIME_FIELD_PREFIX)) { throw new IllegalStateException("Non-prime curves are not supported at this time"); } this.ecSpec = ecSpec; this.messageDigestAlgorithm = messageDigestAlgorithm; this.hashAndSignAlgorithm = hashAndSignAlgorithm; try { final AlgorithmParameters parameters = AlgorithmParameters.getInstance(ELLIPTIC_CURVE_ALGORITHM); parameters.init(ecSpec); this.ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class); } catch (NoSuchAlgorithmException | InvalidParameterSpecException e) { throw new IllegalStateException("Invalid algorithm", e); } } @Override public String toString() { return "ECDSASignatureAlgorithm(curve=" + ecSpec.getName() + ")"; } @Override public String getMessageDigestAlgorithm() { return messageDigestAlgorithm; } @Override public String getRawSignatureAlgorithm() { return "NONEwithECDSA"; } @Override public String getHashAndSignAlgorithm() { return hashAndSignAlgorithm; } /** * Decodes a compressed elliptic curve point as described in SEC-1 v2 section 2.3.4 * * @param keyString The serialized and compressed public key * @return The PublicKey * @see <a href="http://www.secg.org/sec1-v2.pdf">http://www.secg.org/sec1-v2.pdf</a> */ @Override public PublicKey deserializePublicKey(String keyString) { notNull(keyString, "keyString is required"); final byte[] decodedKey = Utils.decodeBase64String(keyString); final BigInteger x = new BigInteger(1, Arrays.copyOfRange(decodedKey, 1, decodedKey.length)); final byte compressedY = decodedKey[0]; final BigInteger yOrder; if (compressedY == TWO.byteValue()) { yOrder = ZERO; } else if (compressedY == THREE.byteValue()) { yOrder = ONE; } else { throw new IllegalArgumentException("Compressed y value was invalid"); } final BigInteger p = ((ECFieldFp) ecParameterSpec.getCurve().getField()).getP(); final BigInteger a = ecParameterSpec.getCurve().getA(); final BigInteger b = ecParameterSpec.getCurve().getB(); // alpha must be equal to y^2, this is validated below final BigInteger alpha = x.modPow(THREE, p).add(a.multiply(x).mod(p)).add(b).mod(p); final BigInteger beta; if (p.mod(FOUR).equals(THREE)) { beta = alpha.modPow(p.add(ONE).divide(FOUR), p); } else { throw new IllegalArgumentException("Curve not supported at this time"); } final BigInteger y = beta.mod(TWO).equals(yOrder) ? beta : p.subtract(beta); // Validate that Y is a root of Y^2 to prevent invalid point attacks if (!alpha.equals(y.modPow(TWO, p))) { throw new IllegalArgumentException("Y was invalid"); } try { return KeyFactory.getInstance(ELLIPTIC_CURVE_ALGORITHM) .generatePublic(new ECPublicKeySpec(new ECPoint(x, y), ecParameterSpec)); } catch (InvalidKeySpecException | NoSuchAlgorithmException e) { throw new IllegalStateException("Invalid algorithm", e); } } /** * Encodes a compressed elliptic curve point as described in SEC-1 v2 section 2.3.3 * * @param key The Elliptic Curve public key to compress and serialize * @return The serialized and compressed public key * @see <a href="http://www.secg.org/sec1-v2.pdf">http://www.secg.org/sec1-v2.pdf</a> */ @Override public String serializePublicKey(PublicKey key) { notNull(key, "key is required"); isInstanceOf(ECPublicKey.class, key, "key must be an instance of ECPublicKey"); final BigInteger x = ((ECPublicKey) key).getW().getAffineX(); final BigInteger y = ((ECPublicKey) key).getW().getAffineY(); final BigInteger compressedY = y.mod(TWO).equals(ZERO) ? TWO : THREE; final byte[] xBytes = bigIntegerToByteArray( x, ecParameterSpec.getCurve().getField().getFieldSize() / Byte.SIZE); final byte[] compressedKey = new byte[xBytes.length + 1]; System.arraycopy(xBytes, 0, compressedKey, 1, xBytes.length); compressedKey[0] = compressedY.byteValue(); return encodeBase64String(compressedKey); } @Override public KeyPair generateKey() throws GeneralSecurityException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ELLIPTIC_CURVE_ALGORITHM); keyGen.initialize(ecSpec, Utils.getSecureRandom()); return keyGen.generateKeyPair(); } } private static final ECDSASignatureAlgorithm SHA256_ECDSA_P256 = new ECDSASignatureAlgorithm( new ECGenParameterSpec(SEC_PRIME_FIELD_PREFIX + "256r1"), "SHA-256", "SHA256withECDSA"); private static final ECDSASignatureAlgorithm SHA384_ECDSA_P384 = new ECDSASignatureAlgorithm( new ECGenParameterSpec(SEC_PRIME_FIELD_PREFIX + "384r1"), "SHA-384", "SHA384withECDSA"); public static TrailingSignatureAlgorithm forCryptoAlgorithm(CryptoAlgorithm algorithm) { switch (algorithm) { case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256: return SHA256_ECDSA_P256; case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384: case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384: case ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384: return SHA384_ECDSA_P384; default: throw new IllegalStateException("Algorithm does not support trailing signature"); } } }
5,478
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/CipherHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.security.GeneralSecurityException; import java.security.spec.AlgorithmParameterSpec; import javax.annotation.concurrent.NotThreadSafe; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; /** * This class provides a cryptographic cipher handler powered by an underlying block cipher. The * block cipher performs authenticated encryption of the provided bytes using Additional * Authenticated Data (AAD). * * <p>This class implements a method called cipherData() that encrypts or decrypts a byte array by * calling methods on the underlying block cipher. */ @NotThreadSafe class CipherHandler { private final int cipherMode_; private final SecretKey key_; private final CryptoAlgorithm cryptoAlgorithm_; private final Cipher cipher_; /** * Process data through the cipher. * * <p>This method calls the <code>update</code> and <code>doFinal</code> methods on the underlying * cipher to complete processing of the data. * * @param nonce the nonce to be used by the underlying cipher * @param contentAad the optional additional authentication data to be used by the underlying * cipher * @param content the content to be processed by the underlying cipher * @param off the offset into content array to be processed * @param len the number of bytes to process * @return the bytes processed by the underlying cipher * @throws AwsCryptoException if cipher initialization fails * @throws BadCiphertextException if processing the data through the cipher fails */ public byte[] cipherData( byte[] nonce, byte[] contentAad, final byte[] content, final int off, final int len) { if (nonce.length != cryptoAlgorithm_.getNonceLen()) { throw new IllegalArgumentException("Invalid nonce length: " + nonce.length); } final AlgorithmParameterSpec spec = new GCMParameterSpec(cryptoAlgorithm_.getTagLen() * 8, nonce, 0, nonce.length); try { cipher_.init(cipherMode_, key_, spec); if (contentAad != null) { cipher_.updateAAD(contentAad); } } catch (final GeneralSecurityException gsx) { throw new AwsCryptoException(gsx); } try { return cipher_.doFinal(content, off, len); } catch (final GeneralSecurityException gsx) { throw new BadCiphertextException(gsx); } } /** * Create a cipher handler for processing bytes using an underlying block cipher. * * @param key the key to use in encrypting or decrypting bytes * @param cipherMode the mode for processing the bytes as defined in {@link Cipher#init(int, * java.security.Key)} * @param cryptoAlgorithm the cryptography algorithm to be used by the underlying block cipher. * @throws GeneralSecurityException */ CipherHandler(final SecretKey key, final int cipherMode, final CryptoAlgorithm cryptoAlgorithm) { this.cipherMode_ = cipherMode; this.key_ = key; this.cryptoAlgorithm_ = cryptoAlgorithm; this.cipher_ = buildCipherObject(cryptoAlgorithm); } private static Cipher buildCipherObject(final CryptoAlgorithm alg) { try { // Right now, just GCM is supported return Cipher.getInstance("AES/GCM/NoPadding"); } catch (final GeneralSecurityException ex) { throw new IllegalStateException("Java does not support the requested algorithm", ex); } } }
5,479
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/MessageCryptoHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import java.util.List; import java.util.Map; public interface MessageCryptoHandler extends CryptoHandler { /** * Informs this handler of an upper bound on the input data size. The handler will throw an * exception if this bound is exceeded, and may use it to perform performance optimizations as * well. * * <p>If this method is called multiple times, the smallest bound will be used. * * @param size An upper bound on the input data size. */ void setMaxInputLength(long size); /** * Return the encryption context used in the generation of the data key used for the encryption of * content. * * <p>During decryption, this value should be obtained by parsing the ciphertext headers that * encodes this value. * * @return the key-value map containing the encryption context. */ Map<String, String> getEncryptionContext(); CiphertextHeaders getHeaders(); /** * All <em>used</em> {@link MasterKey}s. For encryption flows, these are all the {@link * MasterKey}s used to protect the data. In the decryption flow, it is the single {@link * MasterKey} actually used to decrypt the data. */ List<? extends MasterKey<?>> getMasterKeys(); }
5,480
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/EncryptionHandler.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.model.CiphertextFooters; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.CiphertextType; import com.amazonaws.encryptionsdk.model.ContentType; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.ECPrivateKey; import java.util.List; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; /** * This class implements the CryptoHandler interface by providing methods for the encryption of * plaintext data. * * <p>This class creates the ciphertext headers and delegates the encryption of the plaintext to the * {@link BlockEncryptionHandler} or {@link FrameEncryptionHandler} based on the content type. */ public class EncryptionHandler implements MessageCryptoHandler { private static final CiphertextType CIPHERTEXT_TYPE = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA; private final EncryptionMaterials encryptionMaterials_; private final Map<String, String> encryptionContext_; private final CryptoAlgorithm cryptoAlgo_; private final List<MasterKey> masterKeys_; private final List<KeyBlob> keyBlobs_; private final SecretKey encryptionKey_; private final byte version_; private final CiphertextType type_; private final byte nonceLen_; private final PrivateKey trailingSignaturePrivateKey_; private final MessageDigest trailingDigest_; private final Signature trailingSig_; private final CiphertextHeaders ciphertextHeaders_; private final byte[] ciphertextHeaderBytes_; private final CryptoHandler contentCryptoHandler_; private boolean firstOperation_ = true; private boolean complete_ = false; private long plaintextBytes_ = 0; private long plaintextByteLimit_ = -1; /** * Create an encryption handler using the provided master key and encryption context. * * @param frameSize The encryption frame size, or zero for a one-shot encryption task * @param result The EncryptionMaterials with the crypto materials for this encryption job * @throws AwsCryptoException if the encryption context or master key is null. */ public EncryptionHandler( int frameSize, EncryptionMaterials result, CommitmentPolicy commitmentPolicy) throws AwsCryptoException { Utils.assertNonNull(result, "result"); Utils.assertNonNull(commitmentPolicy, "commitmentPolicy"); this.encryptionMaterials_ = result; this.encryptionContext_ = result.getEncryptionContext(); if (!commitmentPolicy.algorithmAllowedForEncrypt(result.getAlgorithm())) { if (commitmentPolicy == CommitmentPolicy.ForbidEncryptAllowDecrypt) { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy + " requiring only non-committed messages. Algorithm ID was " + result.getAlgorithm() + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } else { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy + " requiring only committed messages. Algorithm ID was " + result.getAlgorithm() + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } } this.cryptoAlgo_ = result.getAlgorithm(); this.masterKeys_ = result.getMasterKeys(); this.keyBlobs_ = result.getEncryptedDataKeys(); this.trailingSignaturePrivateKey_ = result.getTrailingSignatureKey(); if (keyBlobs_.isEmpty()) { throw new IllegalArgumentException("No encrypted data keys in materials result"); } if (trailingSignaturePrivateKey_ != null) { try { TrailingSignatureAlgorithm algorithm = TrailingSignatureAlgorithm.forCryptoAlgorithm(cryptoAlgo_); trailingDigest_ = MessageDigest.getInstance(algorithm.getMessageDigestAlgorithm()); trailingSig_ = Signature.getInstance(algorithm.getRawSignatureAlgorithm()); trailingSig_.initSign(trailingSignaturePrivateKey_, Utils.getSecureRandom()); } catch (final GeneralSecurityException ex) { throw new AwsCryptoException(ex); } } else { trailingDigest_ = null; trailingSig_ = null; } // set default values version_ = cryptoAlgo_.getMessageFormatVersion(); type_ = CIPHERTEXT_TYPE; nonceLen_ = cryptoAlgo_.getNonceLen(); ContentType contentType; if (frameSize > 0) { contentType = ContentType.FRAME; } else if (frameSize == 0) { contentType = ContentType.SINGLEBLOCK; } else { throw Utils.cannotBeNegative("Frame size"); } // Construct the headers // Included here rather than as a sub-routine so we can set final variables. // This way we can avoid calculating the keys more times than we need. final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext_); final CiphertextHeaders unsignedHeaders = new CiphertextHeaders( type_, cryptoAlgo_, encryptionContextBytes, keyBlobs_, contentType, frameSize); // We use a deterministic IV of zero for the header authentication. unsignedHeaders.setHeaderNonce(new byte[nonceLen_]); // If using a committing crypto algorithm, we also need to calculate the commitment value along // with the key derivation if (cryptoAlgo_.isCommitting()) { final CommittedKey committedKey = CommittedKey.generate( cryptoAlgo_, result.getCleartextDataKey(), unsignedHeaders.getMessageId()); unsignedHeaders.setSuiteData(committedKey.getCommitment()); encryptionKey_ = committedKey.getKey(); } else { try { encryptionKey_ = cryptoAlgo_.getEncryptionKeyFromDataKey(result.getCleartextDataKey(), unsignedHeaders); } catch (final InvalidKeyException ex) { throw new AwsCryptoException(ex); } } ciphertextHeaders_ = signCiphertextHeaders(unsignedHeaders); ciphertextHeaderBytes_ = ciphertextHeaders_.toByteArray(); byte[] messageId_ = ciphertextHeaders_.getMessageId(); switch (contentType) { case FRAME: contentCryptoHandler_ = new FrameEncryptionHandler( encryptionKey_, nonceLen_, cryptoAlgo_, messageId_, frameSize); break; case SINGLEBLOCK: contentCryptoHandler_ = new BlockEncryptionHandler(encryptionKey_, nonceLen_, cryptoAlgo_, messageId_); break; default: // should never get here because a valid content type is always // set above based on the frame size. throw new AwsCryptoException("Unknown content type."); } } /** * Encrypt a block of bytes from {@code in} putting the plaintext result into {@code out}. * * <p>It encrypts by performing the following operations: * * <ol> * <li>if this is the first call to encrypt, write the ciphertext headers to the output being * returned. * <li>else, pass off the input data to underlying content cryptohandler. * </ol> * * @param in the input byte array. * @param off the offset into the in array where the data to be encrypted starts. * @param len the number of bytes to be encrypted. * @param out the output buffer the encrypted bytes go into. * @param outOff the offset into the output byte array the encrypted data starts at. * @return the number of bytes written to out and processed * @throws AwsCryptoException if len or offset values are negative. * @throws BadCiphertextException thrown by the underlying cipher handler. */ @Override public ProcessingSummary processBytes( final byte[] in, final int off, final int len, final byte[] out, final int outOff) throws AwsCryptoException, BadCiphertextException { if (len < 0 || off < 0) { throw new AwsCryptoException( String.format("Invalid values for input offset: %d and length: %d", off, len)); } checkPlaintextSizeLimit(len); int actualOutLen = 0; if (firstOperation_ == true) { System.arraycopy(ciphertextHeaderBytes_, 0, out, outOff, ciphertextHeaderBytes_.length); actualOutLen += ciphertextHeaderBytes_.length; firstOperation_ = false; } ProcessingSummary contentOut = contentCryptoHandler_.processBytes(in, off, len, out, outOff + actualOutLen); actualOutLen += contentOut.getBytesWritten(); updateTrailingSignature(out, outOff, actualOutLen); plaintextBytes_ += contentOut.getBytesProcessed(); return new ProcessingSummary(actualOutLen, contentOut.getBytesProcessed()); } /** * Finish encryption of the plaintext bytes. * * @param out space for any resulting output data. * @param outOff offset into out to start copying the data at. * @return number of bytes written into out. * @throws BadCiphertextException thrown by the underlying cipher handler. */ @Override public int doFinal(final byte[] out, final int outOff) throws BadCiphertextException { if (complete_) { throw new IllegalStateException("Attempted to call doFinal twice"); } complete_ = true; checkPlaintextSizeLimit(0); int written = contentCryptoHandler_.doFinal(out, outOff); updateTrailingSignature(out, outOff, written); if (cryptoAlgo_.getTrailingSignatureLength() > 0) { try { CiphertextFooters footer = new CiphertextFooters(signContent()); byte[] fBytes = footer.toByteArray(); System.arraycopy(fBytes, 0, out, outOff + written, fBytes.length); return written + fBytes.length; } catch (final SignatureException ex) { throw new AwsCryptoException(ex); } } else { return written; } } private byte[] signContent() throws SignatureException { if (trailingDigest_ != null) { if (!trailingSig_.getAlgorithm().contains("ECDSA")) { throw new UnsupportedOperationException( "Signatures calculated in pieces is only supported for ECDSA."); } final byte[] digest = trailingDigest_.digest(); return generateEcdsaFixedLengthSignature(digest); } return trailingSig_.sign(); } private byte[] generateEcdsaFixedLengthSignature(final byte[] digest) throws SignatureException { byte[] signature; // Unfortunately, we need deterministic lengths some signatures are non-deterministic in length. // So, retry until we get the right length :-( do { trailingSig_.update(digest); signature = trailingSig_.sign(); if (signature.length != cryptoAlgo_.getTrailingSignatureLength()) { // Most of the time, a signature of the wrong length can be fixed // be negating s in the signature relative to the group order. ASN1Sequence seq = ASN1Sequence.getInstance(signature); ASN1Integer r = (ASN1Integer) seq.getObjectAt(0); ASN1Integer s = (ASN1Integer) seq.getObjectAt(1); ECPrivateKey ecKey = (ECPrivateKey) trailingSignaturePrivateKey_; s = new ASN1Integer(ecKey.getParams().getOrder().subtract(s.getPositiveValue())); seq = new DERSequence(new ASN1Encodable[] {r, s}); try { signature = seq.getEncoded(); } catch (IOException ex) { throw new SignatureException(ex); } } } while (signature.length != cryptoAlgo_.getTrailingSignatureLength()); return signature; } /** * Return the size of the output buffer required for a {@code processBytes} plus a {@code doFinal} * with an input of inLen bytes. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and doFinal with len bytes of * input. */ @Override public int estimateOutputSize(final int inLen) { int outSize = 0; if (firstOperation_ == true) { outSize += ciphertextHeaderBytes_.length; } outSize += contentCryptoHandler_.estimateOutputSize(inLen); if (cryptoAlgo_.getTrailingSignatureLength() > 0) { outSize += 2; // Length field in footer outSize += cryptoAlgo_.getTrailingSignatureLength(); } return outSize; } @Override public int estimatePartialOutputSize(int inLen) { int outSize = 0; if (firstOperation_ == true) { outSize += ciphertextHeaderBytes_.length; } outSize += contentCryptoHandler_.estimatePartialOutputSize(inLen); return outSize; } @Override public int estimateFinalOutputSize() { return estimateOutputSize(0); } /** * Return the encryption context. * * @return the key-value map containing encryption context. */ @Override public Map<String, String> getEncryptionContext() { return encryptionContext_; } @Override public CiphertextHeaders getHeaders() { return ciphertextHeaders_; } @Override public void setMaxInputLength(long size) { if (size < 0) { throw Utils.cannotBeNegative("Max input length"); } if (plaintextByteLimit_ == -1 || plaintextByteLimit_ > size) { plaintextByteLimit_ = size; } // check that we haven't already exceeded the limit checkPlaintextSizeLimit(0); } private void checkPlaintextSizeLimit(long additionalBytes) { if (plaintextByteLimit_ != -1 && plaintextBytes_ + additionalBytes > plaintextByteLimit_) { throw new IllegalStateException("Plaintext size exceeds max input size limit"); } } long getMaxInputLength() { return plaintextByteLimit_; } /** * Compute the MAC tag of the header bytes using the provided key, nonce, AAD, and crypto * algorithm identifier. * * @param nonce the nonce to use in computing the MAC tag. * @param aad the AAD to use in computing the MAC tag. * @return the bytes containing the computed MAC tag. */ private byte[] computeHeaderTag(final byte[] nonce, final byte[] aad) { final CipherHandler cipherHandler = new CipherHandler(encryptionKey_, Cipher.ENCRYPT_MODE, cryptoAlgo_); return cipherHandler.cipherData(nonce, aad, new byte[0], 0, 0); } private CiphertextHeaders signCiphertextHeaders(final CiphertextHeaders unsignedHeaders) { final byte[] headerFields = unsignedHeaders.serializeAuthenticatedFields(); final byte[] headerTag = computeHeaderTag(unsignedHeaders.getHeaderNonce(), headerFields); unsignedHeaders.setHeaderTag(headerTag); return unsignedHeaders; } @Override public List<? extends MasterKey<?>> getMasterKeys() { //noinspection unchecked return (List) masterKeys_; // This is unmodifiable } private void updateTrailingSignature(byte[] input, int offset, int len) { if (trailingDigest_ != null) { trailingDigest_.update(input, offset, len); } else if (trailingSig_ != null) { try { trailingSig_.update(input, offset, len); } catch (final SignatureException ex) { throw new AwsCryptoException(ex); } } } @Override public boolean isComplete() { return complete_; } }
5,481
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunction.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.apache.commons.lang3.Validate.isTrue; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.util.Arrays; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * HMAC-based Key Derivation Function. Adapted from Hkdf.java in aws-dynamodb-encryption-java * * @see <a href="http://tools.ietf.org/html/rfc5869">RFC 5869</a> */ public final class HmacKeyDerivationFunction { private static final byte[] EMPTY_ARRAY = new byte[0]; private final String algorithm; private final Provider provider; private SecretKey prk = null; /** * Returns an <code>HmacKeyDerivationFunction</code> object using the specified algorithm. * * @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the * <a href= * "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" > * Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information * about standard algorithm names. * @return the new <code>Hkdf</code> object * @throws NoSuchAlgorithmException if no Provider supports a MacSpi implementation for the * specified algorithm. */ public static HmacKeyDerivationFunction getInstance(final String algorithm) throws NoSuchAlgorithmException { // Constructed specifically to sanity-test arguments. Mac mac = Mac.getInstance(algorithm); return new HmacKeyDerivationFunction(algorithm, mac.getProvider()); } /** * Initializes this Hkdf with input keying material. A default salt of HashLen zeros will be used * (where HashLen is the length of the return value of the supplied algorithm). * * @param ikm the Input Keying Material */ public void init(final byte[] ikm) { init(ikm, null); } /** * Initializes this Hkdf with input keying material and a salt. If <code> * salt</code> is <code>null</code> or of length 0, then a default salt of HashLen zeros will be * used (where HashLen is the length of the return value of the supplied algorithm). * * @param salt the salt used for key extraction (optional) * @param ikm the Input Keying Material */ public void init(final byte[] ikm, final byte[] salt) { byte[] realSalt = (salt == null) ? EMPTY_ARRAY : salt.clone(); byte[] rawKeyMaterial = EMPTY_ARRAY; try { Mac extractionMac = Mac.getInstance(algorithm, provider); if (realSalt.length == 0) { realSalt = new byte[extractionMac.getMacLength()]; Arrays.fill(realSalt, (byte) 0); } extractionMac.init(new SecretKeySpec(realSalt, algorithm)); rawKeyMaterial = extractionMac.doFinal(ikm); this.prk = new SecretKeySpec(rawKeyMaterial, algorithm); } catch (GeneralSecurityException e) { // We've already checked all of the parameters so no exceptions // should be possible here. throw new RuntimeException("Unexpected exception", e); } finally { Arrays.fill(rawKeyMaterial, (byte) 0); // Zeroize temporary array } } private HmacKeyDerivationFunction(final String algorithm, final Provider provider) { isTrue( algorithm.startsWith("Hmac"), "Invalid algorithm " + algorithm + ". Hkdf may only be used with Hmac algorithms."); this.algorithm = algorithm; this.provider = provider; } /** * Returns a pseudorandom key of <code>length</code> bytes. * * @param info optional context and application specific information (can be a zero-length array). * @param length the length of the output key in bytes * @return a pseudorandom key of <code>length</code> bytes. * @throws IllegalStateException if this object has not been initialized */ public byte[] deriveKey(final byte[] info, final int length) throws IllegalStateException { isTrue(length >= 0, "Length must be a non-negative value."); assertInitialized(); final byte[] result = new byte[length]; Mac mac = createMac(); isTrue( length <= 255 * mac.getMacLength(), "Requested keys may not be longer than 255 times the underlying HMAC length."); byte[] t = EMPTY_ARRAY; try { int loc = 0; byte i = 1; while (loc < length) { mac.update(t); mac.update(info); mac.update(i); t = mac.doFinal(); for (int x = 0; x < t.length && loc < length; x++, loc++) { result[loc] = t[x]; } i++; } } finally { Arrays.fill(t, (byte) 0); // Zeroize temporary array } return result; } private Mac createMac() { try { Mac mac = Mac.getInstance(algorithm, provider); mac.init(prk); return mac; } catch (NoSuchAlgorithmException | InvalidKeyException ex) { // We've already validated that this algorithm/key is correct. throw new RuntimeException(ex); } } /** * Throws an <code>IllegalStateException</code> if this object has not been initialized. * * @throws IllegalStateException if this object has not been initialized */ private void assertInitialized() throws IllegalStateException { if (prk == null) { throw new IllegalStateException("Hkdf has not been initialized"); } } }
5,482
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/VersionInfo.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import java.io.IOException; import java.util.Properties; /** This class specifies the versioning system for the AWS KMS encryption client. */ public class VersionInfo { public static final String USER_AGENT_PREFIX = "AwsCrypto/"; public static final String UNKNOWN_VERSION = "unknown"; /* * Loads the version of the library */ public static String loadUserAgent() { return USER_AGENT_PREFIX + versionNumber(); } /** * This returns the API name compatible with the AWS SDK v2 * * @return the name of the library with a tag indicating intended for AWS SDK v2 */ public static String apiName() { return USER_AGENT_PREFIX.substring(0, USER_AGENT_PREFIX.length() - 1); } /* * String representation of the library version e.g. 2.3.3 */ public static String versionNumber() { try { final Properties properties = new Properties(); final ClassLoader loader = VersionInfo.class.getClassLoader(); properties.load(loader.getResourceAsStream("project.properties")); return properties.getProperty("version"); } catch (final IOException ex) { return UNKNOWN_VERSION; } } }
5,483
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/DecryptionHandler.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.model.CiphertextFooters; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.CiphertextType; import com.amazonaws.encryptionsdk.model.ContentType; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; /** * This class implements the CryptoHandler interface by providing methods for the decryption of * ciphertext produced by the methods in {@link EncryptionHandler}. * * <p>This class reads and parses the values in the ciphertext headers and delegates the decryption * of the ciphertext to the {@link BlockDecryptionHandler} or {@link FrameDecryptionHandler} based * on the content type parsed in the ciphertext headers. */ public class DecryptionHandler<K extends MasterKey<K>> implements MessageCryptoHandler { private final CryptoMaterialsManager materialsManager_; private final CommitmentPolicy commitmentPolicy_; /** * The maximum number of encrypted data keys to parse, if positive. If zero, do not limit EDKs. */ private final int maxEncryptedDataKeys_; private final SignaturePolicy signaturePolicy_; private final CiphertextHeaders ciphertextHeaders_; private final CiphertextFooters ciphertextFooters_; private boolean ciphertextHeadersParsed_; private CryptoHandler contentCryptoHandler_; private DataKey<K> dataKey_; private SecretKey decryptionKey_; private CryptoAlgorithm cryptoAlgo_; private Signature trailingSig_; private Map<String, String> encryptionContext_ = null; private byte[] unparsedBytes_ = new byte[0]; private boolean complete_ = false; private long ciphertextSizeBound_ = -1; private long ciphertextBytesSupplied_ = 0; // These ctors are private to ensure type safety - we must ensure construction using a CMM results // in a // DecryptionHandler<?>, not a DecryptionHandler<SomeConcreteType>, since the // CryptoMaterialsManager is not itself // genericized. private DecryptionHandler( final CryptoMaterialsManager materialsManager, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) { Utils.assertNonNull(materialsManager, "materialsManager"); Utils.assertNonNull(commitmentPolicy, "commitmentPolicy"); Utils.assertNonNull(signaturePolicy, "signaturePolicy"); this.materialsManager_ = materialsManager; this.commitmentPolicy_ = commitmentPolicy; this.maxEncryptedDataKeys_ = maxEncryptedDataKeys; this.signaturePolicy_ = signaturePolicy; ciphertextHeaders_ = new CiphertextHeaders(); ciphertextFooters_ = new CiphertextFooters(); } private DecryptionHandler( final CryptoMaterialsManager materialsManager, final CiphertextHeaders headers, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { Utils.assertNonNull(materialsManager, "materialsManager"); Utils.assertNonNull(commitmentPolicy, "commitmentPolicy"); Utils.assertNonNull(signaturePolicy, "signaturePolicy"); materialsManager_ = materialsManager; ciphertextHeaders_ = headers; commitmentPolicy_ = commitmentPolicy; signaturePolicy_ = signaturePolicy; maxEncryptedDataKeys_ = maxEncryptedDataKeys; ciphertextFooters_ = new CiphertextFooters(); if (headers instanceof ParsedCiphertext) { ciphertextBytesSupplied_ = ((ParsedCiphertext) headers).getOffset(); } else { // This is a little more expensive, hence the public create(...) methods // that take a CiphertextHeaders instead of a ParsedCiphertext are // deprecated. ciphertextBytesSupplied_ = headers.toByteArray().length; } readHeaderFields(headers); updateTrailingSignature(headers); } /** * Create a decryption handler using the provided master key. * * <p>Note the methods in the provided master key are used in decrypting the encrypted data key * parsed from the ciphertext headers. * * @param customerMasterKeyProvider the master key provider to use in picking a master key from * the key blobs encoded in the provided ciphertext. * @param commitmentPolicy The commitment policy to enforce during decryption * @param signaturePolicy The signature policy to enforce during decryption * @param maxEncryptedDataKeys The maximum number of encrypted data keys to unwrap during * decryption; zero indicates no maximum * @throws AwsCryptoException if the master key is null. */ @SuppressWarnings("unchecked") public static <K extends MasterKey<K>> DecryptionHandler<K> create( final MasterKeyProvider<K> customerMasterKeyProvider, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { Utils.assertNonNull(customerMasterKeyProvider, "customerMasterKeyProvider"); return (DecryptionHandler<K>) create( new DefaultCryptoMaterialsManager(customerMasterKeyProvider), commitmentPolicy, signaturePolicy, maxEncryptedDataKeys); } /** * Create a decryption handler using the provided master key and already parsed {@code headers}. * * <p>Note the methods in the provided master key are used in decrypting the encrypted data key * parsed from the ciphertext headers. * * @param customerMasterKeyProvider the master key provider to use in picking a master key from * the key blobs encoded in the provided ciphertext. * @param headers already parsed headers which will not be passed into {@link * #processBytes(byte[], int, int, byte[], int)} * @param commitmentPolicy The commitment policy to enforce during decryption * @param signaturePolicy The signature policy to enforce during decryption * @param maxEncryptedDataKeys The maximum number of encrypted data keys to unwrap during * decryption; zero indicates no maximum * @throws AwsCryptoException if the master key is null. * @deprecated This version may have to recalculate the number of bytes already parsed, which adds * a performance penalty. Use {@link #create(CryptoMaterialsManager, ParsedCiphertext, * CommitmentPolicy, SignaturePolicy, int)} instead, which makes the parsed byte count * directly available instead. */ @SuppressWarnings("unchecked") @Deprecated public static <K extends MasterKey<K>> DecryptionHandler<K> create( final MasterKeyProvider<K> customerMasterKeyProvider, final CiphertextHeaders headers, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { Utils.assertNonNull(customerMasterKeyProvider, "customerMasterKeyProvider"); return (DecryptionHandler<K>) create( new DefaultCryptoMaterialsManager(customerMasterKeyProvider), headers, commitmentPolicy, signaturePolicy, maxEncryptedDataKeys); } /** * Create a decryption handler using the provided master key and already parsed {@code headers}. * * <p>Note the methods in the provided master key are used in decrypting the encrypted data key * parsed from the ciphertext headers. * * @param customerMasterKeyProvider the master key provider to use in picking a master key from * the key blobs encoded in the provided ciphertext. * @param headers already parsed headers which will not be passed into {@link * #processBytes(byte[], int, int, byte[], int)} * @param commitmentPolicy The commitment policy to enforce during decryption * @param signaturePolicy The signature policy to enforce during decryption * @param maxEncryptedDataKeys The maximum number of encrypted data keys to unwrap during * decryption; zero indicates no maximum * @throws AwsCryptoException if the master key is null. */ @SuppressWarnings("unchecked") public static <K extends MasterKey<K>> DecryptionHandler<K> create( final MasterKeyProvider<K> customerMasterKeyProvider, final ParsedCiphertext headers, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { Utils.assertNonNull(customerMasterKeyProvider, "customerMasterKeyProvider"); return (DecryptionHandler<K>) create( new DefaultCryptoMaterialsManager(customerMasterKeyProvider), headers, commitmentPolicy, signaturePolicy, maxEncryptedDataKeys); } /** * Create a decryption handler using the provided materials manager. * * <p>Note the methods in the provided materials manager are used in decrypting the encrypted data * key parsed from the ciphertext headers. * * @param materialsManager the materials manager to use in decrypting the data key from the key * blobs encoded in the provided ciphertext. * @param commitmentPolicy The commitment policy to enforce during decryption * @param signaturePolicy The signature policy to enforce during decryption * @param maxEncryptedDataKeys The maximum number of encrypted data keys to unwrap during * decryption; zero indicates no maximum * @throws AwsCryptoException if the master key is null. */ public static DecryptionHandler<?> create( final CryptoMaterialsManager materialsManager, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { return new DecryptionHandler( materialsManager, commitmentPolicy, signaturePolicy, maxEncryptedDataKeys); } /** * Create a decryption handler using the provided materials manager and already parsed {@code * headers}. * * <p>Note the methods in the provided materials manager are used in decrypting the encrypted data * key parsed from the ciphertext headers. * * @param materialsManager the materials manager to use in decrypting the data key from the key * blobs encoded in the provided ciphertext. * @param headers already parsed headers which will not be passed into {@link * #processBytes(byte[], int, int, byte[], int)} * @param commitmentPolicy The commitment policy to enforce during decryption * @param signaturePolicy The signature policy to enforce during decryption * @param maxEncryptedDataKeys The maximum number of encrypted data keys to unwrap during * decryption; zero indicates no maximum * @throws AwsCryptoException if the master key is null. * @deprecated This version may have to recalculate the number of bytes already parsed, which adds * a performance penalty. Use {@link #create(CryptoMaterialsManager, ParsedCiphertext, * CommitmentPolicy, SignaturePolicy, int)} instead, which makes the parsed byte count * directly available instead. */ @Deprecated public static DecryptionHandler<?> create( final CryptoMaterialsManager materialsManager, final CiphertextHeaders headers, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { return new DecryptionHandler( materialsManager, headers, commitmentPolicy, signaturePolicy, maxEncryptedDataKeys); } /** * Create a decryption handler using the provided materials manager and already parsed {@code * headers}. * * <p>Note the methods in the provided materials manager are used in decrypting the encrypted data * key parsed from the ciphertext headers. * * @param materialsManager the materials manager to use in decrypting the data key from the key * blobs encoded in the provided ciphertext. * @param headers already parsed headers which will not be passed into {@link * #processBytes(byte[], int, int, byte[], int)} * @param commitmentPolicy The commitment policy to enforce during decryption * @param signaturePolicy The signature policy to enforce during decryption * @param maxEncryptedDataKeys The maximum number of encrypted data keys to unwrap during * decryption; zero indicates no maximum * @throws AwsCryptoException if the master key is null. */ public static DecryptionHandler<?> create( final CryptoMaterialsManager materialsManager, final ParsedCiphertext headers, final CommitmentPolicy commitmentPolicy, final SignaturePolicy signaturePolicy, final int maxEncryptedDataKeys) throws AwsCryptoException { return new DecryptionHandler( materialsManager, headers, commitmentPolicy, signaturePolicy, maxEncryptedDataKeys); } /** * Decrypt the ciphertext bytes provided in {@code in} and copy the plaintext bytes to {@code * out}. * * <p>This method consumes and parses the ciphertext headers. The decryption of the actual content * is delegated to {@link BlockDecryptionHandler} or {@link FrameDecryptionHandler} based on the * content type parsed in the ciphertext header. * * @param in the input byte array. * @param off the offset into the in array where the data to be decrypted starts. * @param len the number of bytes to be decrypted. * @param out the output buffer the decrypted plaintext bytes go into. * @param outOff the offset into the output byte array the decrypted data starts at. * @return the number of bytes written to {@code out} and processed. * @throws BadCiphertextException if the ciphertext header contains invalid entries or if the * header integrity check fails. * @throws AwsCryptoException if any of the offset or length arguments are negative or if the * total bytes to decrypt exceeds the maximum allowed value. */ @Override public ProcessingSummary processBytes( final byte[] in, final int off, final int len, final byte[] out, final int outOff) throws BadCiphertextException, AwsCryptoException { // We should arguably check if we are already complete_ here as other handlers // like FrameDecryptionHandler and BlockDecryptionHandler do. // However, adding that now could potentially break customers who have extra trailing // bytes in their decryption streams. // The handlers are also inconsistent in general with this check. Even those that // do raise an exception here if already complete will not complain if // a single call to processBytes() completes the message and provides extra trailing bytes: // in that case they will just indicate that they didn't process the extra bytes instead. if (len < 0 || off < 0) { throw new AwsCryptoException( String.format("Invalid values for input offset: %d and length: %d", off, len)); } if (in.length == 0 || len == 0) { return ProcessingSummary.ZERO; } final long totalBytesToParse = unparsedBytes_.length + (long) len; // check for integer overflow if (totalBytesToParse > Integer.MAX_VALUE) { throw new AwsCryptoException( "Size of the total bytes to parse and decrypt exceeded allowed maximum:" + Integer.MAX_VALUE); } checkSizeBound(len); ciphertextBytesSupplied_ += len; final byte[] bytesToParse = new byte[(int) totalBytesToParse]; final int leftoverBytes = unparsedBytes_.length; // If there were previously unparsed bytes, add them as the first // set of bytes to be parsed in this call. System.arraycopy(unparsedBytes_, 0, bytesToParse, 0, unparsedBytes_.length); System.arraycopy(in, off, bytesToParse, unparsedBytes_.length, len); int totalParsedBytes = 0; if (!ciphertextHeadersParsed_) { totalParsedBytes += ciphertextHeaders_.deserialize(bytesToParse, 0, maxEncryptedDataKeys_); // When ciphertext headers are complete, we have the data // key and cipher mode to initialize the underlying cipher if (ciphertextHeaders_.isComplete() == true) { readHeaderFields(ciphertextHeaders_); updateTrailingSignature(ciphertextHeaders_); // reset unparsed bytes as parsing of ciphertext headers is // complete. unparsedBytes_ = new byte[0]; } else { // If there aren't enough bytes to parse ciphertext // headers, we don't have anymore bytes to continue parsing. // But first copy the leftover bytes to unparsed bytes. unparsedBytes_ = Arrays.copyOfRange(bytesToParse, totalParsedBytes, bytesToParse.length); return new ProcessingSummary(0, len); } } int actualOutLen = 0; if (!contentCryptoHandler_.isComplete()) { // if there are bytes to parse further, pass it off to underlying // content cryptohandler. if ((bytesToParse.length - totalParsedBytes) > 0) { final ProcessingSummary contentResult = contentCryptoHandler_.processBytes( bytesToParse, totalParsedBytes, bytesToParse.length - totalParsedBytes, out, outOff); updateTrailingSignature(bytesToParse, totalParsedBytes, contentResult.getBytesProcessed()); actualOutLen = contentResult.getBytesWritten(); totalParsedBytes += contentResult.getBytesProcessed(); } if (contentCryptoHandler_.isComplete()) { actualOutLen += contentCryptoHandler_.doFinal(out, outOff + actualOutLen); } } if (contentCryptoHandler_.isComplete()) { // If the crypto algorithm contains trailing signature, we will need to verify // the footer of the message. if (cryptoAlgo_.getTrailingSignatureLength() > 0) { totalParsedBytes += ciphertextFooters_.deserialize(bytesToParse, totalParsedBytes); if (ciphertextFooters_.isComplete()) { // reset unparsed bytes as parsing of the ciphertext footer is // complete. // This isn't strictly necessary since processing any further data // should be an error. unparsedBytes_ = new byte[0]; try { if (!trailingSig_.verify(ciphertextFooters_.getMAuth())) { throw new BadCiphertextException("Bad trailing signature"); } } catch (final SignatureException ex) { throw new BadCiphertextException("Bad trailing signature", ex); } complete_ = true; } else { // If there aren't enough bytes to parse the ciphertext // footer, we don't have any more bytes to continue parsing. // But first copy the leftover bytes to unparsed bytes. unparsedBytes_ = Arrays.copyOfRange(bytesToParse, totalParsedBytes, bytesToParse.length); return new ProcessingSummary(actualOutLen, len); } } else { complete_ = true; } } return new ProcessingSummary(actualOutLen, totalParsedBytes - leftoverBytes); } /** * Finish processing of the bytes. * * @param out space for any resulting output data. * @param outOff offset into {@code out} to start copying the data at. * @return number of bytes written into {@code out}. * @throws BadCiphertextException if the bytes do not decrypt correctly. */ @Override public int doFinal(final byte[] out, final int outOff) throws BadCiphertextException { // This is an unfortunate special case we have to support for backwards-compatibility. if (ciphertextBytesSupplied_ == 0) { return 0; } // check if cryptohandler for content has been created. There are cases // when it might not have been created such as when doFinal() is called // before the ciphertext headers are fully received and parsed. if (contentCryptoHandler_ == null) { throw new BadCiphertextException("Unable to process entire ciphertext."); } else { int result = contentCryptoHandler_.doFinal(out, outOff); if (!complete_) { throw new BadCiphertextException("Unable to process entire ciphertext."); } return result; } } /** * Return the size of the output buffer required for a <code>processBytes</code> plus a <code> * doFinal</code> with an input of inLen bytes. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and doFinal with input of size * {@code inLen} bytes. */ @Override public int estimateOutputSize(final int inLen) { if (contentCryptoHandler_ != null) { return contentCryptoHandler_.estimateOutputSize(inLen); } else { return (inLen > 0) ? inLen : 0; } } @Override public int estimatePartialOutputSize(int inLen) { if (contentCryptoHandler_ != null) { return contentCryptoHandler_.estimatePartialOutputSize(inLen); } else { return (inLen > 0) ? inLen : 0; } } @Override public int estimateFinalOutputSize() { if (contentCryptoHandler_ != null) { return contentCryptoHandler_.estimateFinalOutputSize(); } else { return 0; } } /** * Return the encryption context. This value is parsed from the ciphertext. * * @return the key-value map containing the encryption client. */ @Override public Map<String, String> getEncryptionContext() { return encryptionContext_; } private void checkSizeBound(long additionalBytes) { if (ciphertextSizeBound_ != -1 && ciphertextBytesSupplied_ + additionalBytes > ciphertextSizeBound_) { throw new IllegalStateException("Ciphertext size exceeds size bound"); } } @Override public void setMaxInputLength(long size) { if (size < 0) { throw Utils.cannotBeNegative("Max input length"); } if (ciphertextSizeBound_ == -1 || ciphertextSizeBound_ > size) { ciphertextSizeBound_ = size; } // check that we haven't already exceeded the limit checkSizeBound(0); } long getMaxInputLength() { return ciphertextSizeBound_; } /** * Check integrity of the header bytes by processing the parsed MAC tag in the headers through the * cipher. * * @param ciphertextHeaders the ciphertext headers object whose integrity needs to be checked. * @return true if the integrity of the header is intact; false otherwise. */ private void verifyHeaderIntegrity(final CiphertextHeaders ciphertextHeaders) throws BadCiphertextException { final CipherHandler cipherHandler = new CipherHandler(decryptionKey_, Cipher.DECRYPT_MODE, cryptoAlgo_); try { final byte[] headerTag = ciphertextHeaders.getHeaderTag(); cipherHandler.cipherData( ciphertextHeaders.getHeaderNonce(), ciphertextHeaders.serializeAuthenticatedFields(), headerTag, 0, headerTag.length); } catch (BadCiphertextException e) { throw new BadCiphertextException("Header integrity check failed.", e); } } /** * Read the fields in the ciphertext headers to populate the corresponding instance variables used * during decryption. * * @param ciphertextHeaders the ciphertext headers object to read. */ @SuppressWarnings("unchecked") private void readHeaderFields(final CiphertextHeaders ciphertextHeaders) { cryptoAlgo_ = ciphertextHeaders.getCryptoAlgoId(); final CiphertextType ciphertextType = ciphertextHeaders.getType(); if (ciphertextType != CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA) { throw new BadCiphertextException("Invalid type in ciphertext."); } final byte[] messageId = ciphertextHeaders.getMessageId(); if (!commitmentPolicy_.algorithmAllowedForDecrypt(cryptoAlgo_)) { throw new AwsCryptoException( "Configuration conflict. " + "Cannot decrypt message with ID " + messageId + " due to CommitmentPolicy " + commitmentPolicy_ + " requiring only committed messages. Algorithm ID was " + cryptoAlgo_ + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } if (maxEncryptedDataKeys_ > 0 && ciphertextHeaders_.getEncryptedKeyBlobCount() > maxEncryptedDataKeys_) { throw new AwsCryptoException("Ciphertext encrypted data keys exceed maxEncryptedDataKeys"); } if (!signaturePolicy_.algorithmAllowedForDecrypt(cryptoAlgo_)) { throw new AwsCryptoException( "Configuration conflict. " + "Cannot decrypt message with ID " + messageId + " because AwsCrypto.createUnsignedMessageDecryptingStream() " + " accepts only unsigned messages. Algorithm ID was " + cryptoAlgo_ + "."); } encryptionContext_ = ciphertextHeaders.getEncryptionContextMap(); DecryptionMaterialsRequest request = DecryptionMaterialsRequest.newBuilder() .setAlgorithm(cryptoAlgo_) .setEncryptionContext(encryptionContext_) .setEncryptedDataKeys(ciphertextHeaders.getEncryptedKeyBlobs()) .build(); DecryptionMaterials result = materialsManager_.decryptMaterials(request); //noinspection unchecked dataKey_ = (DataKey<K>) result.getDataKey(); PublicKey trailingPublicKey = result.getTrailingSignatureKey(); try { decryptionKey_ = cryptoAlgo_.getEncryptionKeyFromDataKey(dataKey_.getKey(), ciphertextHeaders); } catch (final InvalidKeyException ex) { throw new AwsCryptoException(ex); } if (cryptoAlgo_.getTrailingSignatureLength() > 0) { Utils.assertNonNull(trailingPublicKey, "trailing public key"); TrailingSignatureAlgorithm trailingSignatureAlgorithm = TrailingSignatureAlgorithm.forCryptoAlgorithm(cryptoAlgo_); try { trailingSig_ = Signature.getInstance(trailingSignatureAlgorithm.getHashAndSignAlgorithm()); trailingSig_.initVerify(trailingPublicKey); } catch (GeneralSecurityException e) { throw new AwsCryptoException(e); } } else { if (trailingPublicKey != null) { throw new AwsCryptoException("Unexpected trailing signature key in context"); } trailingSig_ = null; } final ContentType contentType = ciphertextHeaders.getContentType(); final short nonceLen = ciphertextHeaders.getNonceLength(); final int frameLen = ciphertextHeaders.getFrameLength(); verifyHeaderIntegrity(ciphertextHeaders); switch (contentType) { case FRAME: contentCryptoHandler_ = new FrameDecryptionHandler( decryptionKey_, (byte) nonceLen, cryptoAlgo_, messageId, frameLen); break; case SINGLEBLOCK: contentCryptoHandler_ = new BlockDecryptionHandler(decryptionKey_, (byte) nonceLen, cryptoAlgo_, messageId); break; default: // should never get here because an invalid content type is // detected when parsing. break; } ciphertextHeadersParsed_ = true; } private void updateTrailingSignature(final CiphertextHeaders headers) { if (trailingSig_ != null) { final byte[] reserializedHeaders = headers.toByteArray(); updateTrailingSignature(reserializedHeaders, 0, reserializedHeaders.length); } } private void updateTrailingSignature(byte[] input, int offset, int len) { if (trailingSig_ != null) { try { trailingSig_.update(input, offset, len); } catch (final SignatureException ex) { throw new AwsCryptoException(ex); } } } @Override public CiphertextHeaders getHeaders() { return ciphertextHeaders_; } @Override public List<K> getMasterKeys() { return Collections.singletonList(dataKey_.getMasterKey()); } @Override public boolean isComplete() { return complete_; } }
5,484
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/SignaturePolicy.java
package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; public enum SignaturePolicy { AllowEncryptAllowDecrypt { @Override public boolean algorithmAllowedForDecrypt(CryptoAlgorithm algorithm) { return true; } }, AllowEncryptForbidDecrypt { @Override public boolean algorithmAllowedForDecrypt(CryptoAlgorithm algorithm) { return algorithm.getTrailingSignatureLength() == 0; } }; public abstract boolean algorithmAllowedForDecrypt(CryptoAlgorithm algorithm); }
5,485
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/FrameDecryptionHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.model.CipherFrameHeaders; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; /** * The frame decryption handler is a subclass of the decryption handler and thereby provides an * implementation of the Cryptography handler. * * <p>It implements methods for decrypting content that was encrypted and stored in frames. */ class FrameDecryptionHandler implements CryptoHandler { private final SecretKey decryptionKey_; private final CryptoAlgorithm cryptoAlgo_; private final CipherHandler cipherHandler_; private final byte[] messageId_; private final short nonceLen_; private CipherFrameHeaders currentFrameHeaders_; private final int frameSize_; private long frameNumber_ = 1; boolean complete_ = false; private byte[] unparsedBytes_ = new byte[0]; /** * Construct a decryption handler for decrypting bytes stored in frames. * * @param customerMasterKey the master key to use when unwrapping the data key encoded in the * ciphertext. */ public FrameDecryptionHandler( final SecretKey decryptionKey, final short nonceLen, final CryptoAlgorithm cryptoAlgo, final byte[] messageId, final int frameLen) { decryptionKey_ = decryptionKey; nonceLen_ = nonceLen; cryptoAlgo_ = cryptoAlgo; messageId_ = messageId; frameSize_ = frameLen; cipherHandler_ = new CipherHandler(decryptionKey_, Cipher.DECRYPT_MODE, cryptoAlgo_); } /** * Decrypt the ciphertext bytes containing content encrypted using frames and put the plaintext * bytes into out. * * <p>It decrypts by performing the following operations: * * <ol> * <li>parse the ciphertext headers * <li>parse the ciphertext until encrypted content in a frame is available * <li>decrypt the encrypted content * <li>return decrypted bytes as output * </ol> * * @param in the input byte array. * @param off the offset into the in array where the data to be decrypted starts. * @param len the number of bytes to be decrypted. * @param out the output buffer the decrypted plaintext bytes go into. * @param outOff the offset into the output byte array the decrypted data starts at. * @return the number of bytes written to out and processed * @throws BadCiphertextException if frame number is invalid/out-of-order or if the bytes do not * decrypt correctly. * @throws AwsCryptoException if the content type found in the headers is not of frame type. */ @Override public ProcessingSummary processBytes( final byte[] in, final int off, final int len, final byte[] out, final int outOff) throws BadCiphertextException, AwsCryptoException { if (complete_) { throw new AwsCryptoException("Ciphertext has already been processed."); } final long totalBytesToParse = unparsedBytes_.length + (long) len; if (totalBytesToParse > Integer.MAX_VALUE) { throw new AwsCryptoException( "Integer overflow of the total bytes to parse and decrypt occured."); } final byte[] bytesToParse = new byte[(int) totalBytesToParse]; // If there were previously unparsed bytes, add them as the first // set of bytes to be parsed in this call. System.arraycopy(unparsedBytes_, 0, bytesToParse, 0, unparsedBytes_.length); System.arraycopy(in, off, bytesToParse, unparsedBytes_.length, len); int actualOutLen = 0; int totalParsedBytes = 0; // Parse available bytes. Stop parsing when there aren't enough // bytes to complete parsing: // - the ciphertext headers // - the cipher frame while (!complete_ && totalParsedBytes < bytesToParse.length) { if (currentFrameHeaders_ == null) { currentFrameHeaders_ = new CipherFrameHeaders(); currentFrameHeaders_.setNonceLength(nonceLen_); if (frameSize_ == 0) { // if frame size in ciphertext headers is 0, the frame size // will need to be parsed in individual frame headers. currentFrameHeaders_.includeFrameSize(true); } } totalParsedBytes += currentFrameHeaders_.deserialize(bytesToParse, totalParsedBytes); // if we have all frame fields, process the encrypted content. if (currentFrameHeaders_.isComplete() == true) { int protectedContentLen = -1; if (currentFrameHeaders_.isFinalFrame()) { protectedContentLen = currentFrameHeaders_.getFrameContentLength(); // The final frame should not be able to exceed the frameLength if (frameSize_ > 0 && protectedContentLen > frameSize_) { throw new BadCiphertextException("Final frame length exceeds frame length."); } } else { protectedContentLen = frameSize_; } // include the tag which is added by the underlying cipher. protectedContentLen += cryptoAlgo_.getTagLen(); if ((bytesToParse.length - totalParsedBytes) < protectedContentLen) { // if we don't have all of the encrypted bytes, break // until they become available. break; } final byte[] bytesToDecrypt_ = Arrays.copyOfRange( bytesToParse, totalParsedBytes, totalParsedBytes + protectedContentLen); totalParsedBytes += protectedContentLen; if (frameNumber_ == Constants.MAX_FRAME_NUMBER) { throw new BadCiphertextException("Frame number exceeds the maximum allowed value."); } final byte[] decryptedBytes = decryptContent(bytesToDecrypt_, 0, bytesToDecrypt_.length); System.arraycopy(decryptedBytes, 0, out, (outOff + actualOutLen), decryptedBytes.length); actualOutLen += decryptedBytes.length; frameNumber_++; complete_ = currentFrameHeaders_.isFinalFrame(); // reset frame headers as we are done processing current frame. currentFrameHeaders_ = null; } else { // if there aren't enough bytes to parse cipher frame, // we can't continue parsing. break; } } if (!complete_) { // buffer remaining bytes for parsing in the next round. unparsedBytes_ = Arrays.copyOfRange(bytesToParse, totalParsedBytes, bytesToParse.length); return new ProcessingSummary(actualOutLen, len); } else { final ProcessingSummary result = new ProcessingSummary(actualOutLen, totalParsedBytes - unparsedBytes_.length); unparsedBytes_ = new byte[0]; return result; } } /** * Finish processing of the bytes. This function does nothing since the final frame will be * processed and decrypted in processBytes(). * * @param out space for any resulting output data. * @param outOff offset into out to start copying the data at. * @return 0 */ @Override public int doFinal(final byte[] out, final int outOff) { if (!complete_) { throw new BadCiphertextException("Unable to process entire ciphertext."); } return 0; } /** * Return the size of the output buffer required for a processBytes plus a doFinal with an input * of inLen bytes. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and doFinal with len bytes of * input. */ @Override public int estimateOutputSize(final int inLen) { int outSize = 0; final int totalBytesToDecrypt = unparsedBytes_.length + inLen; if (totalBytesToDecrypt > 0) { int frames = totalBytesToDecrypt / frameSize_; frames += 1; // add one for final frame which might be < frame size. outSize += (frameSize_ * frames); } return outSize; } @Override public int estimatePartialOutputSize(int inLen) { return estimateOutputSize(inLen); } @Override public int estimateFinalOutputSize() { return 0; } /** * Returns the plaintext bytes of the encrypted content. * * @param input the input bytes containing the content * @param off the offset into the input array where the data to be decrypted starts. * @param len the number of bytes to be decrypted. * @return the plaintext bytes of the encrypted content. * @throws BadCiphertextException if the bytes do not decrypt correctly. */ private byte[] decryptContent(final byte[] input, final int off, final int len) throws BadCiphertextException { final byte[] nonce = currentFrameHeaders_.getNonce(); byte[] contentAad = null; if (currentFrameHeaders_.isFinalFrame() == true) { contentAad = Utils.generateContentAad( messageId_, Constants.FINAL_FRAME_STRING_ID, (int) frameNumber_, currentFrameHeaders_.getFrameContentLength()); } else { contentAad = Utils.generateContentAad( messageId_, Constants.FRAME_STRING_ID, (int) frameNumber_, frameSize_); } return cipherHandler_.cipherData(nonce, contentAad, input, off, len); } @Override public boolean isComplete() { return complete_; } }
5,486
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/AesGcmJceKeyCipher.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.Key; import java.util.Map; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; /** A JceKeyCipher based on the Advanced Encryption Standard in Galois/Counter Mode. */ class AesGcmJceKeyCipher extends JceKeyCipher { private static final int NONCE_LENGTH = 12; private static final int TAG_LENGTH = 128; private static final String TRANSFORMATION = "AES/GCM/NoPadding"; private static final int SPEC_LENGTH = Integer.BYTES + Integer.BYTES + NONCE_LENGTH; AesGcmJceKeyCipher(SecretKey key) { super(key, key); } private static byte[] specToBytes(final GCMParameterSpec spec) { final byte[] nonce = spec.getIV(); final byte[] result = new byte[SPEC_LENGTH]; final ByteBuffer buffer = ByteBuffer.wrap(result); buffer.putInt(spec.getTLen()); buffer.putInt(nonce.length); buffer.put(nonce); return result; } private static GCMParameterSpec bytesToSpec(final byte[] data, final int offset) throws InvalidKeyException { if (data.length - offset != SPEC_LENGTH) { throw new InvalidKeyException("Algorithm specification was an invalid data size"); } final ByteBuffer buffer = ByteBuffer.wrap(data, offset, SPEC_LENGTH); final int tagLen = buffer.getInt(); final int nonceLen = buffer.getInt(); if (tagLen != TAG_LENGTH) { throw new InvalidKeyException( String.format("Authentication tag length must be %s", TAG_LENGTH)); } if (nonceLen != NONCE_LENGTH) { throw new InvalidKeyException( String.format("Initialization vector (IV) length must be %s", NONCE_LENGTH)); } final byte[] nonce = new byte[nonceLen]; buffer.get(nonce); return new GCMParameterSpec(tagLen, nonce); } @Override WrappingData buildWrappingCipher(final Key key, final Map<String, String> encryptionContext) throws GeneralSecurityException { final byte[] nonce = new byte[NONCE_LENGTH]; Utils.getSecureRandom().nextBytes(nonce); final GCMParameterSpec spec = new GCMParameterSpec(TAG_LENGTH, nonce); final Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, key, spec); final byte[] aad = EncryptionContextSerializer.serialize(encryptionContext); cipher.updateAAD(aad); return new WrappingData(cipher, specToBytes(spec)); } @Override Cipher buildUnwrappingCipher( final Key key, final byte[] extraInfo, final int offset, final Map<String, String> encryptionContext) throws GeneralSecurityException { final GCMParameterSpec spec = bytesToSpec(extraInfo, offset); final Cipher cipher = Cipher.getInstance(TRANSFORMATION); cipher.init(Cipher.DECRYPT_MODE, key, spec); final byte[] aad = EncryptionContextSerializer.serialize(encryptionContext); cipher.updateAAD(aad); return cipher; } }
5,487
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/CryptoHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; /** * This interface defines the contract for the implementation of encryption and decryption handlers * in this library. * * <p>The implementations of this interface provided in this package currently process bytes in a * single block mode (where all input data is processed in entirety, or in a framing mode (where * data is processed incrementally in chunks). */ public interface CryptoHandler { /** * Process a block of bytes from {@code in} putting the result into {@code out}. * * @param in the input byte array. * @param inOff the offset into the {@code in} array where the data to be processed starts. * @param inLen the number of bytes to be processed. * @param out the output buffer the processed bytes go into. * @param outOff the offset into the output byte array the processed data starts at. * @return the number of bytes written to {@code out} and the number of bytes parsed. */ ProcessingSummary processBytes( final byte[] in, final int inOff, final int inLen, byte[] out, final int outOff); /** * Finish processing of the bytes. * * @param out the output buffer for copying any remaining output data. * @param outOff offset into {@code out} to start copying the output data. * @return number of bytes written into {@code out}. */ int doFinal(final byte[] out, final int outOff); /** * Return the size of the output buffer required for a {@link #processBytes(byte[], int, int, * byte[], int)} plus a {@link #doFinal(byte[], int)} call with an input of {@code inLen} bytes. * * <p>Note this method is allowed to return an estimation of the output size that is * <i>greater</i> than the actual size of the output. Returning an estimate that is lesser than * the actual size of the output will result in underflow exceptions. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and {@link #doFinal(byte[], * int)} with an input of size {@code inLen} bytes. */ int estimateOutputSize(final int inLen); /** * Return the size of the output buffer required for a call to {@link #processBytes(byte[], int, * int, byte[], int)}. * * <p>Note this method is allowed to return an estimation of the output size that is * <i>greater</i> than the actual size of the output. Returning an estimate that is lesser than * the actual size of the output will result in underflow exceptions. * * @param inLen the length of the input. * @return the space required to accommodate a call to {@link #processBytes(byte[], int, int, * byte[], int)} with an input of size {@code inLen} bytes. */ int estimatePartialOutputSize(final int inLen); /** * Return the size of the output buffer required for a call to {@link #doFinal(byte[], int)}. * * <p>Note this method is allowed to return an estimation of the output size that is * <i>greater</i> than the actual size of the output. Returning an estimate that is lesser than * the actual size of the output will result in underflow exceptions. * * @return the space required to accomodate a call to {@link #doFinal(byte[], int)} */ int estimateFinalOutputSize(); /** * For decrypt and parsing flows returns {@code true} when this has handled as many bytes as it * can. This usually means that it has reached the end of an object, file, or other delimited * stream. */ boolean isComplete(); }
5,488
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/LazyMessageCryptoHandler.java
package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import java.util.List; import java.util.Map; import java.util.function.Function; import javax.annotation.concurrent.NotThreadSafe; /** * A {@link MessageCryptoHandler} that delegates to another MessageCryptoHandler, which is created * at the last possible moment. Typically, this is used in order to defer the creation of the data * key (and associated request to the {@link com.amazonaws.encryptionsdk.CryptoMaterialsManager} * until the max message size is known. */ @NotThreadSafe public class LazyMessageCryptoHandler implements MessageCryptoHandler { private Function<LateBoundInfo, MessageCryptoHandler> delegateFactory; private MessageCryptoHandler delegate; private long maxInputSize = -1; public static final class LateBoundInfo { private final long maxInputSize; private LateBoundInfo(long maxInputSize) { this.maxInputSize = maxInputSize; } public long getMaxInputSize() { return maxInputSize; } } public LazyMessageCryptoHandler(Function<LateBoundInfo, MessageCryptoHandler> delegateFactory) { this.delegateFactory = delegateFactory; this.delegate = null; } private MessageCryptoHandler getDelegate() { if (delegate == null) { delegate = delegateFactory.apply(new LateBoundInfo(maxInputSize)); if (maxInputSize != -1) { delegate.setMaxInputLength(maxInputSize); } // Release references to the delegate factory, now that we're done with it. delegateFactory = null; } return delegate; } @Override public void setMaxInputLength(long size) { if (size < 0) { throw new IllegalArgumentException("Max input size must be non-negative"); } if (delegate == null) { if (maxInputSize == -1 || maxInputSize > size) { maxInputSize = size; } } else { delegate.setMaxInputLength(size); } } @Override public boolean isComplete() { // If we haven't generated the delegate, we're definitely not done yet. return delegate != null && delegate.isComplete(); } /* Operations which autovivify the delegate */ @Override public Map<String, String> getEncryptionContext() { return getDelegate().getEncryptionContext(); } @Override public CiphertextHeaders getHeaders() { return getDelegate().getHeaders(); } @Override public ProcessingSummary processBytes(byte[] in, int inOff, int inLen, byte[] out, int outOff) { return getDelegate().processBytes(in, inOff, inLen, out, outOff); } @Override public List<? extends MasterKey<?>> getMasterKeys() { return getDelegate().getMasterKeys(); } @Override public int doFinal(byte[] out, int outOff) { return getDelegate().doFinal(out, outOff); } @Override public int estimateOutputSize(int inLen) { return getDelegate().estimateOutputSize(inLen); } @Override public int estimatePartialOutputSize(int inLen) { return getDelegate().estimatePartialOutputSize(inLen); } @Override public int estimateFinalOutputSize() { return getDelegate().estimateFinalOutputSize(); } }
5,489
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/FrameEncryptionHandler.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.model.CipherFrameHeaders; import java.nio.ByteBuffer; import java.nio.ByteOrder; import javax.crypto.Cipher; import javax.crypto.SecretKey; /** * The frame encryption handler is a subclass of the encryption handler and thereby provides an * implementation of the Cryptography handler. * * <p>It implements methods for encrypting content and storing the encrypted bytes in frames. */ class FrameEncryptionHandler implements CryptoHandler { private final SecretKey encryptionKey_; private final CryptoAlgorithm cryptoAlgo_; private final CipherHandler cipherHandler_; private final int nonceLen_; private final byte[] messageId_; private final int frameSize_; private final int tagLenBytes_; private long frameNumber_ = 1; private boolean isFinalFrame_; private final byte[] bytesToFrame_; private int bytesToFrameLen_; private boolean complete_ = false; /** * Construct an encryption handler for encrypting bytes and storing them in frames. * * @param customerMasterKey the master key to use when wrapping the data key. * @param encryptionContext the encryption context to use when wrapping the data key. */ public FrameEncryptionHandler( final SecretKey encryptionKey, final int nonceLen, final CryptoAlgorithm cryptoAlgo, final byte[] messageId, final int frameSize) { encryptionKey_ = encryptionKey; cryptoAlgo_ = cryptoAlgo; nonceLen_ = nonceLen; messageId_ = messageId.clone(); frameSize_ = frameSize; tagLenBytes_ = cryptoAlgo_.getTagLen(); bytesToFrame_ = new byte[frameSize_]; bytesToFrameLen_ = 0; cipherHandler_ = new CipherHandler(encryptionKey_, Cipher.ENCRYPT_MODE, cryptoAlgo_); } /** * Encrypt a block of bytes from in putting the plaintext result into out. * * <p>It encrypts by performing the following operations: * * <ol> * <li>determine the size of encrypted content that can fit into current frame * <li>call processBytes() of the underlying cipher to do corresponding cryptographic encryption * of plaintext * <li>check if current frame is fully filled using the processed bytes, write current frame to * the output being returned. * </ol> * * @param in the input byte array. * @param inOff the offset into the in array where the data to be encrypted starts. * @param inLen the number of bytes to be encrypted. * @param out the output buffer the encrypted bytes go into. * @param outOff the offset into the output byte array the encrypted data starts at. * @return the number of bytes written to out and processed * @throws InvalidCiphertextException thrown by the underlying cipher handler. */ @Override public ProcessingSummary processBytes( final byte[] in, final int off, final int len, final byte[] out, final int outOff) throws BadCiphertextException { int actualOutLen = 0; int size = len; int offset = off; while (size > 0) { final int currentFrameCapacity = frameSize_ - bytesToFrameLen_; // bind size to the capacity of the current frame size = Math.min(currentFrameCapacity, size); System.arraycopy(in, offset, bytesToFrame_, bytesToFrameLen_, size); bytesToFrameLen_ += size; // check if there is enough bytes to create a frame if (bytesToFrameLen_ == frameSize_) { actualOutLen += writeEncryptedFrame(bytesToFrame_, 0, bytesToFrameLen_, out, outOff + actualOutLen); // reset buffer len as a new frame is created in next iteration bytesToFrameLen_ = 0; } // update offset by the size of bytes being encrypted. offset += size; // update size to the remaining bytes starting at offset. size = len - offset; } return new ProcessingSummary(actualOutLen, len); } /** * Finish processing of the bytes by writing out the ciphertext or final frame if framing. * * @param out space for any resulting output data. * @param outOff offset into out to start copying the data at. * @return number of bytes written into out. * @throws InvalidCiphertextException thrown by the underlying cipher handler. */ @Override public int doFinal(final byte[] out, final int outOff) throws BadCiphertextException { isFinalFrame_ = true; complete_ = true; return writeEncryptedFrame(bytesToFrame_, 0, bytesToFrameLen_, out, outOff); } /** * Return the size of the output buffer required for a processBytes plus a doFinal with an input * of inLen bytes. * * @param inLen the length of the input. * @return the space required to accommodate a call to processBytes and doFinal with len bytes of * input. */ @Override public int estimateOutputSize(final int inLen) { int outSize = 0; int frames = 0; // include any bytes held for inclusion in a subsequent frame int totalContent = bytesToFrameLen_ + inLen; // compute the size of the frames that will be constructed frames = totalContent / frameSize_; outSize += (frameSize_ * frames); // account for remaining data that will need a new frame. final int leftover = totalContent % frameSize_; outSize += leftover; // even if leftover is 0, there will be a final frame. frames += 1; /* * Calculate overhead of frame headers. */ // nonce and MAC tag. outSize += frames * (nonceLen_ + tagLenBytes_); // sequence number for all frames outSize += frames * (Integer.SIZE / Byte.SIZE); // sequence number end for final frame outSize += Integer.SIZE / Byte.SIZE; // integer for storing final frame size outSize += Integer.SIZE / Byte.SIZE; return outSize; } @Override public int estimatePartialOutputSize(int inLen) { int outSize = 0; int frames = 0; // include any bytes held for inclusion in a subsequent frame int totalContent = bytesToFrameLen_; if (inLen >= 0) { totalContent += inLen; } // compute the size of the frames that will be constructed frames = totalContent / frameSize_; outSize += (frameSize_ * frames); /* * Calculate overhead of frame headers. */ // nonce and MAC tag. outSize += frames * (nonceLen_ + tagLenBytes_); // sequence number for all frames outSize += frames * (Integer.SIZE / Byte.SIZE); return outSize; } @Override public int estimateFinalOutputSize() { int outSize = 0; int frames = 0; // include any bytes held for inclusion in a subsequent frame int totalContent = bytesToFrameLen_; // compute the size of the frames that will be constructed frames = totalContent / frameSize_; outSize += (frameSize_ * frames); // account for remaining data that will need a new frame. final int leftover = totalContent % frameSize_; outSize += leftover; // even if leftover is 0, there will be a final frame. frames += 1; /* * Calculate overhead of frame headers. */ // nonce and MAC tag. outSize += frames * (nonceLen_ + tagLenBytes_); // sequence number for all frames outSize += frames * (Integer.SIZE / Byte.SIZE); // sequence number end for final frame outSize += Integer.SIZE / Byte.SIZE; // integer for storing final frame size outSize += Integer.SIZE / Byte.SIZE; return outSize; } /** * We encrypt the bytes, create the headers for the block, and assemble the frame containing the * headers and the encrypted bytes. * * @param in the input byte array. * @param inOff the offset into the in array where the data to be encrypted starts. * @param inLen the number of bytes to be encrypted. * @param out the output buffer the encrypted bytes go into. * @param outOff the offset into the output byte array the encrypted data starts at. * @return the number of bytes written to out. * @throws BadCiphertextException thrown by the underlying cipher handler. * @throws AwsCryptoException if frame number exceeds the maximum allowed value. */ private int writeEncryptedFrame( final byte[] input, final int off, final int len, final byte[] out, final int outOff) throws BadCiphertextException, AwsCryptoException { if (frameNumber_ > Constants.MAX_FRAME_NUMBER // Make sure we have the appropriate flag set for the final frame; we don't want to accept // non-final-frame data when there won't be a subsequent frame for it to go into. || (frameNumber_ == Constants.MAX_FRAME_NUMBER && !isFinalFrame_)) { throw new AwsCryptoException("Frame number exceeded the maximum allowed value."); } if (out.length == 0) { return 0; } int outLen = 0; byte[] contentAad; if (isFinalFrame_ == true) { contentAad = Utils.generateContentAad( messageId_, Constants.FINAL_FRAME_STRING_ID, (int) frameNumber_, len); } else { contentAad = Utils.generateContentAad( messageId_, Constants.FRAME_STRING_ID, (int) frameNumber_, frameSize_); } final byte[] nonce = getNonce(); final byte[] encryptedBytes = cipherHandler_.cipherData(nonce, contentAad, input, off, len); // create the cipherblock headers now for the encrypted data final int encryptedContentLen = encryptedBytes.length - tagLenBytes_; final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders((int) frameNumber_, nonce, encryptedContentLen, isFinalFrame_); final byte[] cipherFrameHeaderBytes = cipherFrameHeaders.toByteArray(); // assemble the headers and the encrypted bytes into a single block System.arraycopy( cipherFrameHeaderBytes, 0, out, outOff + outLen, cipherFrameHeaderBytes.length); outLen += cipherFrameHeaderBytes.length; System.arraycopy(encryptedBytes, 0, out, outOff + outLen, encryptedBytes.length); outLen += encryptedBytes.length; frameNumber_++; return outLen; } private byte[] getNonce() { /* * To mitigate the risk of IVs colliding within the same message, we use deterministic IV generation within a * message. */ if (frameNumber_ < 1) { // This should never happen - however, since we use a "frame number zero" IV elsewhere (for // header auth), // we must be sure that we don't reuse it here. throw new IllegalStateException("Illegal frame number"); } if ((int) frameNumber_ == Constants.ENDFRAME_SEQUENCE_NUMBER && !isFinalFrame_) { throw new IllegalStateException("Too many frames"); } final byte[] nonce = new byte[nonceLen_]; ByteBuffer buf = ByteBuffer.wrap(nonce); buf.order(ByteOrder.BIG_ENDIAN); // We technically only allocate the low 32 bits for the frame number, and the other bits are // defined to be // zero. However, since MAX_FRAME_NUMBER is 2^32-1, the high-order four bytes of the long will // be zero, so the // big-endian representation will also have zeros in that position. Utils.position(buf, buf.limit() - Long.BYTES); buf.putLong(frameNumber_); return nonce; } @Override public boolean isComplete() { return complete_; } }
5,490
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/CommittedKey.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.management.openmbean.InvalidKeyException; public final class CommittedKey { private final SecretKey key_; private final byte[] commitment_; CommittedKey(SecretKey key, byte[] commitment) { key_ = key; commitment_ = commitment; } public SecretKey getKey() { return key_; } public byte[] getCommitment() { return commitment_.clone(); } /** * The template for creating the label/info for deriving the encryption key from the data key. * * <p>Note that this value must be cloned and modified prior to use. Cloned to prevent * modification of the template and threading issues. Modified to insert the algorithm id into the * first two bytes. */ private static byte[] DERIVE_KEY_LABEL_TEMPLATE = "__DERIVEKEY".getBytes(StandardCharsets.UTF_8); /** * Full label/info for deriving the key commitment value from the data key. * * <p>Unlike {@link #DERIVE_KEY_LABEL_TEMPLATE} this value does not need to be cloned or modified * prior to use. */ private static byte[] COMMITKEY_LABEL = "COMMITKEY".getBytes(StandardCharsets.UTF_8); private static final String RAW_DATA_FORMAT = "RAW"; private static final String HKDF_SHA_512 = "HkdfSHA512"; private static final String HMAC_SHA_512 = "HmacSHA512"; /** Generates an encryption key along with associated commitment value. */ public static CommittedKey generate(CryptoAlgorithm alg, SecretKey dataKey, byte[] nonce) throws InvalidKeyException { if (!alg.isCommitting()) { throw new IllegalArgumentException("Algorithm does not support key commitment."); } if (nonce.length != alg.getCommitmentNonceLength()) { throw new IllegalArgumentException("Invalid nonce size"); } if (dataKey.getFormat() == null || !dataKey.getFormat().equalsIgnoreCase(RAW_DATA_FORMAT)) { throw new IllegalArgumentException( "Currently only RAW format keys are supported for HKDF algorithms. Actual format was " + dataKey.getFormat()); } if (dataKey.getAlgorithm() == null || !dataKey.getAlgorithm().equalsIgnoreCase(alg.getDataKeyAlgo())) { throw new IllegalArgumentException( "DataKey of incorrect algorithm. Expected " + alg.getDataKeyAlgo() + " but was " + dataKey.getAlgorithm()); } final byte[] rawDataKey = dataKey.getEncoded(); if (rawDataKey.length != alg.getDataKeyLength()) { throw new IllegalArgumentException( "DataKey of incorrect length. Expected " + alg.getDataKeyLength() + " but was " + rawDataKey.length); } final String macAlgorithm; switch (alg.getKeyCommitmentAlgo_()) { case HKDF_SHA_512: macAlgorithm = HMAC_SHA_512; break; default: throw new UnsupportedOperationException( "Support for commitment with " + alg.getKeyCommitmentAlgo_() + " not yet built."); } HmacKeyDerivationFunction kdf = null; try { kdf = HmacKeyDerivationFunction.getInstance(macAlgorithm); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } kdf.init(rawDataKey, nonce); final byte[] commitment = kdf.deriveKey(COMMITKEY_LABEL, alg.getCommitmentLength()); // Clone to prevent modification of the master copy final byte[] deriveKeyLabel = DERIVE_KEY_LABEL_TEMPLATE.clone(); final short algId = alg.getValue(); deriveKeyLabel[0] = (byte) ((algId >> 8) & 0xFF); deriveKeyLabel[1] = (byte) (algId & 0xFF); SecretKey ek = new SecretKeySpec(kdf.deriveKey(deriveKeyLabel, alg.getKeyLength()), alg.getKeyAlgo()); return new CommittedKey(ek, commitment); } }
5,491
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/package-info.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ /** * Contains the internal classes that handle the cryptographic defined by the message formats and * algorithms. The package also includes auxiliary classes that implement serialization of * encryption context, parser for deserializing bytes into primitives, and generation of random * bytes. * * <p><em>No classes in this package are intended for public consumption. They may be changed at any * time without concern for API compatibility.</em> * * <ul> * <li>the CryptoHandler interface that defines the contract for the methods that must be * implemented by classes that perform encryption and decryption in this library. * <li>the EncryptionHandler and DecryptionHandler classes handle the creation and parsing of the * ciphertext headers as described in the message format. These two classes delegate the * actual encryption and decryption of content to the Block and Frame handlers. * <li>the BlockEncryptionHandler and BlockDecryptionHandler classes handle the encryption and * decryption of content stored as a single-block as described in the message format. * <li>the FrameEncryptionHandler and FrameDecryptionHandler classes handle the encryption and * decryption of content stored as frames as described in the message format. * <li>the CipherHandler that provides methods to cryptographically transform bytes using a block * cipher. Currently, it only uses AES-GCM block cipher. * <li>the EncContextSerializer provides methods to serialize a map containing the encryption * context into bytes, and deserialize bytes into a map containing the encryption context. * <li>the PrimitivesParser provides methods to parse primitive types from bytes. These methods * are used by deserialization code. * <li>the ContentAadGenerator provides methods to generate the Additional Authenticated Data * (AAD) used in encrypting the content. * <li>the Constants class that contains the constants and default values used in the library. * </ul> */ package com.amazonaws.encryptionsdk.internal;
5,492
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/internal/Constants.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; public final class Constants { /** * Default length of the message identifier used to uniquely identify every ciphertext created by * this library. * * @deprecated This value may change based on {@link CryptoAlgorithm#getMessageIdLength()} */ @Deprecated public static final int MESSAGE_ID_LEN = 16; private Constants() { // Prevent instantiation } /** Marker for identifying the final frame. */ public static final int ENDFRAME_SEQUENCE_NUMBER = ~0; // is 0xFFFFFFFF /** * The identifier for non-final frames in the framing content type. This value is used as part of * the additional authenticated data (AAD) when encryption of content in a frame. */ public static final String FRAME_STRING_ID = "AWSKMSEncryptionClient Frame"; /** * The identifier for the final frame in the framing content type. This value is used as part of * the additional authenticated data (AAD) when encryption of content in a frame. */ public static final String FINAL_FRAME_STRING_ID = "AWSKMSEncryptionClient Final Frame"; /** * The identifier for the single block content type. This value is used as part of the additional * authenticated data (AAD) when encryption of content in a single block. */ public static final String SINGLE_BLOCK_STRING_ID = "AWSKMSEncryptionClient Single Block"; /** Maximum length of the content that can be encrypted in GCM mode. */ public static final long GCM_MAX_CONTENT_LEN = (1L << 36) - 32; public static final int MAX_NONCE_LENGTH = (1 << 8) - 1; /** Maximum value of an unsigned short. */ public static final int UNSIGNED_SHORT_MAX_VAL = (1 << 16) - 1; public static final long MAX_FRAME_NUMBER = (1L << 32) - 1; public static final String EC_PUBLIC_KEY_FIELD = "aws-crypto-public-key"; }
5,493
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/model/CiphertextFooters.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.ParseException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.PrimitivesParser; import com.amazonaws.encryptionsdk.internal.Utils; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; /** * This class encapsulates the optional footer information which follows the actual protected * content. * * <p>It contains the following fields in order: * * <ol> * <li>AuthLength - 2 bytes * <li>MAuth - {@code AuthLength} bytes * </ol> */ public class CiphertextFooters { private int authLength_ = -1; private byte[] mAuth_ = null; private boolean isComplete_ = false; public CiphertextFooters() { // Do nothing } public CiphertextFooters(final byte[] mAuth) { final int length = Utils.assertNonNull(mAuth, "mAuth").length; if (length < 0 || length > Constants.UNSIGNED_SHORT_MAX_VAL) { throw new IllegalArgumentException("Invalid length for mAuth: " + length); } authLength_ = length; mAuth_ = mAuth.clone(); isComplete_ = true; } /** * Parses the footers from the {@code b} starting at offset {@code off} and returns the number of * bytes parsed/consumed. */ public int deserialize(final byte[] b, final int off) throws ParseException { if (b == null) { return 0; } int parsedBytes = 0; try { if (authLength_ < 0) { parsedBytes += parseLength(b, off + parsedBytes); } if (mAuth_ == null) { parsedBytes += parseMauth(b, off + parsedBytes); } isComplete_ = true; } catch (ParseException e) { // this results when we do partial parsing and there aren't enough // bytes to parse; ignore it and return the bytes parsed thus far. } return parsedBytes; } public int getAuthLength() { return authLength_; } public byte[] getMAuth() { return (mAuth_ != null) ? mAuth_.clone() : null; } /** * Check if this object has all the header fields populated and available for reading. * * @return true if this object containing the single block header fields is complete; false * otherwise. */ public boolean isComplete() { return isComplete_; } public byte[] toByteArray() { try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos)) { PrimitivesParser.writeUnsignedShort(dos, authLength_); dos.write(mAuth_); dos.close(); baos.close(); return baos.toByteArray(); } catch (final IOException ex) { throw new AwsCryptoException(ex); } } private int parseLength(final byte[] b, final int off) throws ParseException { authLength_ = PrimitivesParser.parseUnsignedShort(b, off); return 2; } private int parseMauth(final byte[] b, final int off) throws ParseException { final int len = b.length - off; if (len >= authLength_) { mAuth_ = Arrays.copyOfRange(b, off, off + authLength_); return authLength_; } else { throw new ParseException( "Not enough bytes to parse mAuth, " + " needed at least " + authLength_ + " bytes, but only had " + len + " bytes"); } } }
5,494
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/model/CipherFrameHeaders.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.exception.ParseException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.PrimitivesParser; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; /** * This class implements the headers for the encrypted content stored in a frame. These headers are * parsed and used when the encrypted content in the frame is decrypted. * * <p>It contains the following fields in order: * * <ol> * <li>final sequence number marker if final frame * <li>sequence number * <li>nonce * <li>length of content in frame * </ol> */ public final class CipherFrameHeaders { private int sequenceNumber_ = 0; // this is okay since sequence numbers in // frames start at 1 private byte[] nonce_; private int frameContentLength_ = -1; // This is set after the nonce length is parsed in the CiphertextHeaders // during decryption. This can be set only using its setter. private short nonceLength_ = 0; private boolean includeFrameSize_; private boolean isComplete_; private boolean isFinalFrame_; /** Default constructor. */ public CipherFrameHeaders() {} /** * Construct the frame headers using the provided sequence number, nonce, length of content, and * boolean value indicating if it is the final frame. * * @param sequenceNumber the sequence number of the frame * @param nonce the bytes containing the nonce. * @param frameContentLen the length of the content in the frame. * @param isFinal boolean value indicating if it is the final frame. */ public CipherFrameHeaders( final int sequenceNumber, final byte[] nonce, final int frameContentLen, final boolean isFinal) { sequenceNumber_ = sequenceNumber; if (nonce == null) { throw new AwsCryptoException("Nonce cannot be null."); } if (nonce.length > Constants.MAX_NONCE_LENGTH) { throw new AwsCryptoException( "Nonce length is greater than the maximum value of an unsigned byte."); } nonce_ = nonce.clone(); isFinalFrame_ = isFinal; frameContentLength_ = frameContentLen; } /** * Serialize the header into a byte array. * * @return the serialized bytes of the header. */ public byte[] toByteArray() { try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream dataStream = new DataOutputStream(outBytes); if (isFinalFrame_) { dataStream.writeInt(Constants.ENDFRAME_SEQUENCE_NUMBER); } dataStream.writeInt(sequenceNumber_); dataStream.write(nonce_); if (includeFrameSize_ || isFinalFrame_) { dataStream.writeInt(frameContentLength_); } dataStream.close(); return outBytes.toByteArray(); } catch (IOException e) { throw new AwsCryptoException("Failed to serialize cipher frame headers", e); } } /** * Parse the sequence number in the provided bytes. It looks for 4 bytes representing a integer * primitive type in the provided bytes starting at the specified offset. * * <p>If successful, it returns the size of the parsed bytes which is the size of the integer * primitive type. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the size of the integer primitive type. * @throws ParseException if there are not sufficient bytes to parse the sequence number. */ private int parseSequenceNumber(final byte[] b, final int off) throws ParseException { sequenceNumber_ = PrimitivesParser.parseInt(b, off); return Integer.SIZE / Byte.SIZE; } /** * Parse the nonce in the provided bytes. It looks for bytes of size defined by the nonce length * in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the nonce length. On * failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the nonce length. * @throws ParseException if there are not sufficient bytes to parse the nonce. */ private int parseNonce(final byte[] b, final int off) throws ParseException { final int bytesToParseLen = b.length - off; if (bytesToParseLen >= nonceLength_) { nonce_ = Arrays.copyOfRange(b, off, off + nonceLength_); return nonceLength_; } else { throw new ParseException("Not enough bytes to parse nonce"); } } /** * Parse the frame content length in the provided bytes. It looks for 4 bytes representing an * integer primitive type in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the size of the integer * primitive type. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the size of the integer primitive type. * @throws ParseException if there are not sufficient bytes to parse the frame content length. */ private int parseFrameContentLength(final byte[] b, final int off) throws ParseException { frameContentLength_ = PrimitivesParser.parseInt(b, off); if (frameContentLength_ < 0) { throw new BadCiphertextException("Invalid frame length in ciphertext"); } return Integer.SIZE / Byte.SIZE; } /** * Deserialize the provided bytes starting at the specified offset to construct an instance of * this class. * * <p>This method parses the provided bytes for the individual fields in this class. This methods * also supports partial parsing where not all the bytes required for parsing the fields * successfully are available. * * @param b the byte array to deserialize. * @param off the offset in the byte array to use for deserialization. * @return the number of bytes consumed in deserialization. */ public int deserialize(final byte[] b, final int off) { if (b == null) { return 0; } int parsedBytes = 0; try { if (sequenceNumber_ == 0) { parsedBytes += parseSequenceNumber(b, off + parsedBytes); } // parse the sequence number again if the sequence number parsed in // the previous call is the final frame marker and this frame hasn't // already been marked final. if (sequenceNumber_ == Constants.ENDFRAME_SEQUENCE_NUMBER && !isFinalFrame_) { parsedBytes += parseSequenceNumber(b, off + parsedBytes); isFinalFrame_ = true; } if (nonceLength_ > 0 && nonce_ == null) { parsedBytes += parseNonce(b, off + parsedBytes); } if (includeFrameSize_ || isFinalFrame_) { if (frameContentLength_ < 0) { parsedBytes += parseFrameContentLength(b, off + parsedBytes); } } isComplete_ = true; } catch (ParseException e) { // this results when we do partial parsing and there aren't enough // bytes to parse; so just return the bytes parsed thus far. } return parsedBytes; } /** * Return if the frame is a final frame. The final frame is identified as the frame containing the * final sequence number marker. * * @return true if final frame; false otherwise. */ public boolean isFinalFrame() { return isFinalFrame_; } /** * Check if this object has all the header fields populated and available for reading. * * @return true if this object containing the single block header fields is complete; false * otherwise. */ public boolean isComplete() { return isComplete_; } /** * Return the nonce set in the frame header. * * @return the bytes containing the nonce set in the frame header. */ public byte[] getNonce() { return nonce_ != null ? nonce_.clone() : null; } /** * Return the frame content length set in the frame header. * * @return the frame content length set in the frame header. */ public int getFrameContentLength() { return frameContentLength_; } /** * Return the frame sequence number set in the frame header. * * @return the frame sequence number set in the frame header. */ public int getSequenceNumber() { return sequenceNumber_; } /** * Set the length of the nonce used in the encryption of the content in the frame. * * @param nonceLength the length of the nonce used in the encryption of the content in the frame. */ public void setNonceLength(final short nonceLength) { nonceLength_ = nonceLength; } /** * Set the flag to specify whether the frame length needs to be included or parsed in the header. * * @param value true if the frame length needs to be included or parsed in the header; false * otherwise */ public void includeFrameSize(final boolean value) { includeFrameSize_ = true; } }
5,495
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/model/CipherBlockHeaders.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.exception.ParseException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.PrimitivesParser; import java.nio.ByteBuffer; import java.util.Arrays; /** * This class implements the headers for the encrypted content stored in a single block. These * headers are parsed and used when the encrypted content in the single block is decrypted. * * <p>It contains the following fields in order: * * <ol> * <li>nonce * <li>length of content * </ol> */ // @ non_null_by_default public final class CipherBlockHeaders { // @ spec_public nullable private byte[] nonce_; // @ spec_public private long contentLength_ = -1; // This is set after the nonce length is parsed in the CiphertextHeaders // during decryption. This can be set only using its setter. // @ spec_public private short nonceLength_ = 0; // @ public invariant nonceLength_ >= 0; // @ spec_public private boolean isComplete_; /** Default constructor. */ // @ public normal_behavior // @ ensures nonce_ == null; // @ ensures contentLength_ == -1; // @ ensures nonceLength_ == 0; // @ ensures isComplete_ == false; public CipherBlockHeaders() {} /** * Construct the single block headers using the provided nonce and length of content. * * @param nonce the bytes containing the nonce. * @param contentLen the length of the content in the block. */ // @ public normal_behavior // @ requires nonce != null && nonce.length <= Constants.MAX_NONCE_LENGTH; // @ ensures \fresh(nonce_) && nonce_.length == nonce.length; // @ ensures Arrays.equalArrays(nonce_, nonce); // @ ensures contentLength_ == contentLen; // @ ensures nonceLength_ == 0; // @ ensures isComplete_ == false; // @ also private exceptional_behavior // @ requires nonce == null || nonce.length > Constants.MAX_NONCE_LENGTH; // @ signals_only AwsCryptoException; // @ pure public CipherBlockHeaders(/*@ nullable @*/ final byte[] nonce, final long contentLen) { if (nonce == null) { throw new AwsCryptoException("Nonce cannot be null."); } if (nonce.length > Constants.MAX_NONCE_LENGTH) { throw new AwsCryptoException( "Nonce length is greater than the maximum value of an unsigned byte."); } nonce_ = nonce.clone(); contentLength_ = contentLen; } /** * Serialize the header into a byte array. * * @return the serialized bytes of the header. */ /*@ public normal_behavior @ requires nonce_ != null; @ old int nLen = nonce_.length; @ requires nonce_.length <= Integer.MAX_VALUE - (Long.SIZE / Byte.SIZE); @ ensures \result.length == nonce_.length + (Long.SIZE / Byte.SIZE); @ ensures (\forall int i; 0<=i && i<nonce_.length; \result[i] == nonce_[i]); @ ensures contentLength_ == Long.asLong(\result[nLen], \result[nLen+1], \result[nLen+2], @ \result[nLen+3], \result[nLen+4], \result[nLen+5], @ \result[nLen+6], \result[nLen+7]); @ pure @*/ public byte[] toByteArray() { final int outLen = nonce_.length + (Long.SIZE / Byte.SIZE); final ByteBuffer out = ByteBuffer.allocate(outLen); out.put(nonce_); out.putLong(contentLength_); return out.array(); } /** * Parse the nonce in the provided bytes. It looks for bytes of size defined by the nonce length * in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the nonce length. On * failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the nonce length. * @throws ParseException if there are not sufficient bytes to parse the nonce. */ // @ private normal_behavior // @ requires nonceLength_ > 0; // @ requires 0 <= off; // @ requires b.length - off >= nonceLength_; // @ assignable nonce_; // @ ensures nonce_ != null && \fresh(nonce_); // @ ensures Arrays.equalArrays(b, off, nonce_, 0, nonceLength_); // @ ensures \result == nonceLength_; // @ also private exceptional_behavior // @ // add exceptions from arrays.copyofrange // @ requires b.length - off < nonceLength_; // @ assignable \nothing; // @ signals_only ParseException; private int parseNonce(final byte[] b, final int off) throws ParseException { final int bytesToParseLen = b.length - off; if (bytesToParseLen >= nonceLength_) { nonce_ = Arrays.copyOfRange(b, off, off + nonceLength_); return nonceLength_; } else { throw new ParseException("Not enough bytes to parse nonce"); } } /** * Parse the content length in the provided bytes. It looks for 8 bytes representing a long * primitive type in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the size of the long * primitive type. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the size of the long primitive type. * @throws ParseException if there are not sufficient bytes to parse the content length. */ // @ private behavior // @ requires off >= 0; // @ requires b.length - off >= Long.BYTES; // @ old long len = // Long.asLong(b[off],b[off+1],b[off+2],b[off+3],b[off+4],b[off+5],b[off+6],b[off+7]); // @ assignable contentLength_; // @ ensures len >= 0; // @ ensures contentLength_ == len; // @ ensures \result == Long.BYTES; // @ signals_only BadCiphertextException; // @ signals (BadCiphertextException) len < 0 && contentLength_ == len; // @ also private exceptional_behavior // @ requires b.length - off < Long.BYTES; // @ assignable \nothing; // @ signals_only ParseException; private int parseContentLength(final byte[] b, final int off) throws ParseException { contentLength_ = PrimitivesParser.parseLong(b, off); if (contentLength_ < 0) { throw new BadCiphertextException("Invalid content length in ciphertext"); } return Long.SIZE / Byte.SIZE; } /** * Deserialize the provided bytes starting at the specified offset to construct an instance of * this class. * * <p>This method parses the provided bytes for the individual fields in this class. This methods * also supports partial parsing where not all the bytes required for parsing the fields * successfully are available. * * @param b the byte array to deserialize. * @param off the offset in the byte array to use for deserialization. * @return the number of bytes consumed in deserialization. */ /*@ public normal_behavior @ requires b == null; @ assignable \nothing; @ ensures \result == 0; @ also @ // case: do not need to parse either value @ public normal_behavior @ requires b != null && contentLength_ >= 0 && (nonce_ != null || nonceLength_ == 0); @ assignable isComplete_; @ ensures \result == 0; @ ensures isComplete_; @ also @ // case: parse nonce (parse exception) @ public normal_behavior @ requires b != null && nonce_ == null && nonceLength_ > 0; @ requires b.length - off < nonceLength_; @ assignable \nothing; @ ensures \result == 0; @ also @ // case: parse nonce (normally) and not content length @ public normal_behavior @ requires b != null && nonce_ == null && nonceLength_ > 0; @ requires off >= 0 && b.length - off >= nonceLength_; @ requires contentLength_ >= 0; @ assignable nonce_, isComplete_; @ ensures nonce_ != null && \fresh(nonce_); @ ensures Arrays.equalArrays(b, off, nonce_, 0, nonceLength_); @ ensures \result == nonceLength_; @ ensures isComplete_; @ also @ // case: do not parse nonce and parse content length (parse exception) @ public normal_behavior @ requires b != null && (nonce_ != null || nonceLength_ == 0); @ requires contentLength_ < 0; @ requires b.length - off < Long.BYTES; @ assignable \nothing; @ ensures \result == 0; @ also @ // case: parse nonce (normally) and parse content length (parse exception) @ public normal_behavior @ requires b != null && nonce_ == null && nonceLength_ > 0; @ requires off >= 0 && b.length - off >= nonceLength_; @ requires contentLength_ < 0; @ requires b.length - (off + nonceLength_) < Long.BYTES; @ assignable nonce_; @ ensures Arrays.equalArrays(b, off, nonce_, 0, nonceLength_); @ ensures \result == nonceLength_; @ also @ // case: do not parse nonce and parse content length (normally) @ public behavior @ requires b != null && (nonce_ != null || nonceLength_ == 0); @ requires contentLength_ < 0; @ requires off >= 0; @ requires b.length - off >= Long.BYTES; @ assignable contentLength_, isComplete_; @ ensures isComplete_ && contentLength_ >= 0; @ ensures contentLength_ == Long.asLong(b[off], b[off+1], b[off+2], b[off+3], @ b[off+4], b[off+5], b[off+6], b[off+7]); @ ensures \result == Long.BYTES; @ signals_only BadCiphertextException; @ signals (BadCiphertextException) contentLength_ < 0 && isComplete_ == \old(isComplete_); @ also @ // case: parse both normally @ public behavior @ old int nLen = nonceLength_; @ requires b != null; @ requires nonce_ == null && nonceLength_ > 0 && contentLength_ < 0; @ requires off >= 0 && b.length - off >= nonceLength_; @ requires b.length - (off + nonceLength_) >= Long.BYTES; @ requires nonceLength_ <= Integer.MAX_VALUE - Long.BYTES; @ assignable nonce_, contentLength_, isComplete_; @ ensures isComplete_ && contentLength_ >= 0; @ ensures Arrays.equalArrays(b, off, nonce_, 0, nonceLength_); @ ensures contentLength_ == Long.asLong(b[nLen+off], b[nLen+off+1], b[nLen+off+2], @ b[nLen+off+3], b[nLen+off+4], b[nLen+off+5], @ b[nLen+off+6], b[nLen+off+7]); @ ensures \result == nonceLength_ + Long.BYTES; @ signals_only BadCiphertextException; @ signals (BadCiphertextException) (contentLength_ < 0 && isComplete_ == \old(isComplete_) @ && Arrays.equalArrays(b, off, nonce_, 0, nonceLength_)); @*/ public int deserialize(/*@ nullable */ final byte[] b, final int off) { if (b == null) { return 0; } // @ assert b != null; int parsedBytes = 0; try { if (nonceLength_ > 0 && nonce_ == null) { parsedBytes += parseNonce(b, off + parsedBytes); } if (contentLength_ < 0) { parsedBytes += parseContentLength(b, off + parsedBytes); } isComplete_ = true; } catch (ParseException e) { // this results when we do partial parsing and there aren't enough // bytes to parse; so just return the bytes parsed thus far. } return parsedBytes; } /** * Check if this object has all the header fields populated and available for reading. * * @return true if this object containing the single block header fields is complete; false * otherwise. */ // @ public normal_behavior // @ ensures \result == isComplete_; // @ pure public boolean isComplete() { return isComplete_; } /** * Return the nonce set in the single block header. * * @return the bytes containing the nonce set in the single block header. */ // @ public normal_behavior // @ requires nonce_ == null; // @ ensures \result == null; // @ also public normal_behavior // @ requires nonce_ != null; // @ ensures \result != null; // @ ensures \fresh(\result); // @ ensures \result != null; // @ ensures \result.length == nonce_.length; // @ ensures java.util.Arrays.equalArrays(\result,nonce_); // @ pure nullable public byte[] getNonce() { return nonce_ != null ? nonce_.clone() : null; } /** * Return the content length set in the single block header. * * @return the content length set in the single block header. */ // @ public normal_behavior // @ ensures \result == contentLength_; // @ pure public long getContentLength() { return contentLength_; } /** * Set the length of the nonce used in the encryption of the content stored in the single block. * * @param nonceLength the length of the nonce used in the encryption of the content stored in the * single block. */ // @ public normal_behavior // @ requires nonceLength >= 0; // @ assignable nonceLength_; // @ ensures nonceLength_ == nonceLength; public void setNonceLength(final short nonceLength) { nonceLength_ = nonceLength; } }
5,496
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/model/CiphertextType.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * This enum describes the supported types of ciphertext in this library. * * <p>Format: CiphertextType(byte value representing the type) */ public enum CiphertextType { CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA(128); private final byte value_; /** * Create a mapping between the CiphertextType object and its byte value. This is a static method * so the map is created when the class is loaded. This enables fast lookups of the CiphertextType * given a value. */ private static final Map<Byte, CiphertextType> ID_MAPPING = new HashMap<>(); static { for (final CiphertextType s : EnumSet.allOf(CiphertextType.class)) { ID_MAPPING.put(s.value_, s); } } private CiphertextType(final int value) { /* * Java reads literals as integers. So we cast the integer value to byte * here to avoid doing this in the enum definitions above. */ value_ = (byte) value; } /** * Return the value used to encode this ciphertext type object in the ciphertext. * * @return the byte value used to encode this ciphertext type. */ public byte getValue() { return value_; } /** * Deserialize the provided byte value by returning the CiphertextType object representing the * byte value. * * @param value the byte representing the value of the CiphertextType object. * @return the CiphertextType object representing the byte value. */ public static CiphertextType deserialize(final byte value) { final Byte valueByte = Byte.valueOf(value); final CiphertextType result = ID_MAPPING.get(valueByte); return result; } }
5,497
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/model/KeyBlob.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.ParseException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.PrimitivesParser; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; /** * This class implements the format of the key blob. The format contains the following fields in * order: * * <ol> * <li>length of key provider * <li>key provider * <li>length of key provider info * <li>key provider info * <li>length of encrypted key * <li>encrypted key * </ol> */ // @ nullable_by_default public final class KeyBlob implements EncryptedDataKey { private int keyProviderIdLen_ = -1; // @ in providerId; private byte[] keyProviderId_; // @ in providerId; private int keyProviderInfoLen_ = -1; // @ in providerInformation; private byte[] keyProviderInfo_; // @ in providerInformation; private int encryptedKeyLen_ = -1; // @ in encryptedDataKey; private byte[] encryptedKey_; // @ in encryptedDataKey; // @ private invariant keyProviderIdLen_ <= Constants.UNSIGNED_SHORT_MAX_VAL; // @ private invariant keyProviderInfoLen_ <= Constants.UNSIGNED_SHORT_MAX_VAL; // @ private invariant encryptedKeyLen_ <= Constants.UNSIGNED_SHORT_MAX_VAL; // @// KeyBlob implements EncryptedDataKey, which defines three model fields. // @// For a KeyBlob, these model fields correspond directly to some underlying // @// Java fields, as expressed by the following "represents" declarations: // @ private represents providerId = keyProviderId_; // @ private represents providerInformation = keyProviderInfo_; // @ private represents encryptedDataKey = encryptedKey_; // @// As mentioned in EncryptedDataKey, deserialization goes through some // @// incomplete intermediate states. The ghost field "deserializing" keeps // @// track of these states: // @ private ghost int deserializing; // @ private invariant 0 <= deserializing && deserializing < 4; // @// The abstract "isDeserializing", defined in EncryptedDataKey, is represented // @// as "true" whenever "deserializing" is non-0. // @ private represents isDeserializing = deserializing != 0; // @// The fields of KeyBlob come in pairs, for example, "keyProviderId_" and // @// "keyProviderIdLen_". Generally, the latter stores the length of the former. // @// But this is not always so. For one, if the former is "null", then the latter // @// is -1. Also, this relationship the two fields does not hold in one of the // @// incomplete intermediate deserialization states. Therefore, the invariants // @// about these fields are as follows: // @ private invariant deserializing == 1 || keyProviderIdLen_ == (keyProviderId_ == null ? -1 : // keyProviderId_.length); // @ private invariant deserializing == 2 || keyProviderInfoLen_ == (keyProviderInfo_ == null ? -1 // : keyProviderInfo_.length); // @ private invariant deserializing == 3 || encryptedKeyLen_ == (encryptedKey_ == null ? -1 : // encryptedKey_.length); // @// In the incomplete intermediate states, other specific properties hold about the // @// fields, as expressed in the following invariants: // @ private invariant deserializing == 1 ==> 0 <= keyProviderIdLen_ && keyProviderId_ == null; // @ private invariant deserializing == 2 ==> 0 <= keyProviderIdLen_ && 0 <= keyProviderInfoLen_ // && keyProviderInfo_ == null; // @ private invariant deserializing == 3 ==> 0 <= keyProviderIdLen_ && 0 <= keyProviderInfoLen_ // && 0 <= encryptedKeyLen_ && encryptedKey_ == null; // @// It is by querying the "isComplete()" method that a caller finds out if the // @// deserialization is only partially done or is complete. The "isComplete()" // @// method is defined later on and returns the value of the field "isComplete_". // @// If postcondition of "deserialize()" and the following public invariant about // @// "isComplete_" tell a client that the 3 abstract properties of the class have // @// been initialized. Note that this invariant (and, indeed, the "isComplete()" // @// method) does not tell a client anything useful unless "deserialize()" has been // @// called. For example, if the 3 abstract properties of a KeyBlob have been // @// initialized using the "set..." methods, then the result value of "isComplete()" // @// is meaningless. // @ spec_public private boolean isComplete_ = false; // @ public invariant isComplete_ && !isDeserializing ==> providerId != null && // providerInformation != null && encryptedDataKey != null; /** Default constructor. */ // @ public normal_behavior // @ ensures providerId == null && providerInformation == null && encryptedDataKey == null; // @ ensures !isDeserializing; // @ pure public KeyBlob() {} /** * Construct a key blob using the provided key, key provider identifier, and key provider * information. * * @param keyProviderId the key provider identifier string. * @param keyProviderInfo the bytes containing the key provider info. * @param encryptedDataKey the encrypted bytes of the data key. */ // @ public normal_behavior // @ requires keyProviderId != null && EncryptedDataKey.s2ba(keyProviderId).length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ requires keyProviderInfo != null && keyProviderInfo.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ requires encryptedDataKey != null && encryptedDataKey.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ ensures \fresh(providerId); // @ ensures Arrays.equalArrays(providerId, EncryptedDataKey.s2ba(keyProviderId)); // @ ensures \fresh(providerInformation); // @ ensures Arrays.equalArrays(providerInformation, keyProviderInfo); // @ ensures \fresh(this.encryptedDataKey); // @ ensures Arrays.equalArrays(this.encryptedDataKey, encryptedDataKey); // @ ensures !isDeserializing; // @ also // @ public exceptional_behavior // @ requires keyProviderId != null && keyProviderInfo != null && encryptedDataKey != null; // @ requires Constants.UNSIGNED_SHORT_MAX_VAL < EncryptedDataKey.s2ba(keyProviderId).length || // Constants.UNSIGNED_SHORT_MAX_VAL < keyProviderInfo.length || Constants.UNSIGNED_SHORT_MAX_VAL < // encryptedDataKey.length; // @ signals_only AwsCryptoException; // @ pure public KeyBlob( final String keyProviderId, final byte[] keyProviderInfo, final byte[] encryptedDataKey) { setEncryptedDataKey(encryptedDataKey); setKeyProviderId(keyProviderId); setKeyProviderInfo(keyProviderInfo); } // @ public normal_behavior // @ requires edk != null && !edk.isDeserializing; // @ requires edk.providerId != null && EncryptedDataKey.ba2s2ba(edk.providerId).length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ requires edk.providerInformation != null && edk.providerInformation.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ requires edk.encryptedDataKey != null && edk.encryptedDataKey.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ ensures \fresh(providerId); // @ ensures Arrays.equalArrays(providerId, EncryptedDataKey.ba2s2ba(edk.providerId)); // @ ensures \fresh(providerInformation); // @ ensures Arrays.equalArrays(providerInformation, edk.providerInformation); // @ ensures \fresh(encryptedDataKey); // @ ensures Arrays.equalArrays(encryptedDataKey, edk.encryptedDataKey); // @ ensures !isDeserializing; // @ also // @ public exceptional_behavior // @ requires edk != null && !edk.isDeserializing; // @ requires edk.providerId != null && edk.providerInformation != null && edk.encryptedDataKey // != null; // @ requires Constants.UNSIGNED_SHORT_MAX_VAL < EncryptedDataKey.ba2s2ba(edk.providerId).length // || Constants.UNSIGNED_SHORT_MAX_VAL < edk.providerInformation.length || // Constants.UNSIGNED_SHORT_MAX_VAL < edk.encryptedDataKey.length; // @ signals_only AwsCryptoException; // @ pure public KeyBlob(final EncryptedDataKey edk) { setEncryptedDataKey(edk.getEncryptedDataKey()); String s = edk.getProviderId(); // @ set EncryptedDataKey.lemma_s2ba_depends_only_string_contents_only(s, // EncryptedDataKey.ba2s(edk.providerId)); setKeyProviderId(s); setKeyProviderInfo(edk.getProviderInformation()); } /** * Parse the key provider identifier length in the provided bytes. It looks for 2 bytes * representing a short primitive type in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the size of the short * primitive type. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the size of the short primitive. * @throws ParseException if there are not sufficient bytes to parse the identifier length. */ // @ private normal_behavior // @ requires deserializing == 0 && keyProviderId_ == null; // @ requires b != null && 0 <= off && off <= b.length - Short.BYTES; // @ assignable keyProviderIdLen_, deserializing, isDeserializing; // @ ensures \result == Short.BYTES && deserializing == 1; // @ also // @ private exceptional_behavior // @ requires keyProviderId_ == null; // @ requires b != null && 0 <= off && b.length - Short.BYTES < off; // @ assignable \nothing; // @ signals_only ParseException; private int parseKeyProviderIdLen(final byte[] b, final int off) throws ParseException { keyProviderIdLen_ = PrimitivesParser.parseUnsignedShort(b, off); // @ set deserializing = 1; return Short.SIZE / Byte.SIZE; } /** * Parse the key provider identifier in the provided bytes. It looks for bytes of size defined by * the key provider identifier length in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the key provider identifier * length. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the key provider identifier length. * @throws ParseException if there are not sufficient bytes to parse the identifier. */ // @ private normal_behavior // @ requires deserializing == 1 && b != null && 0 <= off && off <= b.length; // @ requires keyProviderIdLen_ <= b.length - off; // @ assignable keyProviderId_, deserializing, isDeserializing; // @ ensures \result == keyProviderIdLen_ && deserializing == 0; // @ ensures keyProviderId_ != null && keyProviderId_.length == keyProviderIdLen_; // @ also // @ private exceptional_behavior // @ requires deserializing == 1 && b != null && 0 <= off && off <= b.length; // @ requires b.length - off < keyProviderIdLen_; // @ assignable \nothing; // @ signals_only ParseException; private int parseKeyProviderId(final byte[] b, final int off) throws ParseException { final int bytesToParseLen = b.length - off; if (bytesToParseLen >= keyProviderIdLen_) { keyProviderId_ = Arrays.copyOfRange(b, off, off + keyProviderIdLen_); // @ set deserializing = 0; return keyProviderIdLen_; } else { throw new ParseException("Not enough bytes to parse key provider id"); } } /** * Parse the key provider info length in the provided bytes. It looks for 2 bytes representing a * short primitive type in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the size of the short * primitive type. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the size of the short primitive type. * @throws ParseException if there are not sufficient bytes to parse the provider info length. */ // @ private normal_behavior // @ requires deserializing == 0 && 0 <= keyProviderIdLen_ && keyProviderInfo_ == null; // @ requires b != null && 0 <= off && off <= b.length - Short.BYTES; // @ assignable keyProviderInfoLen_, deserializing, isDeserializing; // @ ensures \result == Short.BYTES && deserializing == 2; // @ also // @ private exceptional_behavior // @ requires deserializing == 0 && 0 <= keyProviderIdLen_ && keyProviderInfo_ == null; // @ requires b != null && 0 <= off && b.length - Short.BYTES < off; // @ assignable \nothing; // @ signals_only ParseException; private int parseKeyProviderInfoLen(final byte[] b, final int off) throws ParseException { keyProviderInfoLen_ = PrimitivesParser.parseUnsignedShort(b, off); // @ set deserializing = 2; return Short.SIZE / Byte.SIZE; } /** * Parse the key provider info in the provided bytes. It looks for bytes of size defined by the * key provider info length in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the key provider info * length. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the key provider info length. * @throws ParseException if there are not sufficient bytes to parse the provider info. */ // @ private normal_behavior // @ requires deserializing == 2 && b != null && 0 <= off && off <= b.length; // @ requires keyProviderInfoLen_ <= b.length - off; // @ assignable keyProviderInfo_, deserializing, isDeserializing; // @ ensures \result == keyProviderInfoLen_ && deserializing == 0; // @ ensures keyProviderInfo_ != null && keyProviderInfo_.length == keyProviderInfoLen_; // @ also // @ private exceptional_behavior // @ requires deserializing == 2 && b != null && 0 <= off && off <= b.length; // @ requires b.length - off < keyProviderInfoLen_; // @ assignable \nothing; // @ signals_only ParseException; private int parseKeyProviderInfo(final byte[] b, final int off) throws ParseException { final int bytesToParseLen = b.length - off; if (bytesToParseLen >= keyProviderInfoLen_) { keyProviderInfo_ = Arrays.copyOfRange(b, off, off + keyProviderInfoLen_); // @ set deserializing = 0; return keyProviderInfoLen_; } else { throw new ParseException("Not enough bytes to parse key provider info"); } } /** * Parse the key length in the provided bytes. It looks for 2 bytes representing a short primitive * type in the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the size of the short * primitive type. On failure, it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the size of the short primitive type. * @throws ParseException if there are not sufficient bytes to parse the key length. */ // @ private normal_behavior // @ requires deserializing == 0 && 0 <= keyProviderIdLen_ && 0 <= keyProviderInfoLen_ && // encryptedKey_ == null; // @ requires b != null && 0 <= off && off <= b.length - Short.BYTES; // @ assignable encryptedKeyLen_, deserializing, isDeserializing; // @ ensures \result == Short.BYTES && deserializing == 3; // @ also // @ private exceptional_behavior // @ requires deserializing == 0 && 0 <= keyProviderIdLen_ && 0 <= keyProviderInfoLen_ && // encryptedKey_ == null; // @ requires b != null && 0 <= off && b.length - Short.BYTES < off; // @ assignable \nothing; // @ signals_only ParseException; private int parseKeyLen(final byte[] b, final int off) throws ParseException { encryptedKeyLen_ = PrimitivesParser.parseUnsignedShort(b, off); // @ set deserializing = 3; return Short.SIZE / Byte.SIZE; } /** * Parse the key in the provided bytes. It looks for bytes of size defined by the key length in * the provided bytes starting at the specified off. * * <p>If successful, it returns the size of the parsed bytes which is the key length. On failure, * it throws a parse exception. * * @param b the byte array to parse. * @param off the offset in the byte array to use when parsing. * @return the size of the parsed bytes which is the key length. * @throws ParseException if there are not sufficient bytes to parse the key. */ // @ private normal_behavior // @ requires deserializing == 3 && b != null && 0 <= off && off <= b.length; // @ requires encryptedKeyLen_ <= b.length - off; // @ assignable encryptedKey_, deserializing, isDeserializing; // @ ensures \result == encryptedKeyLen_ && deserializing == 0; // @ ensures encryptedKey_ != null && encryptedKey_.length == encryptedKeyLen_; // @ also // @ private exceptional_behavior // @ requires deserializing == 3 && b != null && 0 <= off && off <= b.length; // @ requires b.length - off < encryptedKeyLen_; // @ assignable \nothing; // @ signals_only ParseException; private int parseKey(final byte[] b, final int off) throws ParseException { final int bytesToParseLen = b.length - off; if (bytesToParseLen >= encryptedKeyLen_) { encryptedKey_ = Arrays.copyOfRange(b, off, off + encryptedKeyLen_); // @ set deserializing = 0; return encryptedKeyLen_; } else { throw new ParseException("Not enough bytes to parse key"); } } /** * Deserialize the provided bytes starting at the specified offset to construct an instance of * this class. * * <p>This method parses the provided bytes for the individual fields in this class. This methods * also supports partial parsing where not all the bytes required for parsing the fields * successfully are available. * * @param b the byte array to deserialize. * @param off the offset in the byte array to use for deserialization. * @return the number of bytes consumed in deserialization. */ // @ public normal_behavior // @ requires b == null; // @ assignable \nothing; // @ ensures \result == 0; // @ also // @ public normal_behavior // @ requires !isComplete_; // @ requires b != null && 0 <= off && off <= b.length; // @ assignable this.*; // @ ensures 0 <= \result && \result <= b.length - off; // @ ensures isComplete_ ==> !isDeserializing; public int deserialize(final byte[] b, final int off) { if (b == null) { return 0; } int parsedBytes = 0; try { if (keyProviderIdLen_ < 0) { parsedBytes += parseKeyProviderIdLen(b, off + parsedBytes); } if (keyProviderId_ == null) { parsedBytes += parseKeyProviderId(b, off + parsedBytes); } if (keyProviderInfoLen_ < 0) { parsedBytes += parseKeyProviderInfoLen(b, off + parsedBytes); } if (keyProviderInfo_ == null) { parsedBytes += parseKeyProviderInfo(b, off + parsedBytes); } if (encryptedKeyLen_ < 0) { parsedBytes += parseKeyLen(b, off + parsedBytes); } if (encryptedKey_ == null) { parsedBytes += parseKey(b, off + parsedBytes); } isComplete_ = true; } catch (ParseException e) { // this results when we do partial parsing and there aren't enough // bytes to parse; ignore it and return the bytes parsed thus far. } return parsedBytes; } /** * Serialize an instance of this class to a byte array. * * @return the serialized bytes of the instance. */ // @ public normal_behavior // @ requires !isDeserializing; // @ requires providerId != null; // @ requires providerInformation != null; // @ requires encryptedDataKey != null; // @ assignable \nothing; // @ ensures \fresh(\result); // @ ensures \result.length == 3 * Short.BYTES + providerId.length + providerInformation.length // + encryptedDataKey.length; // @ code_java_math // necessary, or else casts to short are warnings public byte[] toByteArray() { final int outLen = 3 * (Short.SIZE / Byte.SIZE) + keyProviderIdLen_ + keyProviderInfoLen_ + encryptedKeyLen_; final ByteBuffer out = ByteBuffer.allocate(outLen); out.putShort((short) keyProviderIdLen_); out.put(keyProviderId_, 0, keyProviderIdLen_); out.putShort((short) keyProviderInfoLen_); out.put(keyProviderInfo_, 0, keyProviderInfoLen_); out.putShort((short) encryptedKeyLen_); out.put(encryptedKey_, 0, encryptedKeyLen_); return out.array(); } /** * Check if this object has all the header fields populated and available for reading. * * @return true if this object containing the single block header fields is complete; false * otherwise. */ // @ public normal_behavior // @ ensures \result == isComplete_; // @ pure public boolean isComplete() { return isComplete_; } /** * Return the length of the key provider identifier set in the header. * * @return the length of the key provider identifier. */ // @ public normal_behavior // @ requires !isDeserializing; // @ ensures providerId == null ==> \result < 0; // @ ensures providerId != null ==> \result == providerId.length; // @ pure public int getKeyProviderIdLen() { return keyProviderIdLen_; } /** * Return the key provider identifier set in the header. * * @return the string containing the key provider identifier. */ @Override public String getProviderId() { String s = new String(keyProviderId_, StandardCharsets.UTF_8); // The following assume statement essentially says that different // calls to the String constructor above, with the same parameters, // result in strings with the same contents. The assumption is // needed, because JML does not give a way to prove it. // @ assume String.equals(s, EncryptedDataKey.ba2s(keyProviderId_)); return s; } /** * Return the length of the key provider info set in the header. * * @return the length of the key provider info. */ // @ public normal_behavior // @ requires !isDeserializing; // @ ensures providerInformation == null ==> \result < 0; // @ ensures providerInformation != null ==> \result == providerInformation.length; // @ pure public int getKeyProviderInfoLen() { return keyProviderInfoLen_; } /** * Return the information on the key provider set in the header. * * @return the bytes containing information on the key provider. */ @Override public byte[] getProviderInformation() { return keyProviderInfo_.clone(); } /** * Return the length of the encrypted data key set in the header. * * @return the length of the encrypted data key. */ // @ public normal_behavior // @ requires !isDeserializing; // @ ensures encryptedDataKey == null ==> \result < 0; // @ ensures encryptedDataKey != null ==> \result == encryptedDataKey.length; // @ pure public int getEncryptedDataKeyLen() { return encryptedKeyLen_; } /** * Return the encrypted data key set in the header. * * @return the bytes containing the encrypted data key. */ @Override public byte[] getEncryptedDataKey() { return encryptedKey_.clone(); } /** * Set the key provider identifier. * * @param keyProviderId the key provider identifier. */ // @ public normal_behavior // @ requires !isDeserializing; // @ requires keyProviderId != null && EncryptedDataKey.s2ba(keyProviderId).length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable providerId; // @ ensures \fresh(providerId); // @ ensures Arrays.equalArrays(providerId, EncryptedDataKey.s2ba(keyProviderId)); // @ also // @ private normal_behavior // TODO: this behavior is a temporary workaround // @ requires !isDeserializing; // @ requires keyProviderId != null && EncryptedDataKey.s2ba(keyProviderId).length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable keyProviderId_, keyProviderIdLen_; // @ also // @ public exceptional_behavior // @ requires !isDeserializing; // @ requires keyProviderId != null && Constants.UNSIGNED_SHORT_MAX_VAL < // EncryptedDataKey.s2ba(keyProviderId).length; // @ assignable \nothing; // @ signals_only AwsCryptoException; public void setKeyProviderId(final String keyProviderId) { final byte[] keyProviderIdBytes = keyProviderId.getBytes(StandardCharsets.UTF_8); // @ assume Arrays.equalArrays(keyProviderIdBytes, EncryptedDataKey.s2ba(keyProviderId)); if (keyProviderIdBytes.length > Constants.UNSIGNED_SHORT_MAX_VAL) { throw new AwsCryptoException( "Key provider identifier length exceeds the max value of an unsigned short primitive."); } keyProviderId_ = keyProviderIdBytes; keyProviderIdLen_ = keyProviderId_.length; } /** * Set the information on the key provider identifier. * * @param keyProviderInfo the bytes containing information on the key provider identifier. */ // @ public normal_behavior // @ requires !isDeserializing; // @ requires keyProviderInfo != null && keyProviderInfo.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable providerInformation; // @ ensures \fresh(providerInformation); // @ ensures Arrays.equalArrays(providerInformation, keyProviderInfo); // @ also // @ private normal_behavior // TODO: this behavior is a temporary workaround // @ requires !isDeserializing; // @ requires keyProviderInfo != null && keyProviderInfo.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable keyProviderInfo_, keyProviderInfoLen_; // @ also private exceptional_behavior // @ requires !isDeserializing; // @ requires keyProviderInfo != null; // @ requires keyProviderInfo.length > Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable \nothing; // @ signals_only AwsCryptoException; public void setKeyProviderInfo(final byte[] keyProviderInfo) { if (keyProviderInfo.length > Constants.UNSIGNED_SHORT_MAX_VAL) { throw new AwsCryptoException( "Key provider identifier information length exceeds the max value of an unsigned short primitive."); } keyProviderInfo_ = keyProviderInfo.clone(); keyProviderInfoLen_ = keyProviderInfo.length; } /** * Set the encrypted data key. * * @param encryptedDataKey the bytes containing the encrypted data key. */ // @ public normal_behavior // @ requires !isDeserializing; // @ requires encryptedDataKey != null && encryptedDataKey.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable this.encryptedDataKey; // @ ensures \fresh(this.encryptedDataKey); // @ ensures Arrays.equalArrays(this.encryptedDataKey, encryptedDataKey); // @ also // @ private normal_behavior // TODO: this behavior is a temporary workaround // @ requires !isDeserializing; // @ requires encryptedDataKey != null && encryptedDataKey.length <= // Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable encryptedKey_, encryptedKeyLen_; // @ also // @ public exceptional_behavior // @ requires !isDeserializing; // @ requires encryptedDataKey != null; // @ requires encryptedDataKey.length > Constants.UNSIGNED_SHORT_MAX_VAL; // @ assignable \nothing; // @ signals_only AwsCryptoException; public void setEncryptedDataKey(final byte[] encryptedDataKey) { if (encryptedDataKey.length > Constants.UNSIGNED_SHORT_MAX_VAL) { throw new AwsCryptoException( "Key length exceeds the max value of an unsigned short primitive."); } encryptedKey_ = encryptedDataKey.clone(); encryptedKeyLen_ = encryptedKey_.length; } }
5,498
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/model/ContentType.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; /** * This enum describes the supported types for storing the encrypted content in the message format. * There are two types current currently supported: single block and frames. * * <p>The single block format stores the encrypted content in a single block wrapped with headers * containing the nonce, MAC tag, and the content length. * * <p>The frame format partitions the encrypted content in multiple frames of a specified frame * length. Each frame is wrapped by an header containing the frame sequence number, nonce, and the * MAC tag. * * <p>Format: ContentType(byte value representing the type) */ public enum ContentType { SINGLEBLOCK(1), FRAME(2); private final byte value_; /** * Create a mapping between the ContentType object and its byte value. This is a static method so * the map is created when the class is loaded. This enables fast lookups of the ContentType given * a value. */ private static final Map<Byte, ContentType> ID_MAPPING = new HashMap<Byte, ContentType>(); static { for (final ContentType s : EnumSet.allOf(ContentType.class)) { ID_MAPPING.put(s.value_, s); } } private ContentType(final int value) { /* * Java reads literals as integers. So we cast the integer value to byte * here to avoid doing this in the enum definitions above. */ value_ = (byte) value; } /** * Return the value used to encode this content type object in the ciphertext. * * @return the byte value used to encode this content type. */ public byte getValue() { return value_; } /** * Deserialize the provided byte value by returning the ContentType object representing the byte * value. * * @param value the byte representing the value of the ContentType object. * @return the ContentType object representing the byte value. */ public static ContentType deserialize(final byte value) { final Byte valueByte = Byte.valueOf(value); final ContentType result = ID_MAPPING.get(valueByte); return result; } }
5,499