index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
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()); } }
800
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."); } } }
801
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;
802
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); }
803
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)); } }
804
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)); } }
805
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); } }
806
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); } }
807
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)); } }
808
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;
809
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); } }
810
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); } }
811
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;
812
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); }
813
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)); } }
814
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); } }
815
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); } }
816
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_); } }
817
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)); } }
818
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;
819
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); } } }
820
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;
821
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); } } } }
822
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; } }
823
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); } } }
824
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_; } }
825
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; } }
826
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_; } }
827
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."); } } }
828
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; } } }
829
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; } }
830
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"); } } }
831
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); } } }
832
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(); }
833
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_; } }
834
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"); } } }
835
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; } } }
836
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_; } }
837
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); }
838
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_; } }
839
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; } }
840
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(); }
841
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(); } }
842
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_; } }
843
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); } }
844
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;
845
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"; }
846
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"); } } }
847
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; } }
848
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; } }
849
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; } }
850
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; } }
851
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; } }
852
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/EncryptionMaterials.java
package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.MasterKey; import java.security.PrivateKey; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.crypto.SecretKey; /** * Contains the cryptographic materials needed for an encryption operation. * * @see * com.amazonaws.encryptionsdk.CryptoMaterialsManager#getMaterialsForEncrypt(EncryptionMaterialsRequest) */ public final class EncryptionMaterials { private final CryptoAlgorithm algorithm; private final Map<String, String> encryptionContext; private final List<KeyBlob> encryptedDataKeys; private final SecretKey cleartextDataKey; private final PrivateKey trailingSignatureKey; private final List<MasterKey> masterKeys; private EncryptionMaterials(Builder b) { this.algorithm = b.algorithm; this.encryptionContext = b.encryptionContext; this.encryptedDataKeys = b.encryptedDataKeys; this.cleartextDataKey = b.cleartextDataKey; this.trailingSignatureKey = b.trailingSignatureKey; this.masterKeys = b.getMasterKeys(); } public Builder toBuilder() { return new Builder(this); } public static Builder newBuilder() { return new Builder(); } /** * The algorithm to use for this encryption operation. Must match the algorithm in * EncryptionMaterialsRequest, if that algorithm was non-null. */ public CryptoAlgorithm getAlgorithm() { return algorithm; } /** * The encryption context to use for the encryption operation. Does not need to match the * EncryptionMaterialsRequest. */ public Map<String, String> getEncryptionContext() { return encryptionContext; } /** The KeyBlobs to serialize (in cleartext) into the encrypted message. */ public List<KeyBlob> getEncryptedDataKeys() { return encryptedDataKeys; } /** * The cleartext data key to use for encrypting this message. Note that this is the data key prior * to any key derivation required by the crypto algorithm in use. */ public SecretKey getCleartextDataKey() { return cleartextDataKey; } /** * The private key to be used to sign the message trailer. Must be present if any only if required * by the crypto algorithm, and the key type must likewise match the algorithm in use. * * <p>Note that it's the {@link com.amazonaws.encryptionsdk.CryptoMaterialsManager}'s * responsibility to find a place to put the public key; typically, this will be in the encryption * context, to improve cross-compatibility, but this is not a strict requirement. */ public PrivateKey getTrailingSignatureKey() { return trailingSignatureKey; } /** Contains a list of all MasterKeys that could decrypt this message. */ public List<MasterKey> getMasterKeys() { return masterKeys; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EncryptionMaterials that = (EncryptionMaterials) o; return algorithm == that.algorithm && Objects.equals(encryptionContext, that.encryptionContext) && Objects.equals(encryptedDataKeys, that.encryptedDataKeys) && Objects.equals(cleartextDataKey, that.cleartextDataKey) && Objects.equals(trailingSignatureKey, that.trailingSignatureKey) && Objects.equals(masterKeys, that.masterKeys); } @Override public int hashCode() { return Objects.hash( algorithm, encryptionContext, encryptedDataKeys, cleartextDataKey, trailingSignatureKey, masterKeys); } public static class Builder { private CryptoAlgorithm algorithm; private Map<String, String> encryptionContext = Collections.emptyMap(); private List<KeyBlob> encryptedDataKeys = null; private SecretKey cleartextDataKey; private PrivateKey trailingSignatureKey; private List<MasterKey> masterKeys = Collections.emptyList(); private Builder() {} private Builder(EncryptionMaterials r) { algorithm = r.algorithm; encryptionContext = r.encryptionContext; encryptedDataKeys = r.encryptedDataKeys; cleartextDataKey = r.cleartextDataKey; trailingSignatureKey = r.trailingSignatureKey; setMasterKeys(r.masterKeys); } public EncryptionMaterials build() { return new EncryptionMaterials(this); } public CryptoAlgorithm getAlgorithm() { return algorithm; } public Builder setAlgorithm(CryptoAlgorithm algorithm) { this.algorithm = algorithm; return this; } public Map<String, String> getEncryptionContext() { return encryptionContext; } public Builder setEncryptionContext(Map<String, String> encryptionContext) { this.encryptionContext = Collections.unmodifiableMap(new HashMap<>(encryptionContext)); return this; } public List<KeyBlob> getEncryptedDataKeys() { return encryptedDataKeys; } public Builder setEncryptedDataKeys(List<KeyBlob> encryptedDataKeys) { this.encryptedDataKeys = Collections.unmodifiableList(new ArrayList<>(encryptedDataKeys)); return this; } public SecretKey getCleartextDataKey() { return cleartextDataKey; } public Builder setCleartextDataKey(SecretKey cleartextDataKey) { this.cleartextDataKey = cleartextDataKey; return this; } public PrivateKey getTrailingSignatureKey() { return trailingSignatureKey; } public Builder setTrailingSignatureKey(PrivateKey trailingSignatureKey) { this.trailingSignatureKey = trailingSignatureKey; return this; } public List<MasterKey> getMasterKeys() { return masterKeys; } public Builder setMasterKeys(List<MasterKey> masterKeys) { this.masterKeys = Collections.unmodifiableList(new ArrayList<>(masterKeys)); return this; } } }
853
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/DecryptionMaterialsRequest.java
package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; public final class DecryptionMaterialsRequest { private final CryptoAlgorithm algorithm; private final Map<String, String> encryptionContext; private final List<KeyBlob> encryptedDataKeys; private DecryptionMaterialsRequest(Builder b) { this.algorithm = b.getAlgorithm(); this.encryptionContext = b.getEncryptionContext(); this.encryptedDataKeys = b.getEncryptedDataKeys(); } public CryptoAlgorithm getAlgorithm() { return algorithm; } public Map<String, String> getEncryptionContext() { return encryptionContext; } public List<KeyBlob> getEncryptedDataKeys() { return encryptedDataKeys; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static DecryptionMaterialsRequest fromCiphertextHeaders(CiphertextHeaders headers) { return newBuilder() .setAlgorithm(headers.getCryptoAlgoId()) .setEncryptionContext(headers.getEncryptionContextMap()) .setEncryptedDataKeys(headers.getEncryptedKeyBlobs()) .build(); } public static final class Builder { private CryptoAlgorithm algorithm; private Map<String, String> encryptionContext; private List<KeyBlob> encryptedDataKeys; private Builder(DecryptionMaterialsRequest request) { this.algorithm = request.getAlgorithm(); this.encryptionContext = request.getEncryptionContext(); this.encryptedDataKeys = request.getEncryptedDataKeys(); } private Builder() {} public DecryptionMaterialsRequest build() { return new DecryptionMaterialsRequest(this); } public CryptoAlgorithm getAlgorithm() { return algorithm; } public Builder setAlgorithm(CryptoAlgorithm algorithm) { this.algorithm = algorithm; return this; } public Map<String, String> getEncryptionContext() { return encryptionContext; } public Builder setEncryptionContext(Map<String, String> encryptionContext) { this.encryptionContext = Collections.unmodifiableMap(new HashMap<>(encryptionContext)); return this; } public List<KeyBlob> getEncryptedDataKeys() { return encryptedDataKeys; } public Builder setEncryptedDataKeys(List<KeyBlob> encryptedDataKeys) { this.encryptedDataKeys = Collections.unmodifiableList(new ArrayList<>(encryptedDataKeys)); return this; } } }
854
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/EncryptionMaterialsRequest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * Contains the contextual information needed to prepare an encryption operation. * * @see * com.amazonaws.encryptionsdk.CryptoMaterialsManager#getMaterialsForEncrypt(EncryptionMaterialsRequest) */ public final class EncryptionMaterialsRequest { private final Map<String, String> context; private final CryptoAlgorithm requestedAlgorithm; private final long plaintextSize; private final byte[] plaintext; private final CommitmentPolicy commitmentPolicy; private EncryptionMaterialsRequest(Builder builder) { this.context = builder.context; this.requestedAlgorithm = builder.requestedAlgorithm; this.plaintextSize = builder.plaintextSize; this.plaintext = builder.plaintext; if (builder.commitmentPolicy == null) { throw new IllegalArgumentException( "Cannot create EncryptionMaterialRequest without a " + "CommitmentPolicy specified."); } this.commitmentPolicy = builder.commitmentPolicy; } /** @return the encryption context (possibly an empty map) */ public Map<String, String> getContext() { return context; } /** * @return If a specific encryption algorithm was requested by calling {@link * com.amazonaws.encryptionsdk.AwsCrypto#setEncryptionAlgorithm(CryptoAlgorithm)}, the * algorithm requested. Otherwise, returns null. */ public CryptoAlgorithm getRequestedAlgorithm() { return requestedAlgorithm; } /** @return The size of the plaintext if known, or -1 otherwise */ public long getPlaintextSize() { return plaintextSize; } /** * @return The entire input plaintext, if available (and not streaming). Note that for performance * reason this is <i>not</i> a copy of the plaintext; you should never modify this buffer, * lest the actual data being encrypted be modified. If the input plaintext is unavailable, * this will be null. */ @SuppressFBWarnings("EI_EXPOSE_REP") public byte[] getPlaintext() { return plaintext; } public CommitmentPolicy getCommitmentPolicy() { return commitmentPolicy; } public Builder toBuilder() { return new Builder(this); } public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; EncryptionMaterialsRequest request = (EncryptionMaterialsRequest) o; return plaintextSize == request.plaintextSize && Objects.equals(context, request.context) && requestedAlgorithm == request.requestedAlgorithm && Arrays.equals(plaintext, request.plaintext); } @Override public int hashCode() { return Objects.hash(context, requestedAlgorithm, plaintextSize, plaintext); } public static class Builder { private Map<String, String> context = Collections.emptyMap(); private CryptoAlgorithm requestedAlgorithm = null; private long plaintextSize = -1; private byte[] plaintext = null; private CommitmentPolicy commitmentPolicy = null; private Builder() {} private Builder(EncryptionMaterialsRequest request) { this.context = request.getContext(); this.requestedAlgorithm = request.getRequestedAlgorithm(); this.plaintextSize = request.getPlaintextSize(); this.plaintext = request.getPlaintext(); this.commitmentPolicy = request.getCommitmentPolicy(); } public EncryptionMaterialsRequest build() { return new EncryptionMaterialsRequest(this); } public Map<String, String> getContext() { return context; } public Builder setContext(Map<String, String> context) { this.context = Collections.unmodifiableMap(new HashMap<>(context)); return this; } public CryptoAlgorithm getRequestedAlgorithm() { return requestedAlgorithm; } public Builder setRequestedAlgorithm(CryptoAlgorithm requestedAlgorithm) { this.requestedAlgorithm = requestedAlgorithm; return this; } public long getPlaintextSize() { return plaintextSize; } public Builder setPlaintextSize(long plaintextSize) { if (plaintextSize < -1) { throw new IllegalArgumentException("Bad plaintext size"); } this.plaintextSize = plaintextSize; 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; } /** * Sets the plaintext field of the request. * * <p>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. * * <p>This method implicitly sets plaintext size as well. */ @SuppressFBWarnings("EI_EXPOSE_REP") public Builder setPlaintext(byte[] plaintext) { this.plaintext = plaintext; if (plaintext != null) { return setPlaintextSize(plaintext.length); } else { return setPlaintextSize(-1); } } public CommitmentPolicy getCommitmentPolicy() { return commitmentPolicy; } public Builder setCommitmentPolicy(CommitmentPolicy commitmentPolicy) { this.commitmentPolicy = commitmentPolicy; return this; } } }
855
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/DecryptionMaterials.java
package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.DataKey; import java.security.PublicKey; public final class DecryptionMaterials { private final DataKey<?> dataKey; private final PublicKey trailingSignatureKey; private DecryptionMaterials(Builder b) { dataKey = b.getDataKey(); trailingSignatureKey = b.getTrailingSignatureKey(); } public DataKey<?> getDataKey() { return dataKey; } public PublicKey getTrailingSignatureKey() { return trailingSignatureKey; } public static Builder newBuilder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static final class Builder { private DataKey<?> dataKey; private PublicKey trailingSignatureKey; private Builder(DecryptionMaterials result) { this.dataKey = result.getDataKey(); this.trailingSignatureKey = result.getTrailingSignatureKey(); } private Builder() {} public DataKey<?> getDataKey() { return dataKey; } public Builder setDataKey(DataKey<?> dataKey) { this.dataKey = dataKey; return this; } public PublicKey getTrailingSignatureKey() { return trailingSignatureKey; } public Builder setTrailingSignatureKey(PublicKey trailingSignatureKey) { this.trailingSignatureKey = trailingSignatureKey; return this; } public DecryptionMaterials build() { return new DecryptionMaterials(this); } } }
856
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/CiphertextHeaders.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.CryptoAlgorithm; 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.EncryptionContextSerializer; import com.amazonaws.encryptionsdk.internal.PrimitivesParser; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * This class implements the headers for the message (ciphertext) produced by this library. These * headers are parsed and used when the ciphertext is decrypted. * * <p>See https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html for * a detailed description of the fields that make up the encrypted message header. * * <p>It is important to note that all but the last two header fields are checked for their * integrity during decryption using AES-GCM with the nonce and MAC tag values supplied in the last * two fields of the header. */ public class CiphertextHeaders { /** * When passed as maxEncryptedDataKeys, indicates that no maximum should be enforced (i.e., any * number of EDKs are allowed). */ public static final int NO_MAX_ENCRYPTED_DATA_KEYS = 0; private static final SecureRandom RND = new SecureRandom(); private byte version_ = -1; private byte typeVal_; // don't set this to -1 since Java byte is signed // while this value is unsigned and can go up to 128. private short cryptoAlgoVal_ = -1; private byte[] messageId_; private int encryptionContextLen_ = -1; private byte[] encryptionContext_ = new byte[0]; private int cipherKeyCount_ = -1; private List<KeyBlob> cipherKeyBlobs_; private byte contentTypeVal_ = -1; private int reservedField_ = -1; private short nonceLen_ = -1; private int frameLength_ = -1; private byte[] headerNonce_; private byte[] headerTag_; private int suiteDataLen_ = -1; private byte[] suiteData_; // internal variables private int currKeyBlobIndex_ = 0; private boolean isComplete_; private int maxEncryptedDataKeys_ = NO_MAX_ENCRYPTED_DATA_KEYS; /** Default constructor. */ public CiphertextHeaders() {} /** * Construct the ciphertext headers using the provided values. * * @param version the version to set in the header. * @param type the type to set in the header. * @param cryptoAlgo the CryptoAlgorithm enum to encode in the header. * @param encryptionContext the bytes containing the encryption context to set in the header. * @param keyBlobs list of keyBlobs containing the key provider id, key provider info, and * encrypted data key to encode in the header. * @param contentType the content type to set in the header. * @param frameSize the frame payload size to set in the header. * @deprecated {@link #CiphertextHeaders(CiphertextType, CryptoAlgorithm, byte[], List, * ContentType, int)} */ @Deprecated public CiphertextHeaders( final byte version, final CiphertextType type, final CryptoAlgorithm cryptoAlgo, final byte[] encryptionContext, final List<KeyBlob> keyBlobs, final ContentType contentType, final int frameSize) { this( type, assertVersionCompatibility(version, cryptoAlgo), encryptionContext, keyBlobs, contentType, frameSize); } // Utility method since there isn't another good way to check the argument prior to calling a // second constructor private static CryptoAlgorithm assertVersionCompatibility( final byte version, final CryptoAlgorithm cryptoAlgo) { if (version != cryptoAlgo.getMessageFormatVersion()) { throw new IllegalArgumentException( "Version must match the message format version from the type"); } return cryptoAlgo; } /** * Construct the ciphertext headers using the provided values. * * @param type the type to set in the header. * @param cryptoAlgo the CryptoAlgorithm enum to encode in the header. * @param encryptionContext the bytes containing the encryption context to set in the header. * @param keyBlobs list of keyBlobs containing the key provider id, key provider info, and * encrypted data key to encode in the header. * @param contentType the content type to set in the header. * @param frameSize the frame payload size to set in the header. */ public CiphertextHeaders( final CiphertextType type, final CryptoAlgorithm cryptoAlgo, final byte[] encryptionContext, final List<KeyBlob> keyBlobs, final ContentType contentType, final int frameSize) { version_ = cryptoAlgo.getMessageFormatVersion(); typeVal_ = type.getValue(); cryptoAlgoVal_ = cryptoAlgo.getValue(); encryptionContext_ = encryptionContext.clone(); if (encryptionContext_.length > Constants.UNSIGNED_SHORT_MAX_VAL) { throw new AwsCryptoException( "Size of encryption context exceeds the allowed maximum " + Constants.UNSIGNED_SHORT_MAX_VAL); } encryptionContextLen_ = encryptionContext.length; // we only support the encoding of 1 data key in the cipher blob. cipherKeyCount_ = keyBlobs.size(); cipherKeyBlobs_ = new ArrayList<>(keyBlobs); contentTypeVal_ = contentType.getValue(); reservedField_ = 0; nonceLen_ = cryptoAlgo.getNonceLen(); // generate random bytes and assign them as the unique identifier of the // message wrapped by this header. messageId_ = new byte[cryptoAlgo.getMessageIdLength()]; RND.nextBytes(messageId_); frameLength_ = frameSize; // Completed by construction isComplete_ = true; } /** * 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_; } /** * Parse the version in the provided bytes. It looks for a single byte in the provided bytes * starting at the specified off. * * @see {@link ParsingStep} */ private int parseVersion(final byte[] b, final int off) throws ParseException { if (version_ >= 0) { return 0; } version_ = PrimitivesParser.parseByte(b, off); return 1; } /** Sets appropriate constants and parameters for v1 parsing */ private int configV1(final byte[] b, final int off) { suiteDataLen_ = -1; return 0; } /** Sets appropriate constants and parameters for v2 parsing */ private int configV2(final byte[] b, final int off) { suiteDataLen_ = getCryptoAlgoId().getSuiteDataLength(); typeVal_ = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA.getValue(); headerNonce_ = getCryptoAlgoId().getHeaderNonce(); if (headerNonce_ == null) { throw new IllegalStateException( "Message format v2 requires the algorithm to specify a header nonce."); } if (headerNonce_.length > Short.MAX_VALUE) { throw new IllegalStateException( "Message format v2 requires the algorithm to specify a header nonce with " + "length less than 2^15."); } nonceLen_ = (short) headerNonce_.length; return 0; } /** * Parse the type in the provided bytes. It looks for a single byte in the provided bytes starting * at the specified off. * * @see {@link ParsingStep} */ private int parseType(final byte[] b, final int off) throws ParseException { if (typeVal_ != 0) { return 0; } typeVal_ = PrimitivesParser.parseByte(b, off); if (CiphertextType.deserialize(typeVal_) == null) { throw new BadCiphertextException("Invalid ciphertext type."); } return 1; } /** * Parse the algorithm identifier in the provided bytes. It looks for 2 bytes representing a short * primitive type in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseAlgoId(final byte[] b, final int off) throws ParseException { if (cryptoAlgoVal_ >= 0) { return 0; } cryptoAlgoVal_ = PrimitivesParser.parseShort(b, off); if (CryptoAlgorithm.deserialize(version_, cryptoAlgoVal_) == null) { throw new BadCiphertextException("Invalid algorithm identifier in ciphertext"); } return Short.SIZE / Byte.SIZE; } /** * Parse the message ID in the provided bytes. It looks for bytes of the size defined by the * message identifier length in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseMessageId(final byte[] b, final int off) throws ParseException { if (messageId_ != null) { return 0; } final int len = b.length - off; final int messageIdLen = getCryptoAlgoId().getMessageIdLength(); if (len >= messageIdLen) { messageId_ = Arrays.copyOfRange(b, off, off + messageIdLen); return messageIdLen; } else { throw new ParseException("Not enough bytes to parse serial number"); } } /** * Parses suite specific data * * @see {@link ParsingStep} */ private int parseSuiteData(final byte[] b, final int off) throws ParseException { if (suiteData_ != null) { return 0; } final int len = b.length - off; if (len >= suiteDataLen_) { suiteData_ = Arrays.copyOfRange(b, off, off + suiteDataLen_); return suiteDataLen_; } else { throw new ParseException("Not enough bytes to parse suite specific data"); } } /** * Parse the length of the encryption context in the provided bytes. It looks for 2 bytes * representing a short primitive type in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseEncryptionContextLen(final byte[] b, final int off) throws ParseException { if (encryptionContextLen_ >= 0) { return 0; } encryptionContextLen_ = PrimitivesParser.parseUnsignedShort(b, off); if (encryptionContextLen_ < 0) { throw new BadCiphertextException("Invalid encryption context length in ciphertext"); } return Short.SIZE / Byte.SIZE; } /** * Parse the encryption context in the provided bytes. It looks for bytes of size defined by the * encryption context length in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseEncryptionContext(final byte[] b, final int off) throws ParseException { if (encryptionContextLen_ < encryptionContext_.length) { throw new IllegalStateException( "Parsed encryption context is in an invalid state. Size exceeds parsed " + "encryption context length."); } if (encryptionContextLen_ == encryptionContext_.length) { return 0; } final int len = b.length - off; if (len >= encryptionContextLen_) { encryptionContext_ = Arrays.copyOfRange(b, off, off + encryptionContextLen_); return encryptionContextLen_; } else { throw new ParseException("Not enough bytes to parse encryption context"); } } /** * Parse the data key count in the provided bytes. It looks for 2 bytes representing a short * primitive type in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseEncryptedDataKeyCount(final byte[] b, final int off) throws ParseException { if (cipherKeyCount_ >= 0) { return 0; } cipherKeyCount_ = PrimitivesParser.parseUnsignedShort(b, off); if (cipherKeyCount_ < 0) { throw new BadCiphertextException("Invalid cipher key count in ciphertext"); } if (maxEncryptedDataKeys_ > 0 && cipherKeyCount_ > maxEncryptedDataKeys_) { throw new AwsCryptoException("Ciphertext encrypted data keys exceed maxEncryptedDataKeys"); } cipherKeyBlobs_ = Arrays.asList(new KeyBlob[cipherKeyCount_]); return Short.SIZE / Byte.SIZE; } /** * Parses the list of encrypted key blobs. Unlike many of the other parsing methods, this one can * make partial progress. To indicate this partial progress it throws a {@link * PartialParseException} containing the number of parsed bytes. * * @see {@link ParsingStep} */ private int parseEncryptedKeyBlobList(final byte[] b, final int off) throws PartialParseException { int parsedBytes = 0; try { if (cipherKeyCount_ > 0) { while (currKeyBlobIndex_ < cipherKeyCount_) { if (cipherKeyBlobs_.get(currKeyBlobIndex_) == null) { cipherKeyBlobs_.set(currKeyBlobIndex_, new KeyBlob()); } if (cipherKeyBlobs_.get(currKeyBlobIndex_).isComplete() == false) { parsedBytes += parseEncryptedKeyBlob(b, off + parsedBytes); // check if we had enough bytes to parse the key blob if (cipherKeyBlobs_.get(currKeyBlobIndex_).isComplete() == false) { throw new ParseException("Not enough bytes to parse key blob"); } } currKeyBlobIndex_++; } } } catch (final ParseException ex) { throw new PartialParseException(ex, parsedBytes); } return parsedBytes; } /** * Parse the encrypted key blob. It delegates the parsing to the methods in the key blob class. * * @see {@link ParsingStep} */ private int parseEncryptedKeyBlob(final byte[] b, final int off) throws ParseException { return cipherKeyBlobs_.get(currKeyBlobIndex_).deserialize(b, off); } /** * Parse the content type in the provided bytes. It looks for a single byte in the provided bytes * starting at the specified off. * * @see {@link ParsingStep} */ private int parseContentType(final byte[] b, final int off) throws ParseException { if (contentTypeVal_ >= 0) { return 0; } contentTypeVal_ = PrimitivesParser.parseByte(b, off); if (ContentType.deserialize(contentTypeVal_) == null) { throw new BadCiphertextException("Invalid content type in ciphertext."); } return 1; } /** * Parse reserved field in the provided bytes. It looks for 4 bytes representing an integer * primitive type in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseReservedField(final byte[] b, final int off) throws ParseException { if (reservedField_ >= 0) { return 0; } reservedField_ = PrimitivesParser.parseInt(b, off); if (reservedField_ != 0) { throw new BadCiphertextException("Invalid value for reserved field in ciphertext"); } return Integer.SIZE / Byte.SIZE; } /** * Parse the length of the nonce in the provided bytes. It looks for a single byte in the provided * bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseNonceLen(final byte[] b, final int off) throws ParseException { if (nonceLen_ >= 0) { return 0; } nonceLen_ = PrimitivesParser.parseByte(b, off); if (nonceLen_ < 0) { throw new BadCiphertextException("Invalid nonce length in ciphertext"); } return 1; } /** * Parse the frame payload length in the provided bytes. It looks for 4 bytes representing an * integer primitive type in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseFramePayloadLength(final byte[] b, final int off) throws ParseException { if (frameLength_ >= 0) { return 0; } frameLength_ = PrimitivesParser.parseInt(b, off); if (frameLength_ < 0) { throw new BadCiphertextException("Invalid frame length in ciphertext"); } return Integer.SIZE / Byte.SIZE; } /** * Parse the header nonce in the provided bytes. It looks for bytes of the size defined by the * nonce length in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseHeaderNonce(final byte[] b, final int off) throws ParseException { if (nonceLen_ == 0 || headerNonce_ != null) { return 0; } final int len = b.length - off; if (len >= nonceLen_) { headerNonce_ = Arrays.copyOfRange(b, off, off + nonceLen_); return nonceLen_; } else { throw new ParseException("Not enough bytes to parse header nonce"); } } /** * Parse the header tag in the provided bytes. It uses the crypto algorithm identifier to * determine the length of the tag to parse. It looks for bytes of size defined by the tag length * in the provided bytes starting at the specified off. * * @see {@link ParsingStep} */ private int parseHeaderTag(final byte[] b, final int off) throws ParseException { if (headerTag_ != null) { return 0; } final int len = b.length - off; final CryptoAlgorithm cryptoAlgo = CryptoAlgorithm.deserialize(version_, cryptoAlgoVal_); final int tagLen = cryptoAlgo.getTagLen(); if (len >= tagLen) { headerTag_ = Arrays.copyOfRange(b, off, off + tagLen); return tagLen; } else { throw new ParseException("Not enough bytes to parse header tag"); } } /** * Marks a deserialization operation as complete. This method always succeeds while consuming zero * bytes. It sets {@link #isComplete_} to {@code true}. * * @see {@link ParsingStep} */ private int parseComplete(final byte[] b, final int off) throws ParseException { isComplete_ = true; return 0; } /** * Deserialize the provided bytes starting at the specified offset to construct an instance of * this class. Uses the default value for maxEncryptedDataKeys, which results in no limit. * * <p>This method parses the provided bytes for the individual fields in this class. This method * 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) throws ParseException { return deserialize(b, off, NO_MAX_ENCRYPTED_DATA_KEYS); } /** * 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 method * 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. * @param maxEncryptedDataKeys the maximum number of EDKs to deserialize; zero indicates no * maximum * @return the number of bytes consumed in deserialization. */ public int deserialize(final byte[] b, final int off, int maxEncryptedDataKeys) throws ParseException { if (b == null) { return 0; } maxEncryptedDataKeys_ = maxEncryptedDataKeys; int parsedBytes = 0; try { parsedBytes += parseVersion(b, off + parsedBytes); final ParsingStep[] steps; switch (version_) { case 1: // Initial version steps = new ParsingStep[] { this::configV1, this::parseType, this::parseAlgoId, this::parseMessageId, this::parseEncryptionContextLen, this::parseEncryptionContext, this::parseEncryptedDataKeyCount, this::parseEncryptedKeyBlobList, this::parseContentType, this::parseReservedField, this::parseNonceLen, this::parseFramePayloadLength, this::parseHeaderNonce, this::parseHeaderTag, this::parseComplete }; break; case 2: steps = new ParsingStep[] { this::parseAlgoId, this::configV2, // Must come after we've parsed the algorithm this::parseMessageId, this::parseEncryptionContextLen, this::parseEncryptionContext, this::parseEncryptedDataKeyCount, this::parseEncryptedKeyBlobList, this::parseContentType, this::parseFramePayloadLength, this::parseSuiteData, this::parseHeaderTag, this::parseComplete }; break; default: throw new BadCiphertextException("Invalid version"); } for (final ParsingStep step : steps) { parsedBytes += step.parse(b, off + parsedBytes); } } catch (final PartialParseException 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. parsedBytes += e.bytesParsed_; } catch (final 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 the header fields into a byte array. Note this method does not serialize the header * nonce and tag. * * @return the serialized bytes of the header fields not including the header nonce and tag. */ public byte[] serializeAuthenticatedFields() { try { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); DataOutputStream dataStream = new DataOutputStream(outBytes); dataStream.writeByte(version_); if (version_ == 1) { dataStream.writeByte(typeVal_); dataStream.writeShort(cryptoAlgoVal_); dataStream.write(messageId_); PrimitivesParser.writeUnsignedShort(dataStream, encryptionContextLen_); if (encryptionContextLen_ > 0) { dataStream.write(encryptionContext_); } dataStream.writeShort(cipherKeyCount_); for (int i = 0; i < cipherKeyCount_; i++) { final byte[] cipherKeyBlobBytes = cipherKeyBlobs_.get(i).toByteArray(); dataStream.write(cipherKeyBlobBytes); } dataStream.writeByte(contentTypeVal_); dataStream.writeInt(reservedField_); dataStream.writeByte(nonceLen_); dataStream.writeInt(frameLength_); } else if (version_ == 2) { dataStream.writeShort(cryptoAlgoVal_); dataStream.write(messageId_); PrimitivesParser.writeUnsignedShort(dataStream, encryptionContextLen_); if (encryptionContextLen_ > 0) { dataStream.write(encryptionContext_); } dataStream.writeShort(cipherKeyCount_); for (int i = 0; i < cipherKeyCount_; i++) { final byte[] cipherKeyBlobBytes = cipherKeyBlobs_.get(i).toByteArray(); dataStream.write(cipherKeyBlobBytes); } dataStream.writeByte(contentTypeVal_); dataStream.writeInt(frameLength_); dataStream.write(suiteData_); } else { throw new IllegalArgumentException("Unsupported version: " + version_); } dataStream.close(); return outBytes.toByteArray(); } catch (IOException e) { throw new RuntimeException("Failed to serialize cipher text headers", e); } } /** * Serialize the header fields into a byte array. This method serializes all the header fields * including the header nonce and tag. * * @return the serialized bytes of the entire header. */ public byte[] toByteArray() { if (headerNonce_ == null || headerTag_ == null) { throw new AwsCryptoException("Header nonce and tag cannot be null."); } if (version_ == 2 && suiteData_ == null) { throw new AwsCryptoException("Suite Data cannot be null in the v2 message format."); } try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(serializeAuthenticatedFields()); // The v1 header format includes the header nonce. // In v2 this is specified by the crypto algorithm. if (version_ == 1) { baos.write(headerNonce_); } baos.write(headerTag_); return baos.toByteArray(); } catch (IOException ex) { throw new AwsCryptoException(ex); } } /** * Return the version set in the header. * * @return the byte value representing the version. */ public byte getVersion() { return version_; } /** * Return the type set in the header. * * @return the CiphertextType enum value representing the type set in the header. */ public CiphertextType getType() { return CiphertextType.deserialize(typeVal_); } /** * Return the crypto algorithm identifier set in the header. * * @return the CryptoAlgorithm enum value representing the identifier set in the header. */ public CryptoAlgorithm getCryptoAlgoId() { return CryptoAlgorithm.deserialize(version_, cryptoAlgoVal_); } /** * Return the length of the encryption context set in the header. * * @return the length of the encryption context set in the header. */ public int getEncryptionContextLen() { return encryptionContextLen_; } /** * Return the encryption context set in the header. * * @return the bytes containing encryption context set in the header. */ public byte[] getEncryptionContext() { return encryptionContext_.clone(); } public Map<String, String> getEncryptionContextMap() { return EncryptionContextSerializer.deserialize(encryptionContext_); } /** * Return the count of the encrypted key blobs set in the header. * * @return the count of the encrypted key blobs set in the header. */ public int getEncryptedKeyBlobCount() { return cipherKeyCount_; } /** * Return the encrypted key blobs set in the header. * * @return the KeyBlob objects representing the key blobs set in the header. */ public List<KeyBlob> getEncryptedKeyBlobs() { return new ArrayList<>(cipherKeyBlobs_); } /** * Return the content type set in the header. * * @return the ContentType enum value representing the content type set in the header. */ public ContentType getContentType() { return ContentType.deserialize(contentTypeVal_); } /** * Return the message identifier set in the header. * * @return the bytes containing the message identifier set in the header. */ public byte[] getMessageId() { return messageId_ != null ? messageId_.clone() : null; } /** * Return the length of the nonce set in the header. * * @return the length of the nonce set in the header. */ public short getNonceLength() { return nonceLen_; } /** * Return the length of the frame set in the header. * * @return the length of the frame set in the header. */ public int getFrameLength() { return frameLength_; } /** * Return the header nonce set in the header. * * @return the bytes containing the header nonce set in the header. */ public byte[] getHeaderNonce() { return headerNonce_ != null ? headerNonce_.clone() : null; } /** * Return the header tag set in the header. * * @return the header tag set in the header. */ public byte[] getHeaderTag() { return headerTag_ != null ? headerTag_.clone() : null; } /** * Set the header nonce to use for authenticating the header data. * * @param headerNonce the header nonce to use. */ public void setHeaderNonce(final byte[] headerNonce) { headerNonce_ = headerNonce.clone(); } /** * Set the header tag to use for authenticating the header data. * * @param headerTag the header tag to use. */ public void setHeaderTag(final byte[] headerTag) { headerTag_ = headerTag.clone(); } /** * Return suite specific data. * * @return suiteData */ public byte[] getSuiteData() { return suiteData_ != null ? suiteData_.clone() : null; } /** * Sets suite specific data * * @param suiteData */ public void setSuiteData(byte[] suiteData) { suiteData_ = suiteData.clone(); } /** * Return max encrypted data keys. Package scope for unit testing. * * @return int */ int getMaxEncryptedDataKeys() { return maxEncryptedDataKeys_; } private static class PartialParseException extends Exception { private static final long serialVersionUID = 1L; final int bytesParsed_; private PartialParseException(Throwable ex, int bytesParsed) { super(ex); bytesParsed_ = bytesParsed; } } /** * Represents a single step in parsing a header. * * <p>The following requirements apply: * * <ul> * <li>It must be safe to call multiple times. This means that it knows if it has already parsed * something and should be a NOP * <li>It returns how many bytes have been consumed. This will be 0 in the case of a NOP. * <li>If there are insufficient bytes and no bytes are consumed, it may throw either a {@link * ParseException} or a {@link PartialParseException}. * <li>If there are insufficient bytes and some bytes are parsed then it must throw a {@link * PartialParseException} indicating the number of bytes parsed. * </ul> */ @FunctionalInterface private interface ParsingStep { int parse(byte[] b, int off) throws ParseException, PartialParseException; } }
857
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/EncryptionCompletionListener.java
package com.amazonaws.encryptionsdk.model; @FunctionalInterface public interface EncryptionCompletionListener { /** * Invoked upon encryption completion; MaterialsManagers that need to know the size of the * plaintext (e.g. to enforce caching policies) can make use of this. * * @param plaintextBytes Total number of plaintext bytes encrypted */ void onEncryptDone(long plaintextBytes); }
858
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/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 classes that implement the defined message format for storing the encrypted content * and the data key. * * <ul> * <li>the CiphertextHeaders class implements the format for the headers that wrap the * (single-block/framed) encrypted content. The data key is stored in this header. * <li>the CipherBlockHeaders class implements the format for the headers that wrap the encrypted * content stored as a single-block. * <li>the CipherFrameHeader class implements the format for the headers that wrap the encrypted * content stored in frames. * <li>the KeyBlob class implements the format for storing the encrypted data key along with the * headers that identify the key provider. * </ul> */ package com.amazonaws.encryptionsdk.model;
859
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/caching/LocalCryptoMaterialsCache.java
package com.amazonaws.encryptionsdk.caching; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.TreeSet; import javax.annotation.concurrent.GuardedBy; /** * A simple implementation of the {@link CryptoMaterialsCache} using a basic LRU cache. * * <p>Example usage: * * <pre>{@code * LocalCryptoMaterialsCache cache = new LocalCryptoMaterialsCache(500); * * CachingCryptoMaterialsManager materialsManager = CachingCryptoMaterialsManager.builder() * .setMaxAge(5, TimeUnit.MINUTES) * .setCache(cache) * .withMasterKeyProvider(myMasterKeyProvider) * .build(); * * byte[] data = new AwsCrypto().encryptData(materialsManager, plaintext).getResult(); * }</pre> */ public class LocalCryptoMaterialsCache implements CryptoMaterialsCache { // The maximum number of entries to implicitly prune per access due to TTL expiration. We limit // this to avoid // latency spikes when a large number of entries have expired since the last cache usage. private static final int MAX_TTL_PRUNE = 10; // Mockable time source, to allow us to test TTL pruning. // package access for tests // note: we're not using the java 8 time APIs in order to improve android compatibility MsClock clock = MsClock.WALLCLOCK; // The magic numbers here are the normal defaults for LinkedHashMap; we have to specify them // explicitly if we are to // specify accessOrder=true, which enables LRU behavior private final LinkedHashMap<CacheIdentifier, BaseEntry> cacheMap = new LinkedHashMap<>(/* capacity */ 16, /* loadFactor */ 0.75f, /* accessOrder */ true); // This is a treeset sorted by TTL to allow us to quickly find expired entries private final TreeSet<BaseEntry> expirationQueue = new TreeSet<>(LocalCryptoMaterialsCache::compareEntries); private final int capacity; public LocalCryptoMaterialsCache(int capacity) { this.capacity = capacity; } private static int compareEntries(BaseEntry a, BaseEntry b) { int result; if (a == b) { return 0; } result = Long.compare(a.expirationTimestamp_, b.expirationTimestamp_); if (result != 0) { return result; } return Utils.compareObjectIdentity(a, b); } /** A common base for both encrypt and decrypt entries */ private class BaseEntry { final CacheIdentifier identifier_; final long expirationTimestamp_; final long creationTime = clock.timestamp(); private BaseEntry(CacheIdentifier identifier, long expiration) { this.identifier_ = identifier; this.expirationTimestamp_ = expiration; } } /** This wrapper just gives us a usable hashcode over our cache identifiers. */ private static final class CacheIdentifier { private final byte[] identifier; private final int hashCode; private CacheIdentifier(byte[] passed_id) { this.identifier = passed_id.clone(); this.hashCode = Arrays.hashCode(passed_id); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; return Arrays.equals(identifier, ((CacheIdentifier) o).identifier); } @Override public int hashCode() { return hashCode; } } // Note: We take locks on both cache entries as well as the overall cache. // The lock order is overall cache -> cache entry; this means that the entry cannot call back into // the parent cache // while holding its own lock. private final class EncryptCacheEntryInternal extends BaseEntry { private final EncryptionMaterials result; @GuardedBy("this") private UsageStats usageStats = UsageStats.ZERO; private EncryptCacheEntryInternal( CacheIdentifier identifier, long expiration, EncryptionMaterials result) { super(identifier, expiration); this.result = result; } synchronized UsageStats addAndGetUsageStats(UsageStats delta) { this.usageStats = this.usageStats.add(delta); return this.usageStats; } } // When returning cache entries, we create a new object to represent the snapshot of usage stats // at time of get. // This helps avoid races where two gets together push an entry over usage limits, and then both // miss when they // see the entry over the limit. // // Not static as invalidate calls back into the cache. private final class EncryptCacheEntryExposed implements EncryptCacheEntry { private final UsageStats usageStats_; private final EncryptCacheEntryInternal internal_; private EncryptCacheEntryExposed( final UsageStats usageStats, final EncryptCacheEntryInternal internal) { usageStats_ = usageStats; internal_ = internal; } @Override public UsageStats getUsageStats() { return usageStats_; } @Override public long getEntryCreationTime() { return internal_.creationTime; } @Override public EncryptionMaterials getResult() { return internal_.result; } @Override public void invalidate() { removeEntry(internal_); } } private final class DecryptCacheEntryInternal extends BaseEntry implements DecryptCacheEntry { final DecryptionMaterials result; private DecryptCacheEntryInternal( CacheIdentifier identifier, long expiration, DecryptionMaterials result) { super(identifier, expiration); this.result = result; } @Override public DecryptionMaterials getResult() { return result; } @Override public void invalidate() { removeEntry(this); } @Override public long getEntryCreationTime() { return creationTime; } } /** * Removes an entry from the cache. * * @param e the entry to remove */ private synchronized void removeEntry(BaseEntry e) { expirationQueue.remove(e); // This does not update the LRU if the value does not match cacheMap.remove(e.identifier_, e); } /** Prunes all TTL-expired entries, plus LRU entries until we are under capacity limits. */ private synchronized void prune() { // Purge maxage-expired entries first, to avoid pruning entries by LRU unnecessarily when we're // about to free // up space anyway. ttlPrune(); while (cacheMap.size() > capacity) { removeEntry(cacheMap.values().iterator().next()); } } /** Prunes all TTL-expired entries. Does not check capacity. */ private void ttlPrune() { int pruneCount = 0; long now = clock.timestamp(); while (!expirationQueue.isEmpty() && expirationQueue.first().expirationTimestamp_ < now && pruneCount < MAX_TTL_PRUNE) { removeEntry(expirationQueue.first()); pruneCount++; } } private synchronized <T extends BaseEntry> T getEntry(Class<T> klass, byte[] identifier) { // Perform cache maintenance first ttlPrune(); BaseEntry e = cacheMap.get(new CacheIdentifier(identifier)); if (e == null) { return null; } else { if (e.expirationTimestamp_ < clock.timestamp()) { removeEntry(e); return null; } return klass.cast(e); } } private synchronized void putEntry(final BaseEntry entry) { BaseEntry oldEntry = cacheMap.put(entry.identifier_, entry); if (oldEntry != null) { expirationQueue.remove(oldEntry); } expirationQueue.add(entry); prune(); } @Override public EncryptCacheEntry getEntryForEncrypt(byte[] cacheId, final UsageStats usageIncrement) { EncryptCacheEntryInternal entry = getEntry(EncryptCacheEntryInternal.class, cacheId); if (entry != null) { UsageStats stats = entry.addAndGetUsageStats(usageIncrement); return new EncryptCacheEntryExposed(stats, entry); } return null; } @Override public EncryptCacheEntry putEntryForEncrypt( byte[] cacheId, EncryptionMaterials encryptionMaterials, CacheHint hint, UsageStats initialUsage) { EncryptCacheEntryInternal entry = new EncryptCacheEntryInternal( new CacheIdentifier(cacheId), Utils.saturatingAdd(clock.timestamp(), hint.getMaxAgeMillis()), encryptionMaterials); entry.addAndGetUsageStats(initialUsage); putEntry(entry); return new EncryptCacheEntryExposed(initialUsage, entry); } @Override public DecryptCacheEntry getEntryForDecrypt(byte[] cacheId) { return getEntry(DecryptCacheEntryInternal.class, cacheId); } @Override public void putEntryForDecrypt( byte[] cacheId, DecryptionMaterials decryptionMaterials, CacheHint hint) { DecryptCacheEntryInternal entry = new DecryptCacheEntryInternal( new CacheIdentifier(cacheId), Utils.saturatingAdd(clock.timestamp(), hint.getMaxAgeMillis()), decryptionMaterials); putEntry(entry); } }
860
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/caching/CachingCryptoMaterialsManager.java
package com.amazonaws.encryptionsdk.caching; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.internal.EncryptionContextSerializer; 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.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * The CachingCryptoMaterialsManager wraps another {@link CryptoMaterialsManager}, and caches its * results. This helps reduce the number of calls made to the underlying {@link * CryptoMaterialsManager} and/or {@link MasterKeyProvider}, which may help reduce cost and/or * improve performance. * * <p>The CachingCryptoMaterialsManager helps enforce a number of usage limits on encrypt. * Specifically, it limits the number of individual messages encrypted with a particular data key, * and the number of plaintext bytes encrypted with the same data key. It also allows you to * configure a maximum time-to-live for cache entries. * * <p>Note that when performing streaming encryption operations, unless you set the stream size * before writing any data using {@link * com.amazonaws.encryptionsdk.CryptoOutputStream#setMaxInputLength(long)} or {@link * com.amazonaws.encryptionsdk.CryptoInputStream#setMaxInputLength(long)}, the size of the message * will not be known, and to avoid exceeding byte use limits, caching will not be performed. * * <p>By default, two different {@link CachingCryptoMaterialsManager}s will not share cached * entries, even when using the same {@link CryptoMaterialsCache}. However, it's possible to make * different {@link CachingCryptoMaterialsManager}s share the same cached entries by assigning a * partition ID to them; all {@link CachingCryptoMaterialsManager}s with the same partition ID will * share the same cached entries. * * <p>Assigning partition IDs manually requires great care; if the backing {@link * CryptoMaterialsManager}s are not equivalent, having entries cross over between them can result in * problems such as encrypting messages to the wrong key, or accidentally bypassing access controls. * For this reason we recommend not supplying a partition ID unless required for your use case. */ public class CachingCryptoMaterialsManager implements CryptoMaterialsManager { private static final String CACHE_ID_HASH_ALGORITHM = "SHA-512"; private static final long MAX_MESSAGE_USE_LIMIT = 1L << 32; private static final long MAX_BYTE_USE_LIMIT = Long.MAX_VALUE; // 2^63 - 1 private final CryptoMaterialsManager backingCMM; private final CryptoMaterialsCache cache; private final byte[] partitionIdHash; private final String partitionId; private final long maxAgeMs; private final long messageUseLimit; private final long byteUseLimit; private final CryptoMaterialsCache.CacheHint hint = new CryptoMaterialsCache.CacheHint() { @Override public long getMaxAgeMillis() { return maxAgeMs; } }; public static class Builder { private CryptoMaterialsManager backingCMM; private CryptoMaterialsCache cache; private String partitionId = null; private long maxAge = 0; private long messageUseLimit = MAX_MESSAGE_USE_LIMIT; private long byteUseLimit = Long.MAX_VALUE; private Builder() {} /** * Sets the {@link CryptoMaterialsManager} that should be queried when the {@link * CachingCryptoMaterialsManager} (CCMM) incurs a cache miss. * * <p>You can set either a MasterKeyProvider or a CryptoMaterialsManager to back the CCMM - the * last value set will be used. * * @param backingCMM The CryptoMaterialsManager to invoke on cache misses * @return this builder */ public Builder withBackingMaterialsManager(CryptoMaterialsManager backingCMM) { this.backingCMM = backingCMM; return this; } /** * Sets the {@link MasterKeyProvider} that should be queried when the {@link * CachingCryptoMaterialsManager} (CCMM) incurs a cache miss. * * <p>You can set either a MasterKeyProvider or a CryptoMaterialsManager to back the CCMM - the * last value set will be used. * * <p>This method is equivalent to calling {@link * #withBackingMaterialsManager(CryptoMaterialsManager)} passing a {@link * DefaultCryptoMaterialsManager} constructed using your {@link MasterKeyProvider}. * * @param mkp The MasterKeyProvider to invoke on cache misses * @return this builder */ public Builder withMasterKeyProvider(MasterKeyProvider mkp) { return withBackingMaterialsManager(new DefaultCryptoMaterialsManager(mkp)); } /** * Sets the cache to which this {@link CryptoMaterialsManager} will be bound. * * @param cache The cache to associate with the CMM * @return this builder */ public Builder withCache(CryptoMaterialsCache cache) { this.cache = cache; return this; } /** * Sets the partition ID for this CMM. This is an optional operation. * * <p>By default, two CMMs will never use each other's cache entries. This helps ensure that * CMMs with different delegates won't incorrectly use each other's encrypt and decrypt results. * However, in certain special circumstances it can be useful to share entries between different * CMMs - for example, if the backing CMM is constructed based on some parameters that depend on * the operation, you may wish for delegates constructed with the same parameters to share the * same partition. * * <p>To accomplish this, set the same partition ID and backing cache on both CMMs; entries * cached from one of these CMMs can then be used by the other. This should only be done with * careful consideration and verification that the CMM delegates are equivalent for your * application's purposes. * * <p>By default, the partition ID is set to a random UUID to avoid any collisions. * * @param partitionId The partition ID * @return this builder */ public Builder withPartitionId(String partitionId) { this.partitionId = partitionId; return this; } /** * Sets the maximum lifetime for entries in the cache, for both encrypt and decrypt operations. * When the specified amount of time passes after initial creation of the entry, the entry will * be considered unusable, and the next operation will incur a cache miss. * * @param maxAge The amount of time entries are allowed to live. Must be positive. * @param units The units maxAge is expressed in * @return this builder */ public Builder withMaxAge(long maxAge, TimeUnit units) { if (maxAge <= 0) { throw new IllegalArgumentException("Max age must be positive"); } this.maxAge = units.toMillis(maxAge); return this; } /** * Sets the maximum number of individual messages that can be encrypted under the same a cached * data key. This does not affect decrypt operations. * * <p>Specifying this limit is optional; by default, the limit is set to 2^32. This is also the * maximum accepted value; if you specify a higher limit, an {@link IllegalArgumentException} * will be thrown. * * @param messageUseLimit The maximum number of messages that can be encrypted by the same data * key. Must be positive. * @return this builder */ public Builder withMessageUseLimit(long messageUseLimit) { if (messageUseLimit <= 0) { throw new IllegalArgumentException("Message use limit must be positive"); } if (messageUseLimit > MAX_MESSAGE_USE_LIMIT) { throw new IllegalArgumentException( "Message use limit exceeds limit of " + MAX_MESSAGE_USE_LIMIT); } // We limit the number of messages encrypted under the same data key primarily to stay far // away from any // chance of message ID collisions (and therefore collisions of the key+IV used for the actual // message // encryption). this.messageUseLimit = messageUseLimit; return this; } /** * Sets the maximum number of plaintext bytes that can be encrypted under the same a cached data * key. This does not affect decrypt operations. * * <p>Specifying this limit is optional; by default, the limit is set to 2^63 - 1. * * <p>While this limit can be set to zero, in this case keys can only be cached if they are used * for zero-length messages. * * @param byteUseLimit The maximum number of bytes that can be encrypted by the same data key. * Must be non-negative. * @return this builder */ public Builder withByteUseLimit(long byteUseLimit) { if (byteUseLimit < 0) { throw new IllegalArgumentException("Byte use limit must be non-negative"); } // Currently, since the byte use limit is Long.MAX_VALUE, this can't be reached, but is // included for // consistency. //noinspection ConstantConditions if (byteUseLimit > MAX_BYTE_USE_LIMIT) { throw new IllegalArgumentException( "Byte use limit exceeds maximum of " + MAX_BYTE_USE_LIMIT); } this.byteUseLimit = byteUseLimit; return this; } public CachingCryptoMaterialsManager build() { if (backingCMM == null) { throw new IllegalArgumentException("Backing CMM must be set"); } if (cache == null) { throw new IllegalArgumentException("Cache must be set"); } if (maxAge <= 0) { throw new IllegalArgumentException("Max age must be set"); } return new CachingCryptoMaterialsManager(this); } } public static Builder newBuilder() { return new Builder(); } private CachingCryptoMaterialsManager(Builder builder) { this.backingCMM = builder.backingCMM; this.cache = builder.cache; this.partitionId = builder.partitionId != null ? builder.partitionId : UUID.randomUUID().toString(); this.maxAgeMs = builder.maxAge; this.messageUseLimit = builder.messageUseLimit; this.byteUseLimit = builder.byteUseLimit; try { this.partitionIdHash = MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM) .digest(partitionId.getBytes(StandardCharsets.UTF_8)); } catch (GeneralSecurityException e) { throw new AwsCryptoException(e); } } @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { // We cannot correctly enforce size limits if the request has no known plaintext size, so bypass // the cache in // this case. if (request.getPlaintextSize() == -1) { return backingCMM.getMaterialsForEncrypt(request); } // Strip off information on the plaintext length & contents - we do this because we will be // (potentially) // reusing the result from the backing CMM across multiple requests, and as such it would be // misleading to pass on // the first such request's information to the backing CMM. EncryptionMaterialsRequest upstreamRequest = request.toBuilder().setPlaintext(null).setPlaintextSize(-1).build(); byte[] cacheId = getCacheIdentifier(upstreamRequest); CryptoMaterialsCache.UsageStats increment = initialIncrementForRequest(request); // If our plaintext size is such that even a brand new entry would reach or exceed cache limits, // there's no // point in accessing the cache - in fact, doing so would poison a cache entry that could // potentially be still // used for a smaller request. So we'll bypass the cache and just call the backing CMM directly // in this case. if (increment.getBytesEncrypted() >= byteUseLimit) { return backingCMM.getMaterialsForEncrypt(request); } CryptoMaterialsCache.EncryptCacheEntry entry = cache.getEntryForEncrypt(cacheId, increment); if (entry != null && !isEntryExpired(entry.getEntryCreationTime()) && !hasExceededLimits(entry.getUsageStats())) { return entry.getResult(); } else if (entry != null) { // entry has potentially expired, so hint to the cache that it should be removed, in case the // cache stores // multiple entries or something entry.invalidate(); } // Cache miss. EncryptionMaterials result = backingCMM.getMaterialsForEncrypt(request); if (result.getAlgorithm().isSafeToCache()) { cache.putEntryForEncrypt(cacheId, result, hint, initialIncrementForRequest(request)); } return result; } private boolean hasExceededLimits(final CryptoMaterialsCache.UsageStats stats) { return stats.getBytesEncrypted() > byteUseLimit || stats.getMessagesEncrypted() > messageUseLimit; } private boolean isEntryExpired(final long entryCreationTime) { return System.currentTimeMillis() - entryCreationTime > maxAgeMs; } private CryptoMaterialsCache.UsageStats initialIncrementForRequest( EncryptionMaterialsRequest request) { return new CryptoMaterialsCache.UsageStats(request.getPlaintextSize(), 1); } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { byte[] cacheId = getCacheIdentifier(request); CryptoMaterialsCache.DecryptCacheEntry entry = cache.getEntryForDecrypt(cacheId); if (entry != null && !isEntryExpired(entry.getEntryCreationTime())) { return entry.getResult(); } DecryptionMaterials result = backingCMM.decryptMaterials(request); cache.putEntryForDecrypt(cacheId, result, hint); return result; } private byte[] getCacheIdentifier(EncryptionMaterialsRequest req) { try { MessageDigest digest = MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM); digest.update(partitionIdHash); CryptoAlgorithm algorithm = req.getRequestedAlgorithm(); digest.update((byte) (algorithm != null ? 1 : 0)); if (algorithm != null) { updateDigestWithAlgorithm(digest, algorithm); } digest.update( MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM) .digest(EncryptionContextSerializer.serialize(req.getContext()))); return digest.digest(); } catch (GeneralSecurityException e) { throw new AwsCryptoException(e); } } private byte[] getCacheIdentifier(DecryptionMaterialsRequest req) { try { MessageDigest digest = MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM); byte[] hashOfContext = digest.digest(EncryptionContextSerializer.serialize(req.getEncryptionContext())); ArrayList<byte[]> keyBlobHashes = new ArrayList<>(req.getEncryptedDataKeys().size()); for (KeyBlob blob : req.getEncryptedDataKeys()) { keyBlobHashes.add(digest.digest(blob.toByteArray())); } keyBlobHashes.sort(new Utils.ComparingByteArrays()); // Now starting the digest of the actual cache identifier digest.update(partitionIdHash); updateDigestWithAlgorithm(digest, req.getAlgorithm()); keyBlobHashes.forEach(digest::update); // This all-zero sentinel field indicates the end of the key blob hashes. digest.update(new byte[digest.getDigestLength()]); digest.update(hashOfContext); return digest.digest(); } catch (GeneralSecurityException e) { throw new AwsCryptoException(e); } } // Common helper to add the algorithm identifier (in proper big endian order) for both encrypt and // decrypt paths. private void updateDigestWithAlgorithm(MessageDigest digest, CryptoAlgorithm algorithm) { short algId = algorithm.getValue(); digest.update(new byte[] {(byte) (algId >> 8), (byte) (algId)}); } }
861
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/caching/CryptoMaterialsCache.java
package com.amazonaws.encryptionsdk.caching; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import java.util.Objects; /** * Represents a generic cache for cryptographic materials. MaterialsCaches store mappings from * abstract bytestring identifiers to MaterialsResults and DecryptResults. * * <p>In general, the materials cache is concerned about the proper storage of these materials, and * managing size limits on the cache. While it stores statistics about cache usage limits, the * enforcement of these limits is left to the caller (typically, a {@link * CachingCryptoMaterialsManager}). * * <p>For encrypt, a cache implementation may store multiple cache entries for the same identifier. * This allows for usage limits to be enforced even when doing multiple streaming requests in * parallel. However, the cache is permitted to set a limit on the number of such entries (even as * low as only allowing one entry per identifier), and if it does so should evict the excess * entries. * * <p>Being a cache, a CryptoMaterialsCache is permitted to evict entries at any time. However, a * caller can explicitly hint the cache to invalidate an entry in the encrypt-side cache. This is * generally done when usage limits are exceeded. The cache is not required to respect this * invalidation hint. * * <p>Likewise, the CacheHint passed to the put calls on caches will indicate the maximum lifetime * of entries; the cache is allowed - but not required - to evict entries automatically upon * expiration of this lifetime. */ public interface CryptoMaterialsCache { /** * Searches for an entry in the encrypt cache matching a particular cache identifier, and returns * one if found. * * @param cacheId The identifier for the item in the cache * @param usageIncrement The amount of usage to atomically add to the returned entry. This usage * increment must be reflected in the getUsageStats() method on the returned cache entry. * @return The entry, or null if not found or an error occurred */ EncryptCacheEntry getEntryForEncrypt(byte[] cacheId, final UsageStats usageIncrement); /** * Attempts to add a new entry to the encrypt cache to be returned on subsequent {@link * #getEntryForEncrypt(byte[], UsageStats)} calls. * * <p>In the event that an error occurs when adding the entry to the cache, this function shall * still return a EncryptCacheEntry instance, which shall act as if the cache entry was * immediately evicted and/or invalidated. * * @param cacheId The identifier for the item in the cache * @param encryptionMaterials The {@link EncryptionMaterials} to associate with this new entry * @param initialUsage The initial usage stats for the cache entry * @return A new, locked EncryptCacheEntry instance containing the given encryptionMaterials */ EncryptCacheEntry putEntryForEncrypt( byte[] cacheId, EncryptionMaterials encryptionMaterials, CacheHint hint, UsageStats initialUsage); /** * Searches for an entry in the encrypt cache matching a particular cache identifier, and returns * one if found. * * <p>In the event of an error accessing the cache, this function will return null. * * @param cacheId The identifier for the item in the cache * @return The cached decryption result, or null if none was found or an error occurred. */ DecryptCacheEntry getEntryForDecrypt(byte[] cacheId); /** * Adds a new entry to the decrypt cache. In the event of an error, this function will return * silently without propagating the exception. * * <p>If an entry already exists for this cache ID, the cache may either overwrite the entry in * its entirety, or update the creation timestamp for the existing entry, at its option. * * @param cacheId The identifier for the item in the cache * @param decryptionMaterials The {@link DecryptionMaterials} to associate with the new entry. */ void putEntryForDecrypt(byte[] cacheId, DecryptionMaterials decryptionMaterials, CacheHint hint); /** * Contains some additional information associated with a cache entry. The cache receiving this * hint may take some actions based on the hint, or it may ignore it entirely. */ interface CacheHint { /** * Returns the lifetime of the cache entry. This hint suggests to the cache that the entry will * not be useful after the provided number of milliseconds passes, and suggests that the cache * should discard the entry when this interval elapses even if it is not explicitly invalidated. * * <p>Note that this time counts from the <i>creation</i> of the entry, not from last use. * * @return The lifetime of this entry, in milliseconds. If the lifetime is unknown or * irrelevant, this will return {@link Long#MAX_VALUE}. */ long getMaxAgeMillis(); } /** * Represents an entry in the encrypt cache, and provides methods for manipulating the entry. * * <p>Note that the EncryptCacheEntry Java object remains valid even after the cache entry is * invalidated or evicted; getResult will still return a valid result, for example. */ interface EncryptCacheEntry { /** * @return The current usage statistics for this entry. The caller should be aware that these * statistics may be stale by the time they are returned. */ UsageStats getUsageStats(); /** @return The unix timestamp at which this entry was added to the cache, in milliseconds */ long getEntryCreationTime(); /** * @return The EncryptionMaterials associated with this cache entry. The encrypt completion * callback should be a no-op. */ EncryptionMaterials getResult(); /** Suggests to the cache that this entry should be removed from the cache. */ default void invalidate() {} } final class UsageStats { public static final UsageStats ZERO = new UsageStats(0, 0); private final long bytesEncrypted; private final long messagesEncrypted; public UsageStats(long bytesEncrypted, long messagesEncrypted) { if (bytesEncrypted < 0) { throw new IllegalArgumentException("Negative bytes encrypted is not permitted"); } if (messagesEncrypted < 0) { throw new IllegalArgumentException("Negative messages encrypted is not permitted"); } this.bytesEncrypted = bytesEncrypted; this.messagesEncrypted = messagesEncrypted; } public long getBytesEncrypted() { return bytesEncrypted; } public long getMessagesEncrypted() { return messagesEncrypted; } /** * Performs a pairwise add of two UsageStats objects. In the event of overflow, counters * saturate at {@link Long#MAX_VALUE} * * @param other * @return */ public UsageStats add(UsageStats other) { return new UsageStats( saturatingAdd(getBytesEncrypted(), other.getBytesEncrypted()), saturatingAdd(getMessagesEncrypted(), other.getMessagesEncrypted())); } static long saturatingAdd(long a, long b) { if (a < 0 || b < 0) { throw new IllegalArgumentException("Negative usage values are not permitted"); } return Utils.saturatingAdd(a, b); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UsageStats that = (UsageStats) o; return getBytesEncrypted() == that.getBytesEncrypted() && getMessagesEncrypted() == that.getMessagesEncrypted(); } @Override public int hashCode() { return Objects.hash(getBytesEncrypted(), getMessagesEncrypted()); } @Override public String toString() { return "UsageStats{" + "bytesEncrypted=" + bytesEncrypted + ", messagesEncrypted=" + messagesEncrypted + '}'; } } /** * Represents an entry in the decrypt cache, and provides methods for manipulating the entry. * * <p>Note that the DecryptCacheEntry JAva object remains valid even after the cache entry is * invalidated or evicted; getResult will still return a valid result, for example. */ interface DecryptCacheEntry { /** Returns the DecryptionMaterials associated with this entry. */ DecryptionMaterials getResult(); /** Advises the cache that this entry should be removed from the cache. */ void invalidate(); /** @return The unix timestamp at which this entry was added to the cache, in milliseconds */ long getEntryCreationTime(); } }
862
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/caching/MsClock.java
package com.amazonaws.encryptionsdk.caching; interface MsClock { MsClock WALLCLOCK = System::currentTimeMillis; public long timestamp(); }
863
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/caching/NullCryptoMaterialsCache.java
package com.amazonaws.encryptionsdk.caching; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; /** A {@link CryptoMaterialsCache} that doesn't actually cache anything. */ public class NullCryptoMaterialsCache implements CryptoMaterialsCache { @Override public EncryptCacheEntry getEntryForEncrypt(byte[] cacheId, final UsageStats usageIncrement) { return null; } @Override public EncryptCacheEntry putEntryForEncrypt( byte[] cacheId, EncryptionMaterials encryptionMaterials, CacheHint hint, UsageStats initialUsage) { return new EncryptCacheEntry() { private final long creationTime = System.currentTimeMillis(); @Override public synchronized UsageStats getUsageStats() { return initialUsage; } @Override public long getEntryCreationTime() { return creationTime; } @Override public EncryptionMaterials getResult() { return encryptionMaterials; } }; } @Override public DecryptCacheEntry getEntryForDecrypt(byte[] cacheId) { return null; } @Override public void putEntryForDecrypt( byte[] cacheId, DecryptionMaterials decryptionMaterials, CacheHint hint) { // no-op } }
864
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/exception/BadCiphertextException.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.exception; /** * This exception is thrown when the values found in a ciphertext message are invalid or corrupt. */ // @ non_null_by_default public class BadCiphertextException extends AwsCryptoException { private static final long serialVersionUID = -1L; /*@ public normal_behavior @ ensures standardThrowable(); @*/ // @ pure public BadCiphertextException() { super(); } /*@ public normal_behavior @ ensures standardThrowable(message); @*/ // @ pure public BadCiphertextException(final String message) { super(message); } /*@ public normal_behavior @ ensures standardThrowable(cause); @*/ // @ pure public BadCiphertextException(final Throwable cause) { super(cause); } /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure public BadCiphertextException(final String message, final Throwable cause) { super(message, cause); } }
865
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/exception/NoSuchMasterKeyException.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.exception; import com.amazonaws.encryptionsdk.MasterKey; /** * This exception is thrown when the SDK attempts to use a {@link MasterKey} which either doesn't * exist or to which it doesn't have access. */ // @ non_null_by_default public class NoSuchMasterKeyException extends AwsCryptoException { private static final long serialVersionUID = -1L; /*@ public normal_behavior @ ensures standardThrowable(); @*/ // @ pure public NoSuchMasterKeyException() {} /*@ public normal_behavior @ ensures standardThrowable(message); @*/ // @ pure public NoSuchMasterKeyException(final String message) { super(message); } /*@ public normal_behavior @ ensures standardThrowable(cause); @*/ // @ pure public NoSuchMasterKeyException(final Throwable cause) { super(cause); } /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure public NoSuchMasterKeyException(final String message, final Throwable cause) { super(message, cause); } /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure // TODO public NoSuchMasterKeyException( final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
866
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/exception/AwsCryptoException.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.exception; /** This is the parent class of the runtime exceptions thrown by the AWS Encryption SDK. */ // @ non_null_by_default public class AwsCryptoException extends RuntimeException { private static final long serialVersionUID = -1L; // @ public normal_behavior // @ ensures standardThrowable(); // @ pure public AwsCryptoException() { super(); } // @ public normal_behavior // @ ensures standardThrowable(message); // @ pure public AwsCryptoException(final String message) { super(message); } // @ public normal_behavior // @ ensures standardThrowable(cause); // @ pure public AwsCryptoException(final Throwable cause) { super(cause); } // @ public normal_behavior // @ ensures standardThrowable(message,cause); // @ pure public AwsCryptoException(final String message, final Throwable cause) { super(message, cause); } // @ public normal_behavior // @ ensures standardThrowable(message,cause); // @ pure // TODO public AwsCryptoException( final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
867
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/exception/CannotUnwrapDataKeyException.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.exception; import com.amazonaws.encryptionsdk.DataKey; /** This exception is thrown when there are no {@link DataKey}s which can be decrypted. */ // @ non_null_by_default public class CannotUnwrapDataKeyException extends AwsCryptoException { private static final long serialVersionUID = -1L; /*@ public normal_behavior @ ensures standardThrowable(); @*/ // @ pure public CannotUnwrapDataKeyException() { super(); } /*@ public normal_behavior @ ensures standardThrowable(message); @*/ // @ pure public CannotUnwrapDataKeyException(final String message) { super(message); } /*@ public normal_behavior @ ensures standardThrowable(cause); @*/ // @ pure public CannotUnwrapDataKeyException(final Throwable cause) { super(cause); } /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure public CannotUnwrapDataKeyException(final String message, final Throwable cause) { super(message, cause); } }
868
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/exception/ParseException.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.exception; /** * This exception is thrown when there are not enough bytes to parse a primitive, a specified number * of bytes, or the bytes does not properly represent the desired object. */ // @ non_null_by_default public class ParseException extends AwsCryptoException { private static final long serialVersionUID = -1L; /** Constructs a new exception with no detail message. */ /*@ public normal_behavior @ ensures standardThrowable(); @*/ // @ pure public ParseException() { super(); } /** * Constructs a new exception with the specified detail message. * * @param message the detail message. */ /*@ public normal_behavior @ ensures standardThrowable(message); @*/ // @ pure public ParseException(final String message) { super(message); } /** * Constructs a new exception with the specified cause and a detail message of <tt>(cause==null ? * null : cause.toString())</tt> (which typically contains the class and detail message of * <tt>cause</tt>). * * @param cause the cause (which is saved for later retrieval by the {@link Throwable#getCause()} * method). (A <tt>null</tt> value is permitted, and indicates that the cause is nonexistent * or unknown.) */ /*@ public normal_behavior @ ensures standardThrowable(cause); @*/ // @ pure public ParseException(final Throwable cause) { super(cause); } /** * Constructs a new exception with the specified detail message and cause. * * <p>Note that the detail message associated with cause is not automatically incorporated in this * exception's detail message. * * @param message the detail message (which is saved for later retrieval by the {@link * Throwable#getMessage()} method). * @param cause the cause (which is saved for later retrieval by the {@link Throwable#getCause()} * method). (A <tt>null</tt> value is permitted, and indicates that the cause is nonexistent * or unknown.) */ /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure public ParseException(final String message, final Throwable cause) { super(message, cause); } }
869
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/exception/UnsupportedProviderException.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.exception; import com.amazonaws.encryptionsdk.MasterKeyProvider; /** * This exception is thrown when there are no {@link MasterKeyProvider}s which which support the * requested {@code provider} value. */ // @ non_null_by_default public class UnsupportedProviderException extends AwsCryptoException { private static final long serialVersionUID = -1L; /*@ public normal_behavior @ ensures standardThrowable(); @*/ // @ pure public UnsupportedProviderException() {} /*@ public normal_behavior @ ensures standardThrowable(message); @*/ // @ pure public UnsupportedProviderException(final String message) { super(message); } /*@ public normal_behavior @ ensures standardThrowable(cause); @*/ // @ pure public UnsupportedProviderException(final Throwable cause) { super(cause); } /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure public UnsupportedProviderException(final String message, final Throwable cause) { super(message, cause); } /*@ public normal_behavior @ ensures standardThrowable(message,cause); @*/ // @ pure // TODO public UnsupportedProviderException( final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
870
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/exception/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 various exceptions which may be thrown by the AWS Encryption SDK. */ package com.amazonaws.encryptionsdk.exception;
871
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/LCS_FORMED_CONSECUTIVE_SEGMENTS_LEAST_LENGTH_K.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LCS_FORMED_CONSECUTIVE_SEGMENTS_LEAST_LENGTH_K{ static int f_gold ( int k , String s1 , String s2 ) { int n = s1 . length ( ) ; int m = s2 . length ( ) ; int lcs [ ] [ ] = new int [ n + 1 ] [ m + 1 ] ; int cnt [ ] [ ] = new int [ n + 1 ] [ m + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { lcs [ i ] [ j ] = Math . max ( lcs [ i - 1 ] [ j ] , lcs [ i ] [ j - 1 ] ) ; if ( s1 . charAt ( i - 1 ) == s2 . charAt ( j - 1 ) ) cnt [ i ] [ j ] = cnt [ i - 1 ] [ j - 1 ] + 1 ; if ( cnt [ i ] [ j ] >= k ) { for ( int a = k ; a <= cnt [ i ] [ j ] ; a ++ ) lcs [ i ] [ j ] = Math . max ( lcs [ i ] [ j ] , lcs [ i - a ] [ j - a ] + a ) ; } } } return lcs [ n ] [ m ] ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(4); param0.add(2); param0.add(3); param0.add(5); param0.add(2); param0.add(3); param0.add(3); param0.add(1); param0.add(2); param0.add(2); List<String> param1 = new ArrayList<>(); param1.add("aggayxysdfa"); param1.add("55571659965107"); param1.add("01011011100"); param1.add("aggasdfa"); param1.add("5710246551"); param1.add("0100010"); param1.add("aabcaaaa"); param1.add("1219"); param1.add("111000011"); param1.add("wiC oD"); List<String> param2 = new ArrayList<>(); param2.add("aggajxaaasdfa"); param2.add("390286654154"); param2.add("0000110001000"); param2.add("aggajasdfaxy"); param2.add("79032504084062"); param2.add("10100000"); param2.add("baaabcd"); param2.add("3337119582"); param2.add("011"); param2.add("csiuGOUwE"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
872
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/COUNT_CHARACTERS_STRING_DISTANCE_ENGLISH_ALPHABETS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_CHARACTERS_STRING_DISTANCE_ENGLISH_ALPHABETS{ static int f_gold ( String str ) { int result = 0 ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( Math . abs ( str . charAt ( i ) - str . charAt ( j ) ) == Math . abs ( i - j ) ) result ++ ; return result ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("smnKL"); param0.add("270083"); param0.add("0"); param0.add("kcZdsz"); param0.add("483544224"); param0.add("000011"); param0.add("WysGCirMwKBzP"); param0.add("3366"); param0.add("110"); param0.add("NlaMkpCjUgg"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
873
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/RECURSIVE_PROGRAM_PRIME_NUMBER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class RECURSIVE_PROGRAM_PRIME_NUMBER{ static boolean f_gold ( int n , int i ) { if ( n <= 2 ) return ( n == 2 ) ? true : false ; if ( n % i == 0 ) return false ; if ( i * i > n ) return true ; return f_gold ( n , i + 1 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(3); param0.add(7); param0.add(89); param0.add(97); param0.add(41); param0.add(73); param0.add(95); param0.add(69); param0.add(20); param0.add(30); List<Integer> param1 = new ArrayList<>(); param1.add(2); param1.add(2); param1.add(2); param1.add(2); param1.add(2); param1.add(2); param1.add(2); param1.add(2); param1.add(2); param1.add(2); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
874
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/COUNT_DISTINCT_OCCURRENCES_AS_A_SUBSEQUENCE.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_DISTINCT_OCCURRENCES_AS_A_SUBSEQUENCE{ static int f_gold ( String S , String T ) { int m = T . length ( ) ; int n = S . length ( ) ; if ( m > n ) return 0 ; int mat [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 1 ; i <= m ; i ++ ) mat [ i ] [ 0 ] = 0 ; for ( int j = 0 ; j <= n ; j ++ ) mat [ 0 ] [ j ] = 1 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( T . charAt ( i - 1 ) != S . charAt ( j - 1 ) ) mat [ i ] [ j ] = mat [ i ] [ j - 1 ] ; else mat [ i ] [ j ] = mat [ i ] [ j - 1 ] + mat [ i - 1 ] [ j - 1 ] ; } } return mat [ m ] [ n ] ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("banana"); param0.add("49597223"); param0.add("1000010000011"); param0.add("BTlzufK"); param0.add("3474007"); param0.add("0010"); param0.add("dKHhoTD"); param0.add("9123259723"); param0.add("11001000111110"); param0.add("iY WJlIZ"); List<String> param1 = new ArrayList<>(); param1.add("ban"); param1.add("42"); param1.add("010"); param1.add("lf RS"); param1.add("370"); param1.add("00000"); param1.add("doT"); param1.add("123"); param1.add("0"); param1.add("iI"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
875
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/CHECK_WHETHER_TWO_STRINGS_ARE_ANAGRAM_OF_EACH_OTHER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_WHETHER_TWO_STRINGS_ARE_ANAGRAM_OF_EACH_OTHER{ static boolean f_gold ( char [ ] str1 , char [ ] str2 ) { int n1 = str1 . length ; int n2 = str2 . length ; if ( n1 != n2 ) return false ; Arrays . sort ( str1 ) ; Arrays . sort ( str2 ) ; for ( int i = 0 ; i < n1 ; i ++ ) if ( str1 [ i ] != str2 [ i ] ) return false ; return true ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("LISTEN"); param0.add("TRIANGLE"); param0.add("test"); param0.add("night"); param0.add("Inch"); param0.add("Dusty"); param0.add("GJLMOOSTTXaabceefgllpwz"); param0.add("41658699122772743330"); param0.add("0000000000000000000000001111111111111111111"); param0.add("ERioPYDqgTSz bVCW"); List<String> param1 = new ArrayList<>(); param1.add("SILENT"); param1.add("INTEGRAL"); param1.add("ttew"); param1.add("thing"); param1.add("Study"); param1.add("1"); param1.add("EJRXYajoy"); param1.add("9931020"); param1.add("0000000000000000000001111111111111111111111"); param1.add("GLajZE"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i).toCharArray(),param1.get(i).toCharArray()) == f_gold(param0.get(i).toCharArray(),param1.get(i).toCharArray())) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
876
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/COUNT_NUMBERS_CAN_CONSTRUCTED_USING_TWO_NUMBERS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_NUMBERS_CAN_CONSTRUCTED_USING_TWO_NUMBERS{ static int f_gold ( int n , int x , int y ) { boolean [ ] arr = new boolean [ n + 1 ] ; if ( x <= n ) arr [ x ] = true ; if ( y <= n ) arr [ y ] = true ; int result = 0 ; for ( int i = Math . min ( x , y ) ; i <= n ; i ++ ) { if ( arr [ i ] ) { if ( i + x <= n ) arr [ i + x ] = true ; if ( i + y <= n ) arr [ i + y ] = true ; result ++ ; } } return result ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(23); param0.add(56); param0.add(30); param0.add(51); param0.add(21); param0.add(69); param0.add(12); param0.add(44); param0.add(99); param0.add(46); List<Integer> param1 = new ArrayList<>(); param1.add(16); param1.add(95); param1.add(63); param1.add(89); param1.add(99); param1.add(63); param1.add(69); param1.add(52); param1.add(65); param1.add(58); List<Integer> param2 = new ArrayList<>(); param2.add(16); param2.add(6); param2.add(1); param2.add(46); param2.add(38); param2.add(50); param2.add(73); param2.add(9); param2.add(10); param2.add(37); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
877
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/SUM_PAIRWISE_PRODUCTS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class SUM_PAIRWISE_PRODUCTS{ static int f_gold ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= n ; j ++ ) sum = sum + i * j ; return sum ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(21); param0.add(32); param0.add(16); param0.add(38); param0.add(9); param0.add(3); param0.add(5); param0.add(46); param0.add(45); param0.add(87); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
878
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/COUNT_SET_BITS_IN_AN_INTEGER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class COUNT_SET_BITS_IN_AN_INTEGER{ static int f_gold ( int n ) { int count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(58); param0.add(92); param0.add(73); param0.add(52); param0.add(24); param0.add(14); param0.add(58); param0.add(11); param0.add(8); param0.add(52); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
879
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/LONGEST_PALINDROME_SUBSEQUENCE_SPACE.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LONGEST_PALINDROME_SUBSEQUENCE_SPACE{ static int f_gold ( String s ) { int n = s . length ( ) ; int a [ ] = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int back_up = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( j == i ) a [ j ] = 1 ; else if ( s . charAt ( i ) == s . charAt ( j ) ) { int temp = a [ j ] ; a [ j ] = back_up + 2 ; back_up = temp ; } else { back_up = a [ j ] ; a [ j ] = Math . max ( a [ j - 1 ] , a [ j ] ) ; } } } return a [ n - 1 ] ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add(" E"); param0.add("0845591950"); param0.add("00101011"); param0.add("pLSvlwrACvFaoT"); param0.add("7246"); param0.add("1010101100000"); param0.add("obPkcLSFp"); param0.add("914757557818"); param0.add("1"); param0.add("PKvUWIQ"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
880
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/LONGEST_EVEN_LENGTH_SUBSTRING_SUM_FIRST_SECOND_HALF.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LONGEST_EVEN_LENGTH_SUBSTRING_SUM_FIRST_SECOND_HALF{ static int f_gold ( String str ) { int n = str . length ( ) ; int maxlen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j += 2 ) { int length = j - i + 1 ; int leftsum = 0 , rightsum = 0 ; for ( int k = 0 ; k < length / 2 ; k ++ ) { leftsum += ( str . charAt ( i + k ) - '0' ) ; rightsum += ( str . charAt ( i + k + length / 2 ) - '0' ) ; } if ( leftsum == rightsum && maxlen < length ) maxlen = length ; } } return maxlen ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("yQHVDWxcfsazM"); param0.add("7889372253"); param0.add("00"); param0.add("N"); param0.add("178791892313"); param0.add("110111101111"); param0.add("Ba"); param0.add("320901509"); param0.add("11"); param0.add(" HCUbvi"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
881
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/DYCK_PATH.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class DYCK_PATH{ public static int f_gold ( int n ) { int res = 1 ; for ( int i = 0 ; i < n ; ++ i ) { res *= ( 2 * n - i ) ; res /= ( i + 1 ) ; } return res / ( n + 1 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(72); param0.add(90); param0.add(61); param0.add(28); param0.add(70); param0.add(13); param0.add(7); param0.add(98); param0.add(99); param0.add(67); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
882
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/PRINT_A_CLOSEST_STRING_THAT_DOES_NOT_CONTAIN_ADJACENT_DUPLICATES.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class PRINT_A_CLOSEST_STRING_THAT_DOES_NOT_CONTAIN_ADJACENT_DUPLICATES{ public static String f_gold ( String s1 ) { int n = s1 . length ( ) ; char [ ] s = s1 . toCharArray ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { s [ i ] = 'a' ; while ( s [ i ] == s [ i - 1 ] || ( i + 1 < n && s [ i ] == s [ i + 1 ] ) ) s [ i ] ++ ; i ++ ; } } return ( new String ( s ) ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("cHcZCdkbIMGUYe"); param0.add("2292016725711"); param0.add("10110111100010"); param0.add("wHso xGbBY"); param0.add("21884"); param0.add("0"); param0.add("I"); param0.add("716213436"); param0.add("101"); param0.add("HXdDbjcyPc"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)).equals(f_gold(param0.get(i)))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
883
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/OVERLAPPING_SUM_TWO_ARRAY.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class OVERLAPPING_SUM_TWO_ARRAY{ static int f_gold ( int [ ] A , int [ ] B , int n ) { HashMap < Integer , Integer > hash = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash . containsKey ( A [ i ] ) ) hash . put ( A [ i ] , 1 + hash . get ( A [ i ] ) ) ; else hash . put ( A [ i ] , 1 ) ; if ( hash . containsKey ( B [ i ] ) ) hash . put ( B [ i ] , 1 + hash . get ( B [ i ] ) ) ; else hash . put ( B [ i ] , 1 ) ; } int sum = 0 ; for ( Map . Entry entry : hash . entrySet ( ) ) { if ( Integer . parseInt ( ( entry . getValue ( ) ) . toString ( ) ) == 1 ) sum += Integer . parseInt ( ( entry . getKey ( ) ) . toString ( ) ) ; } return sum ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{13,31,63,75,90,92,94,98}); param0.add(new int[]{-20}); param0.add(new int[]{0,0,0,1,1,1}); param0.add(new int[]{47,71,9,64,66,99,7,44,75,84,88,49,95,56,3,90,73,2}); param0.add(new int[]{-76,-72,-70,-60,-44,-38,-38,-26,-16,-10,-4,-2,4,18,30,38,54,56,64,66,68,70,72,82,84}); param0.add(new int[]{0,0,0,0,0,1,1,0,1,0,0,0,0,0,1,1,0,1,0,0,1,0,0,1,1,1}); param0.add(new int[]{3,4,4,6,11,13,14,18,30,30,34,39,40,45,46,50,51,56,60,61,66,68,72,79,79,82,83,87,89,91,91,92,92,93,94}); param0.add(new int[]{-14,12,98,34,58,-70,6,52,-50,96,-6}); param0.add(new int[]{0,0,0,1,1,1,1,1}); param0.add(new int[]{34,85,60,55,38,69,21,43,39,83,10,71,73,15,94,59,83,39,29,31,61,9,11,27,71,90,18,11,4,3,97,43,58,50,35,42,70,33,98,61,32,32,12,29}); List<int [ ]> param1 = new ArrayList<>(); param1.add(new int[]{14,16,20,28,32,55,56,56}); param1.add(new int[]{60}); param1.add(new int[]{0,0,1,1,1,1}); param1.add(new int[]{8,27,21,40,99,8,52,37,72,50,61,82,88,71,27,84,38,35}); param1.add(new int[]{-80,-64,-50,-44,-34,-26,-24,-22,-6,-2,2,2,12,24,34,44,48,50,52,70,76,82,86,94,96}); param1.add(new int[]{0,0,0,1,1,0,1,0,0,1,1,1,0,0,1,0,0,1,1,0,0,0,1,1,0,0}); param1.add(new int[]{3,7,15,15,21,23,30,32,35,38,38,41,41,41,44,45,49,52,60,60,63,66,66,70,72,74,74,75,79,81,87,88,89,93,96}); param1.add(new int[]{50,-22,-82,40,-80,30,-58,-64,60,6,-28}); param1.add(new int[]{0,0,1,1,1,1,1,1}); param1.add(new int[]{74,10,95,67,59,17,32,87,87,12,22,45,50,35,25,51,10,86,75,4,74,43,92,63,60,28,32,72,66,61,43,48,20,89,55,59,22,85,73,43,7,65,53,98}); List<Integer> param2 = new ArrayList<>(); param2.add(6); param2.add(0); param2.add(5); param2.add(16); param2.add(16); param2.add(17); param2.add(22); param2.add(9); param2.add(5); param2.add(34); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
884
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/MOBILE_NUMERIC_KEYPAD_PROBLEM.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class MOBILE_NUMERIC_KEYPAD_PROBLEM{ static int f_gold ( char keypad [ ] [ ] , int n ) { if ( keypad == null || n <= 0 ) return 0 ; if ( n == 1 ) return 10 ; int [ ] odd = new int [ 10 ] ; int [ ] even = new int [ 10 ] ; int i = 0 , j = 0 , useOdd = 0 , totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) odd [ i ] = 1 ; for ( j = 2 ; j <= n ; j ++ ) { useOdd = 1 - useOdd ; if ( useOdd == 1 ) { even [ 0 ] = odd [ 0 ] + odd [ 8 ] ; even [ 1 ] = odd [ 1 ] + odd [ 2 ] + odd [ 4 ] ; even [ 2 ] = odd [ 2 ] + odd [ 1 ] + odd [ 3 ] + odd [ 5 ] ; even [ 3 ] = odd [ 3 ] + odd [ 2 ] + odd [ 6 ] ; even [ 4 ] = odd [ 4 ] + odd [ 1 ] + odd [ 5 ] + odd [ 7 ] ; even [ 5 ] = odd [ 5 ] + odd [ 2 ] + odd [ 4 ] + odd [ 8 ] + odd [ 6 ] ; even [ 6 ] = odd [ 6 ] + odd [ 3 ] + odd [ 5 ] + odd [ 9 ] ; even [ 7 ] = odd [ 7 ] + odd [ 4 ] + odd [ 8 ] ; even [ 8 ] = odd [ 8 ] + odd [ 0 ] + odd [ 5 ] + odd [ 7 ] + odd [ 9 ] ; even [ 9 ] = odd [ 9 ] + odd [ 6 ] + odd [ 8 ] ; } else { odd [ 0 ] = even [ 0 ] + even [ 8 ] ; odd [ 1 ] = even [ 1 ] + even [ 2 ] + even [ 4 ] ; odd [ 2 ] = even [ 2 ] + even [ 1 ] + even [ 3 ] + even [ 5 ] ; odd [ 3 ] = even [ 3 ] + even [ 2 ] + even [ 6 ] ; odd [ 4 ] = even [ 4 ] + even [ 1 ] + even [ 5 ] + even [ 7 ] ; odd [ 5 ] = even [ 5 ] + even [ 2 ] + even [ 4 ] + even [ 8 ] + even [ 6 ] ; odd [ 6 ] = even [ 6 ] + even [ 3 ] + even [ 5 ] + even [ 9 ] ; odd [ 7 ] = even [ 7 ] + even [ 4 ] + even [ 8 ] ; odd [ 8 ] = even [ 8 ] + even [ 0 ] + even [ 5 ] + even [ 7 ] + even [ 9 ] ; odd [ 9 ] = even [ 9 ] + even [ 6 ] + even [ 8 ] ; } } totalCount = 0 ; if ( useOdd == 1 ) { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += even [ i ] ; } else { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += odd [ i ] ; } return totalCount ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<char [ ] [ ]> param0 = new ArrayList<>(); param0.add(new char[][]{new char[]{' ','A','C','K','R','R','V','c','d','i','i','j','m','o','q','q','r','r','v','v','x','z'},new char[]{'B','D','I','M','N','Q','R','Z','c','f','i','j','j','l','l','n','p','q','s','t','t','w'},new char[]{'A','F','F','G','H','J','K','K','N','V','V','b','c','c','g','i','j','l','l','s','t','y'},new char[]{' ','A','B','B','E','H','I','J','J','P','Q','T','U','V','Z','c','c','j','p','w','y','z'},new char[]{' ',' ','A','C','F','G','H','M','N','R','R','V','c','i','j','o','p','p','q','r','w','y'},new char[]{' ',' ','C','C','D','H','I','J','K','O','S','X','Y','f','h','h','o','p','p','u','u','w'},new char[]{'B','C','D','H','M','M','Q','Q','R','S','X','Z','e','e','e','j','k','l','m','o','v','w'},new char[]{'A','C','C','D','H','H','I','J','L','L','L','M','N','S','U','c','d','f','f','s','u','y'},new char[]{'A','B','D','D','I','J','K','L','L','M','P','S','S','Y','b','e','h','j','m','o','q','s'},new char[]{' ','B','E','H','H','J','M','P','S','T','U','V','Z','d','j','m','m','p','q','v','w','w'},new char[]{'B','E','F','G','H','M','M','M','N','O','Q','R','T','V','a','c','g','g','i','s','x','y'},new char[]{'A','E','G','J','O','R','R','S','T','W','a','b','f','h','h','i','m','n','s','u','v','y'},new char[]{'B','D','E','H','I','I','K','M','N','P','Q','S','a','e','i','j','m','o','p','r','x','z'},new char[]{'A','G','I','K','K','L','O','P','U','U','X','X','Z','a','c','f','g','i','l','o','o','v'},new char[]{' ',' ','E','H','J','J','L','M','N','O','P','S','S','X','c','f','g','r','u','v','x','z'},new char[]{'C','E','F','F','H','H','I','K','M','M','U','Z','e','e','h','h','h','j','k','k','p','r'},new char[]{' ',' ',' ','C','G','I','J','O','O','P','T','V','Y','b','j','n','o','o','s','u','w','x'},new char[]{'A','D','F','F','H','H','N','R','S','W','W','Y','Y','b','f','i','k','o','u','y','y','z'},new char[]{' ','C','G','I','I','L','P','S','X','Y','d','d','f','g','g','k','m','o','r','r','r','x'},new char[]{'F','I','J','N','P','P','Q','Q','R','X','Y','a','b','h','h','j','l','m','n','p','r','y'},new char[]{' ','C','D','E','F','L','Q','Q','V','c','g','h','k','k','l','l','n','o','p','r','u','x'},new char[]{' ','A','G','K','L','M','T','U','U','W','Z','a','f','i','k','k','n','n','p','q','v','z'}}); param0.add(new char[][]{new char[]{'3','5','1','5','6','7','7','3','0','4','7','6','1','4','0','6','3','4','1','3','1','2','9','8','7','8','0','2','7','6','1','0','3','8','0','5','9','3','9','9','8','6'},new char[]{'0','3','8','5','0','2','0','6','1','8','7','2','8','6','0','3','9','4','9','5','7','4','3','7','4','3','8','6','1','5','4','8','0','8','3','2','7','7','6','9','7','9'},new char[]{'6','7','1','1','7','2','5','3','2','8','4','7','8','6','1','5','2','1','6','5','7','6','8','6','8','8','1','6','3','1','1','7','1','6','4','9','2','8','2','6','3','4'},new char[]{'8','7','9','2','0','6','6','6','2','3','1','4','8','2','3','5','5','9','2','8','0','3','2','7','2','0','2','7','0','6','5','8','2','9','3','9','8','1','9','7','9','7'},new char[]{'9','8','1','5','0','9','9','7','7','8','4','1','8','0','4','6','7','0','5','8','6','5','6','5','1','4','0','4','3','4','6','7','6','7','3','5','4','5','6','7','1','1'},new char[]{'4','4','4','9','8','8','7','5','3','1','8','4','8','1','0','4','9','8','9','5','2','7','5','3','4','8','2','4','7','5','0','3','6','2','5','6','3','1','9','4','8','9'},new char[]{'7','2','7','6','2','8','8','8','1','1','5','4','6','5','3','0','3','7','4','0','0','2','4','1','8','0','0','7','6','4','7','1','8','8','1','8','8','2','3','1','7','2'},new char[]{'2','7','5','8','7','6','2','9','9','0','6','1','7','8','1','3','3','1','5','7','9','8','2','0','7','6','0','0','1','1','5','8','6','7','7','9','9','0','4','4','3','4'},new char[]{'0','9','9','0','5','4','9','9','3','0','3','1','5','9','9','5','3','0','2','3','9','9','7','8','5','4','6','4','2','8','7','0','2','3','6','5','2','6','0','6','5','7'},new char[]{'1','1','4','1','4','2','7','1','9','7','9','9','4','4','2','7','6','8','2','6','7','3','1','8','0','5','3','0','3','9','0','4','7','9','6','8','1','7','0','3','2','4'},new char[]{'6','3','1','3','2','9','5','5','4','7','2','4','7','6','9','2','0','1','2','1','4','3','8','4','9','8','9','7','7','6','8','2','4','5','3','0','1','3','0','1','0','9'},new char[]{'5','9','4','2','1','5','0','2','6','6','0','8','3','0','3','3','3','0','7','8','0','7','7','4','3','0','6','9','6','2','2','2','8','3','7','2','4','0','0','4','5','2'},new char[]{'3','1','1','6','2','9','7','0','3','2','8','0','5','2','2','9','9','2','8','3','5','7','4','2','8','7','8','0','4','9','7','8','0','3','2','2','1','5','1','4','9','1'},new char[]{'6','4','8','2','4','2','5','4','0','1','0','9','0','3','0','6','4','8','6','7','9','3','0','1','6','9','5','7','5','2','9','4','7','0','6','4','1','4','4','1','3','5'},new char[]{'6','7','8','2','9','5','0','2','6','5','4','9','4','7','8','4','6','7','6','5','1','3','8','1','7','5','9','3','9','4','0','6','5','6','9','8','4','6','9','9','0','2'},new char[]{'6','9','2','4','3','7','2','5','8','6','3','6','3','6','7','2','6','8','6','4','3','9','6','2','1','3','1','8','8','9','6','2','0','2','2','9','3','6','4','4','8','7'},new char[]{'1','4','5','5','7','2','3','8','3','6','9','3','3','4','4','2','3','7','5','5','2','8','7','2','7','6','0','5','1','4','1','5','5','0','4','8','7','8','1','4','2','6'},new char[]{'5','6','8','0','0','6','3','8','3','8','2','0','8','5','4','4','0','0','8','5','8','9','1','3','3','1','1','2','9','9','1','2','1','3','5','8','7','9','3','1','3','5'},new char[]{'9','6','7','4','9','0','2','8','9','4','3','6','4','1','8','3','1','8','0','4','4','2','1','2','9','8','3','6','7','3','9','5','7','9','1','4','6','1','4','5','4','0'},new char[]{'5','7','4','0','6','7','8','3','6','5','8','1','4','9','9','2','7','7','4','2','8','0','8','3','2','7','3','5','7','4','4','1','3','5','1','9','6','1','0','9','5','4'},new char[]{'3','4','0','0','3','2','2','2','9','7','5','5','1','8','4','7','9','0','7','4','1','9','3','7','3','9','5','0','3','6','6','8','8','4','1','8','2','3','9','5','3','3'},new char[]{'7','0','6','2','5','2','1','8','1','4','4','8','9','0','3','0','3','1','9','0','8','0','1','0','3','7','6','6','3','9','4','3','4','4','1','4','7','2','9','5','8','3'},new char[]{'7','5','7','9','8','8','3','4','3','2','5','2','4','6','5','6','1','6','0','4','9','6','8','0','3','3','2','1','1','8','9','5','3','8','3','0','4','7','7','9','2','6'},new char[]{'6','3','9','7','5','8','5','1','1','6','6','0','8','3','2','7','3','0','4','5','1','2','3','0','4','2','8','4','1','1','0','2','3','2','5','6','3','0','1','2','2','5'},new char[]{'8','7','2','1','4','9','6','5','2','0','9','1','0','8','6','9','7','3','4','5','6','7','2','8','3','0','1','9','5','4','4','1','6','4','0','5','1','5','7','8','2','4'},new char[]{'4','8','1','1','7','0','8','0','2','1','8','2','2','7','6','2','3','5','2','5','5','5','9','3','4','9','4','9','8','8','0','1','6','7','7','5','7','5','9','3','6','1'},new char[]{'5','8','6','8','0','7','3','1','9','2','3','5','5','5','0','9','2','2','2','8','7','7','6','7','6','7','4','3','9','8','3','9','3','5','7','1','3','1','4','0','7','1'},new char[]{'9','2','6','8','8','6','8','4','8','6','7','7','7','0','2','6','5','1','5','3','8','0','5','6','5','4','9','4','6','0','0','7','2','2','1','1','0','5','1','2','5','1'},new char[]{'1','8','4','3','2','6','1','8','3','6','5','5','1','5','9','8','0','2','8','9','4','2','1','9','6','5','1','2','5','4','6','7','3','8','7','3','2','4','7','6','6','0'},new char[]{'9','2','9','7','5','6','4','9','5','4','8','5','2','4','0','5','5','1','0','9','3','6','4','0','9','4','2','7','5','1','3','4','8','3','7','4','2','8','3','0','2','8'},new char[]{'8','4','4','7','5','7','3','2','8','9','5','5','2','3','8','3','3','8','0','4','9','5','9','8','5','9','1','9','4','3','9','7','4','3','0','9','3','1','3','1','3','9'},new char[]{'9','3','7','7','4','9','1','1','8','9','2','1','2','4','1','0','9','2','8','8','9','7','2','6','0','4','3','6','2','1','4','7','6','2','4','0','8','5','1','6','2','1'},new char[]{'6','8','7','3','6','4','3','9','3','7','1','5','0','5','5','1','7','9','3','9','8','9','9','6','6','3','1','2','2','2','0','7','8','4','7','3','6','2','2','1','9','6'},new char[]{'1','3','1','5','7','5','2','5','3','4','0','7','6','8','5','9','7','1','0','3','3','8','2','9','7','2','4','8','6','3','1','3','3','0','7','1','5','9','0','9','8','1'},new char[]{'4','1','6','2','2','3','9','7','6','5','6','5','3','0','8','4','3','0','6','8','7','4','1','4','2','3','2','2','1','0','0','5','3','4','0','8','4','8','4','9','0','0'},new char[]{'2','1','1','4','8','0','6','9','7','0','9','4','7','6','1','1','5','2','0','6','9','2','0','2','7','3','3','0','5','2','6','3','0','1','8','3','5','5','3','9','8','5'},new char[]{'1','3','2','8','8','7','7','2','6','3','8','8','5','6','7','0','1','7','7','8','5','1','9','5','2','5','7','2','2','5','9','6','0','3','1','2','2','2','3','0','1','9'},new char[]{'2','5','0','6','4','0','1','6','9','7','0','6','7','4','9','1','0','2','5','5','7','0','2','0','8','0','6','2','6','8','1','1','0','6','4','4','0','6','5','8','7','3'},new char[]{'9','7','8','6','0','3','7','5','7','5','6','0','5','6','3','9','6','3','2','6','0','0','6','5','8','3','7','3','7','3','5','2','4','9','4','1','0','7','9','7','6','2'},new char[]{'3','0','7','5','1','4','8','7','9','9','0','7','6','8','6','0','5','8','0','8','9','4','8','1','3','1','8','6','0','5','1','7','3','4','7','6','4','2','8','6','1','7'},new char[]{'4','2','8','1','1','3','2','6','5','1','9','1','2','8','8','8','2','6','2','5','6','0','7','5','2','0','9','3','0','1','4','1','1','0','0','3','9','3','4','8','8','3'},new char[]{'9','1','9','0','9','4','0','8','4','9','7','6','7','6','0','7','1','1','7','4','9','0','0','7','3','2','8','1','6','9','7','2','0','1','6','1','9','8','9','7','5','3'}}); param0.add(new char[][]{new char[]{'0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','1','1','1','1','1'}}); param0.add(new char[][]{new char[]{'b','q','b','D','t','y','Z','G','d','r','R','R','z','A','Y','H','D','Q','X','U','o','a','S','P','S','c','W','r','I','y','E','x','E','k','l','F','M','G','z','T','I','E','D','K','M','l'},new char[]{'V','m','W','M','l','H','l','j','f','S','k','g','O','W','S','R','I','L','J','Z','V','X','w','l','K','s','F','o','X','k','a','L','K','H',' ','E','x','b','Z','w','Z','Y','U','y','I','Q'},new char[]{'I','o','s','A','f','Z','C','o','X','b','d','s',' ','Y','Q','U','C','T','K','r','Q','U','P','C','w','R','e','s','L','A','j','g','p','B','I','W','L','e','w','b','R','z','Y','M','M','E'},new char[]{'k','Y','v','L','f','x','v','l','C','g','J','V','l','q','p','x','z','A','J','h','V','i','h','r','Z','i',' ','y','M','k','p','q','X','M','U','W','v','v','P','L','n','j','r','O','k',' '},new char[]{'K','k','K','Z','X','W','e',' ','x','u','r','l','l','z','V','e','K','z','y','x','f','v','n','f','K','p','b','I','C','p','b','V','R','t','n','t','m','A','F','J','U','M','n','g','M','W'},new char[]{'a','e','x','A','U','V','P','W','W','l','p',' ','o','L','X','E','g','k','Y','W','P','Y','B','t','Z','m','V','Z','O','z','o','O','m','s','x','O','L','q','Z','E','y','B','l','h','h','T'},new char[]{'c','x','R','R','x','S','R','y','J','Y','e','F','X','x','h','L','N','Q','j','X','s','H','Z','M','Q','b','Q','h','x','R','Y','C','r','D','b','O','l','W','J','I','A','P','x','D','T','c'},new char[]{'Y','s','B','N','B','g','e','h','l','y','N','s','a','f','k','p','C','Q','c','U','A','N','w','V','z','F','j','M','F','g','q','x','r','l','e','Y','T','z',' ','a','n','n','x','p','m','J'},new char[]{'v','O','a','A','E','q','L','P',' ','w','l','G','k','f','M','A','k','i','f','D','z','A','J','Y','b','g','a','h','e','S','Q','H','c','f','I','S','X','Y','J','g','f','n','G','J','r','S'},new char[]{' ','S','w','G','b','v','z','U','l','k','a','w','y','D','Q','v','c','T','S','S','n','M','m','j','U','X','a','k','O','A','T','a','U','u','y','s','W','j','k','n','a','V','X','N','D','C'},new char[]{'Z','o','O','a','z','M','X','k','m','X','J','w','y','d','j','c','Q','E','E','i','g','q','U','v','C','k','y','t','T','A','o','u','o','e','J','c','c','d','i','o','b','A','h','g','y','Y'},new char[]{'O','j','F','A','f','t','J','u','V','J','P','Z','C','c','c','y','G','s','W','X','O','g','q','l','z','L','p','U','o','A','k','v','q','v','I','W','k','r','m','Y','i','V','Y','c','P','S'},new char[]{'N',' ','W','k','z','o','V','w','M','a','q','c','P','D','x','O','M','y',' ','B','y','L','V','E','j','i','C','k',' ',' ','c','K','c','h','y','K','c','G','Q','h','B','i','L','Q','P','s'},new char[]{'X','p','y','I','W','F','F','o','W','g','A','H','a','H','X','F','d','Y','I','x','n','r','s','c','B','L','o','B','C','o','G','v','T','q','A','Z','a','Z','d','S','B','S','F','I','m','C'},new char[]{'F','t','c','w','E','X','s','F','e','J','h','Y','f','g','d','f','N','X','G','l','n','M','L','k','P','Y','M',' ','U','X','n','s','o','F','R','g','E','I','G','P','x','f','h','K','b','k'},new char[]{'a','p','j','Q','X','p','h','R','g','U','O','x','X','k','v','m','o','E','Z','Z','W','v','k','l','o','O','N','P','Q','k','A','K','c','l','w','a','k','Z','d','T','S','t','K','L','x','k'},new char[]{'t','f','V','Q','X','e','s','f','o','N','U','z','y','K','F',' ','A','V','W','A','j','C','T','G','z','K','j',' ','I','w','h','Q','t','I','m','V','h','M','L','Q','J','g','p','x','P','i'},new char[]{'X','Q','b','i','T','A','R','f','c','r','K','t','J','E','Z','d','W','O','G','X','u','I','z',' ','m','H','s','P','d','s','k','m','E','K','Y','H','L','b','Z','y','I','c','p','y','Y','T'},new char[]{'P','g','C','T','i','Z','s','s','r','E','L','P','T','o','r','g','x','c','U','b','o','l','H','H','k','b','N','e','S','E','U','c','g','V','E','V','l','L',' ','I','h','M','L','z','P','e'},new char[]{'l','i','O','F','S','e','Z','j','y','J','p','c','q','j','Q','E','j','d','u','S','N','Y','R',' ','F','I','f','u','d','t','u','Q','J','v','i','x','A','d','k','v','H','Z','B','u','o','k'},new char[]{'V','p','B','h','M','a','p','n','z','L','s','g','c','G','T','X','a','X','s','h','O','x','h','s','x','N',' ','O','w','F','v','M','W','u','c','Y','x','x','H','P','T','h','s','W','w','l'},new char[]{'B','f','k','U','j','b','X','J','z','y','w','B','n','f','x','N','Y','l','Q','h','t','v','U','y','I','G','q','T','a','i','N','p','e','Z','Y','Q','B','G','e','N','V','s','E','U','B','h'},new char[]{'q','Y','r','w','t','G','G','M','F',' ','e','u','E','g','s','D','c','h','L','G','x','u','V','j','u','U','i','m','Y','J','L','P','h','X','p','P','F','f','O','u','U','H','Y','I','A','X'},new char[]{'v',' ','W','A','e','t','Y','t','I','s','w','M',' ','E','R','K','x','i','O','w','h','e','f','N','i','N','v','q','F','u','A','c','e','s','p','N','j','G','q','W','q','U','J','b','V','i'},new char[]{'p','Y','p','f','I','N','S','C','J','p','O','O','s','V','s','Z','y','s','l','o','b','e','L','J','m','W','g','P','x','l','W','N','a','T','m','D','p','p','l','P','E','V','c','O','T','Z'},new char[]{'x',' ','v','X','T','s','i','A','J','q','H','P','x','q','Y','n','s','i','W','z','Y','q','a','Z','t','M','s','A','q','e','W','V','g','y','x','n','E','p','x','t','q','R','T','m','h','m'},new char[]{'M','u','D','R','R','h','B','f',' ','H','b','l','q','X','f','b','r','e','v','D','m','T','v','l','g','l','z','y','A','O','i','G','Q','l','K','G','H','G','S','b','a','b','k','p','g','R'},new char[]{'G','Q','P','e','P','r','K','U','l','g','X','q','I','O','U','y','V','Z','t','Q','g','d','T','J','q','w','z','L','V','p','e','X','x','D','k','R','P','U','L','z','a','L','L','Q','z','D'},new char[]{'j','W','Q','E','P','V','f','p','w','n','U','j','Z','P','f','v','R','r','h','z','r','l','T','P','U','f','v','A','B','k','b','n','o','h','j','K','h','r','f','q','x','E','U','g','d','C'},new char[]{'C','v','D',' ','K','d','d','D','d','f','U','F','l','x','E','D','Q','L','W','X','E','E','X','T','M','C','e','B','x','o','C','f','d','o','F','T','J','F','G','l','k','x','u','q','N','t'},new char[]{'l','d','P','k','N','w','t','C','u','n','f','Z','B','A','Z','z','z','v','Z','s','n','f','Y','c','s','j','e','M','E','i','N','Y','D','k','k','n','j','X','q','T','T','G','S','d','t','d'},new char[]{'c','c','G','d','y','T','E','w','k','R','d','N','S','M','L','p','H','F','C','L','n','l','C','M','L','u','k',' ','X','E','L','J','L','G','l','H','l','r','p','v','D','T','r','L','v','e'},new char[]{'t','A','s','J','M','b','P','a','p','G','q','p','i','d','b','C','S','w','c','N','m','A','C','m','f','T','P','z','U','L','o','V','N','M','G','h','V','h','U','S','I','N','f','H','L','f'},new char[]{'q','V','Z','j','s','c','T','n','U','l','E','V','c','s','J','n','q','b','c','h','e','x','H','G','k','U','P','U','T','W','n','t','p','i','b','u','b','H','s','D','L','Y','Z','u','P','w'},new char[]{'s','F','O','t','J','e','f','P','l','l','v','G','B','J','i','b','i','r','P','x','a','i','X','T','G','G','a','k','d','Z','L','Y','U','r','b','p','t','k','L','t','x','T','k','v','a','k'},new char[]{'c','s','B','Z','d','h','d','P','w','D','a','c','G','M','T','u','U','O','T','w','a','o','x','V','J','g','N','w','w','f','g','u','j','p','G','T','w','X','J','p','M','y','o','G','m','w'},new char[]{'w','j','K','u','K','d','N','I','w','E',' ','K','K','c','x','U','A','A','v','F','z','a','z','C','V','W','A','o','m','Z','i','U','F','e','p','w','O','A','T','u','a','P','l','y','w','J'},new char[]{'b','M','e','h','S','Q','c','G','D','A','I','H','g','f','E','j','x','u','P','p','p','d','V','F','D','L','L','g','H','h','n','Q','K','L','g','K','y','Y','u','A','g','W','t','J','X','F'},new char[]{'k','J','l','X','J','m','e','Y','d','Z','L','W','r','W','T','J','G','f',' ','s','j','j','P','h','k','x','k','k','B','N','j','h','s','o','b','m','u','O','i','D','c','B','a','h','B','Y'},new char[]{'L','l','R','Z','f','j','G','E','j','g','X','S','P','H','T','a','c','Y','b','r','N','N','R','n','d','j','H','M','X','A','V','G','c','r','l','v','F','e','z','k','z','Q','r','F','L','H'},new char[]{'U','o','Y','O','n','J','c','i','j','a','j','H','O','u','S','m','K','y','i','T','v','j',' ','v','H','f','r','q','F','a','l','u','F','E','p','b','V',' ','m','O','M','E','f','Q','t','T'},new char[]{' ','B','H','i','H','c','T',' ','K','u','d','C','F','F','S','v','Z','A','b','t','r','G','I','F','p','L','G','N','h','y','m','b','z','V','G','D','p','K','p','C','X','y','w','c','z','K'},new char[]{'P','q','o','M','T','U','o','r','A','h','S','q','T','s','V','u','c','N','v','E','r','X','k','v','M','p','Q','d','Y','Q','J','c','L','M','r','Z','D','k','V','u','G',' ','Y','O','i','x'},new char[]{'V','x','o','G','T','g','G','N','A','q','p','l','K','t','j','n','C','U','c','b','q','q','c','C','w','x','B','C','t','V','z','y','y','o','U','E','O','X','j','V','r','y','t','n','R','H'},new char[]{'Z','O','w','z','v','K','U','c','N','M','h','W','Y','Z','g','k','h','o','K','B','K','q','u','P','z','v','j','u','z','P','B','y','p','Y','U','W','Z','I','c','m','W','J','c','l',' ','O'},new char[]{'Q','A','B','Z','C','D','N','i','W','E','W','V','Z','k','A','D','z','Z','I','t','Y','K','u','T','u','q','p','V','P','y','o','e','Y','x','d','L','P','L','p','Z','E','N','r','c','K','Z'}}); param0.add(new char[][]{new char[]{'1','1','1','1','2','2','3','3','3','4','4','5','5','6','7','7','7','8','8','9','9'},new char[]{'0','0','1','1','1','2','3','4','5','6','6','6','6','6','6','6','7','7','8','8','9'},new char[]{'0','0','0','0','0','1','1','2','2','2','3','3','4','5','5','5','5','6','7','7','8'},new char[]{'0','1','1','2','2','2','2','2','3','3','4','4','5','5','6','6','7','7','7','9','9'},new char[]{'0','0','1','1','2','2','2','3','3','3','4','4','4','4','4','6','7','7','8','8','9'},new char[]{'0','0','0','0','1','1','2','3','3','3','3','4','4','4','5','7','8','8','8','9','9'},new char[]{'0','0','0','0','0','0','1','1','2','3','4','5','5','6','6','7','7','8','8','9','9'},new char[]{'0','2','2','2','4','4','4','4','4','5','5','5','6','6','7','7','7','8','8','9','9'},new char[]{'0','0','1','2','3','3','3','4','4','5','5','5','7','7','7','8','8','8','9','9','9'},new char[]{'0','0','1','2','2','3','4','4','4','4','4','5','6','6','6','7','8','8','9','9','9'},new char[]{'0','0','1','1','1','1','1','2','2','2','2','3','4','4','5','5','6','6','8','8','9'},new char[]{'0','0','1','2','2','2','3','3','5','5','5','6','7','7','7','7','7','8','8','9','9'},new char[]{'0','0','1','1','1','3','5','5','5','5','6','6','6','6','6','7','7','8','8','9','9'},new char[]{'0','0','1','2','2','2','2','2','2','3','3','5','5','5','6','7','8','8','9','9','9'},new char[]{'0','0','0','0','2','3','5','5','5','5','5','6','6','6','7','7','7','7','7','8','9'},new char[]{'0','0','1','2','2','3','3','3','4','4','4','5','5','5','6','6','6','7','7','8','9'},new char[]{'0','0','0','0','1','1','3','3','3','4','4','5','5','6','7','8','8','8','9','9','9'},new char[]{'0','0','1','1','1','1','1','2','2','3','5','5','6','6','6','7','7','7','7','8','8'},new char[]{'0','1','1','1','1','2','2','4','4','4','4','4','5','5','6','7','7','8','8','9','9'},new char[]{'1','1','2','2','3','3','4','5','5','5','5','6','6','7','7','7','8','8','8','9','9'},new char[]{'0','0','0','0','2','2','2','3','3','4','5','5','5','5','5','5','6','7','7','7','9'}}); param0.add(new char[][]{new char[]{'0','1','0','1','1','1','0','1','1','0','1','0','0','0','1','1','1','1','0','0','0','1','1','1','0','1','1','1','1','1','0','0','0','1','1','1','1','0','1'},new char[]{'1','0','0','0','1','0','1','1','0','0','0','0','1','0','0','0','1','1','0','0','0','1','0','0','1','0','1','1','1','1','0','0','0','0','0','0','0','1','0'},new char[]{'0','1','1','0','1','0','1','1','0','0','0','1','0','1','1','0','1','0','0','1','0','1','0','1','1','1','0','1','0','0','0','1','0','0','1','1','1','0','0'},new char[]{'0','1','1','0','0','1','1','1','0','0','0','1','1','1','1','1','0','1','0','1','1','0','0','0','1','1','0','0','1','1','1','1','0','0','0','0','1','1','0'},new char[]{'1','1','1','1','1','0','0','0','1','0','1','1','0','1','1','0','0','1','1','1','1','0','1','0','0','0','0','0','1','0','0','1','0','0','1','0','0','1','1'},new char[]{'1','0','1','0','0','1','1','1','1','0','1','1','0','0','0','0','1','0','0','1','0','1','0','1','1','1','1','0','0','1','0','0','1','1','0','1','0','1','0'},new char[]{'0','0','0','0','1','1','0','1','0','1','0','1','1','1','1','1','0','1','1','0','1','0','0','1','0','1','0','0','0','0','1','1','1','1','0','0','0','1','1'},new char[]{'1','0','0','1','1','1','1','0','0','0','1','0','0','1','0','0','0','0','1','0','1','0','0','0','0','1','1','0','1','1','0','1','0','0','0','0','1','0','0'},new char[]{'0','0','1','1','1','1','0','1','0','1','1','1','1','0','1','1','0','0','0','0','0','0','0','1','0','1','1','0','1','0','0','0','1','1','0','1','1','1','1'},new char[]{'1','0','0','1','1','0','1','1','0','0','0','1','1','0','1','0','1','0','0','0','0','1','1','1','0','1','1','0','0','1','0','0','0','1','1','0','1','0','0'},new char[]{'0','0','0','1','0','0','1','1','0','0','1','0','0','1','0','0','0','0','1','1','0','1','0','0','1','0','1','0','1','0','1','1','0','0','0','1','0','0','1'},new char[]{'1','0','0','1','0','0','0','0','1','1','1','0','1','1','1','0','0','0','0','0','0','1','0','1','0','1','0','1','1','1','1','0','1','0','1','1','0','1','0'},new char[]{'0','0','1','0','0','0','1','1','1','1','1','0','1','1','1','1','0','0','1','0','0','0','0','1','0','1','1','0','0','1','1','1','0','0','0','1','1','0','0'},new char[]{'0','1','0','1','0','0','0','0','1','1','1','1','0','0','0','0','1','1','1','0','0','0','0','0','0','1','0','1','1','1','1','0','0','1','0','0','0','0','0'},new char[]{'0','0','0','0','1','1','0','0','1','1','0','0','0','1','1','0','1','0','0','0','0','1','0','0','1','1','1','0','0','1','1','1','1','0','1','0','1','1','1'},new char[]{'1','1','0','1','1','0','0','0','0','0','0','1','0','1','0','0','0','1','1','0','1','1','0','0','1','0','0','1','0','0','0','0','1','0','1','0','1','0','1'},new char[]{'0','0','0','1','1','1','1','1','1','1','1','1','1','1','0','0','0','0','0','0','0','0','0','1','1','1','1','1','1','0','1','0','0','1','1','1','1','1','0'},new char[]{'1','1','0','1','1','1','0','0','1','1','0','0','1','0','1','1','0','1','1','0','0','1','1','0','0','1','0','0','0','0','0','1','0','0','0','1','0','1','1'},new char[]{'0','0','1','0','1','0','0','0','0','0','1','0','0','1','1','1','0','1','0','0','0','0','0','1','0','0','0','0','1','0','1','1','1','0','1','1','1','0','0'},new char[]{'1','1','0','1','0','0','1','1','1','1','0','0','1','0','0','0','1','1','1','0','1','0','1','0','1','1','1','1','1','0','0','0','1','0','0','0','1','1','1'},new char[]{'1','0','0','1','1','1','0','0','1','1','1','1','1','0','0','0','0','0','1','0','1','0','0','0','0','1','0','0','1','1','0','1','1','0','1','0','0','0','0'},new char[]{'0','0','1','1','0','1','1','1','0','0','0','1','1','1','1','1','0','1','1','1','1','0','1','0','1','0','1','1','1','0','0','1','0','1','1','1','1','0','0'},new char[]{'0','1','0','1','1','1','1','1','0','0','1','1','0','1','0','1','1','0','0','0','1','0','0','1','0','1','0','0','1','0','0','0','1','1','1','1','1','1','1'},new char[]{'0','1','1','1','1','0','1','1','0','0','1','0','0','1','1','0','1','0','0','0','1','1','0','0','0','0','0','1','1','0','1','1','0','1','1','1','0','0','1'},new char[]{'0','0','0','1','0','0','1','0','1','0','0','1','0','1','1','0','1','0','1','1','0','0','0','0','1','0','1','0','0','1','0','1','1','1','1','0','0','0','1'},new char[]{'1','0','0','1','0','1','0','1','0','0','1','1','1','0','0','0','1','0','1','1','0','1','1','1','0','0','1','1','0','1','1','0','1','1','0','0','1','1','0'},new char[]{'0','0','1','0','1','1','0','0','1','1','1','0','0','1','1','1','0','1','0','0','0','0','1','1','1','1','1','0','0','1','0','1','0','0','1','0','1','0','0'},new char[]{'1','1','0','0','1','1','1','0','0','1','0','1','1','1','0','0','0','0','0','1','0','1','0','1','1','0','1','1','1','0','0','1','0','0','1','0','1','1','1'},new char[]{'0','1','0','0','1','1','0','1','1','0','1','0','1','1','0','0','1','1','1','1','1','1','1','1','1','1','0','1','0','0','0','0','0','1','1','0','1','0','1'},new char[]{'1','0','1','0','1','1','0','0','0','1','1','0','0','0','0','1','1','0','0','0','0','0','0','1','1','0','1','0','1','1','1','0','0','0','0','1','1','1','0'},new char[]{'1','0','1','0','1','0','1','0','0','1','1','1','0','1','1','1','1','0','0','1','0','1','0','0','0','1','1','0','1','1','1','0','1','0','0','0','0','0','1'},new char[]{'1','1','0','0','1','0','0','1','1','1','1','0','0','0','0','0','0','1','1','0','0','1','0','0','1','1','1','0','0','0','1','1','1','1','1','1','1','0','0'},new char[]{'1','0','0','1','1','0','1','1','0','0','0','0','0','1','0','0','1','1','1','1','1','1','0','0','0','1','1','1','1','0','0','1','1','0','1','1','1','0','1'},new char[]{'0','1','0','0','0','1','0','1','0','0','1','0','1','0','1','1','0','1','0','1','1','0','0','0','0','0','1','1','0','1','1','0','1','1','0','0','1','1','1'},new char[]{'1','0','1','1','1','1','1','1','0','0','1','0','1','0','1','0','0','1','0','0','0','0','1','1','0','1','0','1','0','1','1','1','1','1','1','0','0','1','0'},new char[]{'0','1','1','1','0','1','0','1','1','0','0','0','1','0','0','0','1','0','0','0','0','1','0','0','0','0','0','1','1','1','0','1','1','0','1','1','1','1','1'},new char[]{'1','1','1','0','1','1','0','0','0','0','1','1','0','1','1','0','1','0','0','1','0','0','1','1','1','0','1','1','0','1','1','1','0','1','1','0','0','0','1'},new char[]{'0','1','0','0','0','1','1','1','1','1','1','1','0','0','1','1','0','1','0','0','1','1','1','0','0','1','0','0','0','0','1','0','1','0','1','0','1','1','0'},new char[]{'1','1','0','1','1','0','0','1','1','1','0','1','1','0','1','1','0','0','1','1','1','1','0','0','0','0','0','0','0','1','0','0','0','1','0','0','1','1','1'}}); param0.add(new char[][]{new char[]{'B','D','D','E','H','H','J','M','M','M','M','N','O','O','P','R','S','T','U','U','W','W','Z','Z','b','c','c','e','f','g','j','k','k','n','o','r','t','u','v'},new char[]{' ','A','A','A','C','C','D','D','E','F','H','J','J','K','L','L','N','T','T','U','W','Y','Z','c','f','g','i','i','k','k','m','n','o','p','r','r','u','v','x'},new char[]{' ','A','A','C','D','E','G','H','K','K','L','Q','S','U','V','Z','a','d','e','g','i','i','j','n','o','o','p','p','q','s','s','t','t','w','x','x','x','y','z'},new char[]{' ','B','D','E','G','H','H','H','H','K','M','O','O','R','R','S','S','U','V','X','a','a','d','e','e','f','h','i','j','p','p','q','q','q','s','w','w','y','z'},new char[]{' ','A','A','C','E','F','G','H','J','J','K','M','O','S','S','U','X','Y','Z','b','d','f','g','h','i','j','k','l','n','q','q','s','s','t','u','u','v','y','z'},new char[]{'H','H','H','H','J','J','K','M','N','S','U','U','V','V','V','W','Y','a','b','c','c','e','f','f','f','h','k','l','m','q','q','s','t','v','v','w','w','y','z'},new char[]{'A','B','D','G','H','I','J','J','L','M','N','P','Q','S','T','T','X','X','X','Y','Z','a','c','d','d','d','i','k','l','m','n','p','q','q','t','w','x','y','y'},new char[]{' ','B','B','C','E','F','G','H','I','I','I','J','J','K','M','N','O','O','P','Q','S','T','W','Y','Y','a','c','d','h','h','i','j','k','o','o','s','z','z','z'},new char[]{' ','A','C','C','D','E','E','E','F','H','H','M','M','N','N','R','T','W','Z','Z','d','e','h','h','j','j','k','m','n','o','p','r','s','s','t','w','x','x','x'},new char[]{'A','D','I','M','P','Q','U','U','Y','Y','Z','Z','Z','a','b','c','e','f','f','f','g','g','h','h','i','i','j','m','n','o','p','q','r','u','u','u','w','x','z'},new char[]{' ','A','A','A','B','C','E','F','G','H','J','Q','R','S','U','U','V','W','Y','Z','a','b','b','d','g','j','k','l','l','m','n','n','o','s','s','u','w','w','w'},new char[]{' ','A','B','C','E','E','E','H','J','J','K','M','N','P','R','U','U','V','W','a','e','f','k','k','k','l','l','m','n','n','o','o','o','q','r','r','t','u','x'},new char[]{' ','B','B','E','F','F','H','O','O','P','P','Q','R','S','T','X','a','a','a','b','e','f','g','i','j','m','n','p','r','t','t','t','u','v','v','w','x','x','z'},new char[]{' ','A','B','C','D','E','E','G','H','J','J','J','K','K','M','P','Q','R','R','W','X','X','Z','a','a','e','h','i','j','k','q','q','r','r','s','u','x','x','y'},new char[]{' ','B','I','I','J','J','K','N','O','P','P','R','U','X','Z','Z','Z','b','d','f','f','h','h','h','j','k','k','n','n','o','o','p','q','s','t','v','w','x','z'},new char[]{' ',' ','B','E','K','L','M','N','Q','Q','R','S','T','U','V','V','V','W','X','Y','Z','a','b','e','e','g','i','i','m','n','o','p','s','u','u','v','w','x','z'},new char[]{'E','E','E','E','J','K','K','M','N','P','Q','S','S','V','W','W','W','X','Y','c','c','d','e','f','h','n','n','p','q','r','s','t','u','v','x','x','y','z','z'},new char[]{' ',' ',' ','E','E','F','F','G','G','H','J','L','O','Q','R','R','T','V','W','Y','Y','Z','Z','c','f','g','h','h','j','l','q','q','q','t','v','x','x','y','y'},new char[]{'B','D','G','G','H','J','J','K','M','Q','S','S','T','T','T','U','V','Z','Z','a','b','d','e','g','g','h','h','l','l','n','o','s','u','u','v','v','w','x','y'},new char[]{' ',' ','B','B','B','C','D','D','E','I','L','M','O','O','P','P','Q','R','R','R','R','R','U','a','b','c','d','e','g','k','l','l','n','n','n','p','p','r','r'},new char[]{' ',' ','B','E','E','F','G','L','M','N','N','O','P','R','R','S','S','S','T','T','Y','Y','Z','a','a','b','d','e','f','j','j','k','l','l','m','o','o','p','y'},new char[]{'A','B','E','E','H','H','I','J','J','N','O','P','Q','R','V','V','W','W','X','X','Y','Z','Z','g','i','j','j','m','n','o','q','r','r','s','s','s','s','t','x'},new char[]{' ','G','J','L','M','M','Q','Q','Q','S','U','W','W','Y','Z','Z','a','b','f','h','i','i','l','l','m','n','o','p','p','p','q','q','q','s','s','t','u','v','w'},new char[]{'B','B','D','E','E','H','I','J','K','K','L','S','T','V','X','b','b','b','d','d','g','h','h','h','i','i','k','l','m','m','n','o','v','w','x','x','x','z','z'},new char[]{'B','C','C','C','D','D','E','F','J','K','M','N','O','O','Q','Q','R','R','R','S','T','U','V','W','W','a','b','f','g','i','m','n','n','n','p','p','p','u','v'},new char[]{' ','B','D','F','F','H','J','J','M','M','N','T','U','c','d','e','e','j','j','j','l','l','m','m','n','n','o','p','p','p','s','t','t','v','v','w','y','y','y'},new char[]{' ','A','A','B','D','G','H','H','H','I','K','N','O','P','R','S','T','Y','Y','a','b','c','e','f','g','h','j','j','j','m','n','o','s','s','u','u','x','x','z'},new char[]{' ',' ','F','G','G','J','N','N','P','S','S','S','T','T','X','Z','a','d','e','f','f','h','i','j','k','m','m','n','r','s','s','t','v','w','x','x','x','z','z'},new char[]{'B','B','D','I','J','L','M','M','N','P','P','Q','S','U','X','X','X','Y','Z','a','b','e','e','f','g','i','j','l','m','o','q','r','r','t','v','w','w','w','w'},new char[]{' ','A','B','C','D','D','E','F','F','H','I','J','J','M','N','N','O','S','U','V','W','W','e','g','h','h','i','j','j','o','p','q','q','r','t','v','v','x','y'},new char[]{' ','A','A','C','C','D','D','D','E','G','I','J','O','Q','S','S','S','T','T','V','X','Y','Y','b','i','k','l','l','m','n','p','t','v','w','w','x','x','y','z'},new char[]{'A','A','D','F','G','H','I','L','N','P','Q','S','T','U','V','W','W','X','Y','Z','b','c','f','g','g','g','j','j','j','l','q','s','s','v','v','w','x','y','z'},new char[]{'B','H','I','J','K','K','L','L','M','N','N','N','P','P','S','T','U','V','W','W','a','a','a','a','b','j','j','k','m','n','p','u','u','u','v','w','x','y','z'},new char[]{'B','B','D','D','D','E','G','H','I','I','I','L','N','N','O','P','R','R','R','S','V','V','Y','Z','a','b','h','k','l','m','n','o','p','p','q','r','s','x','z'},new char[]{'A','B','B','G','G','H','J','J','L','M','M','N','N','P','P','P','R','S','T','X','Z','d','d','f','f','j','j','j','l','l','l','m','r','r','u','v','v','x','x'},new char[]{' ','B','B','C','E','G','J','J','K','L','N','O','Q','R','T','T','V','V','X','X','b','e','f','i','i','k','m','n','o','o','p','s','s','u','u','w','x','x','x'},new char[]{'A','A','A','B','B','E','H','H','H','I','J','J','N','Q','Q','R','R','U','V','X','a','b','d','d','e','e','g','g','k','k','l','n','n','p','q','q','v','w','x'},new char[]{'B','B','B','C','C','D','E','F','H','I','I','K','N','N','P','P','P','U','W','X','Z','c','e','h','h','i','j','l','p','p','r','r','r','r','v','w','x','x','y'},new char[]{' ',' ','B','C','C','D','E','E','H','L','O','P','P','S','T','V','Y','Y','Y','c','d','e','e','f','h','h','h','j','k','l','m','n','r','s','s','u','x','y','y'}}); param0.add(new char[][]{new char[]{'8','0','3','3','7','7','3','5','4','9','6','9','4','6','9'},new char[]{'8','7','2','2','6','9','6','0','0','6','8','1','6','1','5'},new char[]{'2','0','5','1','8','0','0','2','9','4','1','4','8','0','2'},new char[]{'9','9','9','5','1','8','9','5','8','7','2','9','4','0','4'},new char[]{'1','6','7','1','7','4','7','4','6','4','3','8','0','4','9'},new char[]{'2','7','9','6','1','2','2','9','0','7','2','3','2','0','9'},new char[]{'9','5','3','3','6','1','3','1','3','4','3','4','1','5','9'},new char[]{'1','6','5','2','6','7','1','8','6','6','2','2','6','7','6'},new char[]{'5','3','8','0','3','6','3','2','1','2','3','8','1','0','2'},new char[]{'2','2','6','8','0','6','5','9','9','3','9','5','8','6','4'},new char[]{'4','1','0','3','9','1','0','8','3','4','0','9','0','6','8'},new char[]{'1','7','9','6','6','1','7','2','5','9','5','2','1','1','8'},new char[]{'7','7','4','5','2','6','4','3','4','9','1','4','3','7','2'},new char[]{'1','3','0','5','9','2','2','6','2','4','0','7','2','6','1'},new char[]{'0','4','4','2','6','9','5','4','3','2','6','5','6','4','0'}}); param0.add(new char[][]{new char[]{'0','0','0','0','0','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','1','1','1','1'},new char[]{'0','0','0','0','0','0','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','0','1','1','1'},new char[]{'0','0','0','0','0','0','0','0','1','1','1','1'},new char[]{'0','0','0','0','0','0','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','1','1','1','1','1','1','1'},new char[]{'0','0','0','0','0','0','0','1','1','1','1','1'},new char[]{'0','0','0','0','0','1','1','1','1','1','1','1'}}); param0.add(new char[][]{new char[]{'u','V','l','L','o','i','o','L','S','D','S','u','Z','E','s','q','P','X','d','v','W','J','p','r','e','j','F','l','Z','U','R','Y','M','C','S','C','Q','A'},new char[]{'w','p','O','x','a','v','Q','Z','n','Q','j','t','N',' ','n','u','y','x','E','r','d','e','g','e','H','Z','b','s','A','R','x','h','v','X','x','K','P','M'},new char[]{'y','D','z','t','g','L','B','N','i','g','E','l','P','q','j','m','c','X','b','X','Z','w','s','Z','F','p','r','P','o','p','Y','R','w','n','y','n','t','C'},new char[]{'b','v','G','K','J','u','w','q','x','b','O','Z','b','v','E','O','o','j','W','d','r','z','X','K','r','O','m','S','V','D','m','O','j','O','J','L','z','S'},new char[]{'Z','O','X','A','d','N','V','t','f','z','q','H','O','Z','b','T','W','B','u','K','P','y','w','z','p','M','Z','P','l','y','J','G','i','C','r','y','s','v'},new char[]{'k','R','i','z','A','l','J','X','C','i','P','A','y','y','a','E','V','s','a','P','r','Y','D','n','o','w','M',' ','W','m','W','H','a','v','j','g','Y','m'},new char[]{'M','y','N','A','R','u','e','N','H','a','s','E','Q','b','d','E','s','X','f','G','N','x','h','i','u','U','M','U','s','u','N','f','u','o','C','s','S','P'},new char[]{'h','C','v','L','H','h','Y','Y','F','S','d','Q','h','V','V','U','g','C','s','X','E','t','e','M','F','w','U','e','C','J','Y','R','o','a','W','L','k','K'},new char[]{'k','H','J','T','s','F','y','C','O','J','O','B','m','B','e','G','l','g','y','J','y','u','F','E','B',' ','B','Z','a','e','v','u','U','J','l','C','k','v'},new char[]{'d','y','V','Z','t','X','n','v','O','s','E','L','Z','x','x','p','w','W','S','n','G','y','q','o','B','X','f','r','n','T','y','p','J','j','I','w','r','s'},new char[]{'h','y','p','j','r','D','j','H','t','X','q','K','N','j','h','v','K','r','j','J','A','u','D','f','J','n','q','w','P','w','i','s','G','s','t','D','r','A'},new char[]{'f','I','v','M','x','K','O','i','p','y','o','Z','Y','s','V','f','i','V','x','K','p','a','L','V','r','B','v','d','M','e','X','h','F','S','p','Z','J','I'},new char[]{'H','V','a','a','i','k','D','e','Z','i','h','v','A','G','N','Q','r','e','A','q','n','a','z','N','b','y','R','z','c','I','A','h','z','o','F','w','p','h'},new char[]{'X','z','K','b','z','E','u','E','h','L','X','K','Q','r','f','Z','k','p','S','b','l','N','M','u','f','z','p','f','Q','U','q','g','F','K','D','Q','H','K'},new char[]{'S','U','o','u','z','G','q','w','N','B','c','u','k','n','v','S','O','Z','I','F','T','Z','D','g','w','K','G','C','B','M','e','W','r','v','l','t','t','u'},new char[]{'P','e','m','H','W','b','s','C','j','U','E','a','J','o','G',' ','H','T','f','j','N','N','E','u','W','O','X','e','m','w',' ','f','U','Y','N','X','I','j'},new char[]{' ','v','q','O','d','p','d','Q','N','A','v','u','o','q',' ','S','H','b','M','J','b','G','L','N','w','r','G','Q','E','R','y','a','k','S','W','I','P','d'},new char[]{'N','z','F','X','x','J','q','G','Z','Z','E',' ','q','M','L','B','y','k','h','R','e','R','N','p','D','K','n','g','E','w','P','v','J','P',' ','q','N','s'},new char[]{'u','Q','F','j','r','I','X','C','E','R','R','E','D','p','n','a','X','Q','J','F','F','x','s','P','o','a','t','f','S','n','P','S','k','s','j','M','L','l'},new char[]{'F',' ','n','P','P','N','D',' ','N','W','G','m','p','P','R','L','b','c','q','O','k','Y','p','I','b','P','Y','Y','F','c','p','W','e','R','k','j','V','h'},new char[]{'Q','J','g','D','S','U','m','z','M','n','a','V','q','P','X','w','s','v','J','J','h','n','J','d','Z','M','v','M','h','Q',' ','W','V','s','O','A','x','j'},new char[]{'N','i','m','F','H','C',' ','x',' ','t','g','q','j','d','n','g','l','U','k','U','q','h','A','c','u','o','U','z','D','N','p','R','K','k','T','i','D','i'},new char[]{'P','r','W','S','s','U','k','l','e','s','W','d','Y','q','p','Q','z','F','Z','s','x','h','J','q','B','F','R','m','l','f','H','U','d','V','o','b','t','B'},new char[]{'R','q','m','q','h','q','i','P','N','O','q','i','V','O','n','K','J','d','E','b','V','O','u','S','l','u','A','k','d','r','x','g','y','U','A','q','p','d'},new char[]{'r','h','h','L','j','d','b','o','v','D','d','M','f','y','Q','V',' ','j','a','T','X','a','t','I','Z','A','P','l','Y','j','c','A','A','e','r','H','u','f'},new char[]{'a','Y','J','J','k','L','x','l','O','n','J','I','l','x','V','S','S','l','D','E','m','d',' ','j','Q','L','t','c','o','D','z','A','x','u','F','E','v','a'},new char[]{'o','K','F','V','L','G','t','A','d','b','P','F','K','N','J','e','B','T','H','n','D','b','m','T','L','S','n','D','b','s','I','t','O','a','m','a','A','n'},new char[]{'L','o','z','L','a','d','T','D','d','S','D','a','m','z','y','y','A','j','v','H','F','t','A','f','G','E',' ','x',' ','m','L','I','O','Z','C','y','X','x'},new char[]{' ','I','i','s','E','N','m','k','l','n','s','s','P','M','x','i','I','K','k','m','k','X','n','W','k','F','D','c','l','d','n','o','H','T','B','g','S','v'},new char[]{'g','p','d','A','Y','b','L','P','v','j','O','C','s','g','J','m','P','d','H','c','h','U','P','J','h','c','f','W','l','K','F','T','s','Z','n','v',' ','p'},new char[]{'O','H','J','y','B','c','M','Q','F','k','S','o','b','M','c','i','K','l','a','Y','v','O','U','R','B','o','H','g','o',' ','H','l','g','e','L','x','M','z'},new char[]{'q','u','A','O','u','f','r','U','F','g','f','g','R','E','W','H','n','e','N','Z','y','M','j','L','T','b','v','N','u','X','E','y','g','Y',' ','n','T','r'},new char[]{'k','n','F','B','X','t','j','a','b','I','C','O','R','h','c','C','F','E','l','Y','s','D','p','j','J',' ','y','u','x','q',' ','P','J','P','t','g','X','j'},new char[]{'M','u','Q','x','r','n','U','w','w',' ','H','P',' ','V','X','Y','t','Z','F','H','X','N','y','E','j','I','Q','P',' ','y','e','I','o','b','j','E','p','G'},new char[]{'n','d','T','f','a','D','s','i','b','m','K','h','c','G','I','p','d','x','I','G','B','q','k','A','B','M','g','S','t','K','b','m','m','u','k',' ','U','Z'},new char[]{'C','v','L','k','x','L',' ','m','x','P','C','X','n','w','d','E','O','D','Q','i','A','p','K','r','n','Y','T','v','K','O','M','w','p','P','R','X','I','g'},new char[]{'l','M','d','j','M','d','y','x',' ','o','E','t','X','w','c','H','r','q','d','Q','I','g','T','F','t','q','A','e','m','y','G','t','v','G','r','x','g','H'},new char[]{'T','f','N','W','K','T','b','O','J','B','a','d','l','y','s','s','W','D','t','z','D','c','k','l','e','Q','A','J','J','k','M','G','F','S','C','N','x','X'}}); List<Integer> param1 = new ArrayList<>(); param1.add(13); param1.add(39); param1.add(15); param1.add(31); param1.add(11); param1.add(20); param1.add(38); param1.add(8); param1.add(6); param1.add(32); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
885
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/CHECK_VALID_SEQUENCE_DIVISIBLE_M_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_VALID_SEQUENCE_DIVISIBLE_M_1{ static int f_gold ( int n , int index , int modulo , int M , int arr [ ] , int dp [ ] [ ] ) { modulo = ( ( modulo % M ) + M ) % M ; if ( index == n ) { if ( modulo == 0 ) { return 1 ; } return 0 ; } if ( dp [ index ] [ modulo ] != - 1 ) { return dp [ index ] [ modulo ] ; } int placeAdd = f_gold ( n , index + 1 , modulo + arr [ index ] , M , arr , dp ) ; int placeMinus = f_gold ( n , index + 1 , modulo - arr [ index ] , M , arr , dp ) ; int res = placeAdd ; dp [ index ] [ modulo ] = res ; return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(19); param0.add(14); param0.add(5); param0.add(8); param0.add(14); param0.add(16); param0.add(24); param0.add(7); param0.add(35); param0.add(8); List<Integer> param1 = new ArrayList<>(); param1.add(29); param1.add(17); param1.add(7); param1.add(10); param1.add(12); param1.add(21); param1.add(26); param1.add(7); param1.add(35); param1.add(5); List<Integer> param2 = new ArrayList<>(); param2.add(20); param2.add(13); param2.add(6); param2.add(10); param2.add(16); param2.add(17); param2.add(24); param2.add(7); param2.add(33); param2.add(8); List<Integer> param3 = new ArrayList<>(); param3.add(19); param3.add(17); param3.add(8); param3.add(8); param3.add(19); param3.add(18); param3.add(21); param3.add(7); param3.add(22); param3.add(6); List<int [ ]> param4 = new ArrayList<>(); param4.add(new int[]{1,2,2,3,6,15,16,17,20,21,27,28,28,29,44,47,53,53,54,59,60,60,66,68,78,79,80,84,87,91,92,97}); param4.add(new int[]{68,-86,-98,40,-6,-16,-98,50,46,-34,74,-8,-70,-18,-58,92,12,98,34,6,54,70}); param4.add(new int[]{0,0,0,0,0,1,1,1,1,1}); param4.add(new int[]{8,8,80,15,73,51,44,98,99,59,73,42}); param4.add(new int[]{-88,-82,-78,-72,-70,-54,-32,-32,-10,-8,8,14,16,22,26,26,28,30,34,34,62,62,76,88}); param4.add(new int[]{0,1,0,1,1,0,0,0,0,0,1,0,1,1,1,1,0,0,0,1,0,1,1,1,1,1,1,1}); param4.add(new int[]{4,8,8,16,22,23,28,32,38,45,48,50,52,54,55,64,70,75,75,76,83,87,88,89,94,94,95}); param4.add(new int[]{-56,-66,-60,94,44,-92,18,-26,-88,46,-24,-8,-46,78}); param4.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param4.add(new int[]{80,95,34,51,95,68,55,65,60}); List<int [ ] [ ]> param5 = new ArrayList<>(); param5.add(new int[][]{new int[]{4,7,9,11,16,22,22,24,31,35,36,37,44,46,47,50,52,56,59,62,62,63,65,65,67,67,72,74,74,79,92,92},new int[]{6,10,12,16,17,21,23,25,25,25,27,30,32,39,39,40,46,47,47,62,78,79,79,84,86,87,88,88,90,91,93,95},new int[]{2,3,8,9,12,12,27,28,32,33,33,38,39,40,43,43,46,47,48,48,56,58,62,72,77,77,78,89,93,94,97,98},new int[]{2,3,3,6,12,13,14,14,17,19,19,19,20,23,27,43,48,52,53,54,60,65,65,67,67,67,68,74,75,78,88,90},new int[]{1,3,13,16,21,23,30,30,35,37,37,42,43,47,47,49,50,52,60,61,67,68,73,78,78,79,80,82,83,89,95,97},new int[]{2,4,6,10,11,16,24,33,34,35,40,40,47,50,51,55,62,64,68,70,70,73,75,81,85,85,89,91,92,93,93,94},new int[]{3,5,11,11,15,19,20,25,26,27,27,36,37,44,56,60,64,64,68,74,76,76,77,78,80,84,87,91,92,94,95,96},new int[]{2,2,9,14,16,20,20,27,28,29,32,33,35,46,53,54,55,57,61,62,63,63,69,74,84,87,88,90,93,93,98,98},new int[]{4,5,9,12,14,20,21,22,25,26,32,33,33,35,36,38,45,51,54,58,60,61,67,69,70,75,75,77,80,89,90,94},new int[]{2,8,18,18,20,23,24,29,31,32,33,34,35,41,41,47,48,49,52,55,61,65,65,66,69,69,76,85,89,91,94,94},new int[]{6,10,12,14,14,32,32,34,35,39,39,44,44,50,52,52,54,56,58,60,60,62,65,69,69,71,77,83,83,86,92,92},new int[]{2,8,15,19,21,27,32,41,46,47,48,49,51,51,63,65,67,72,73,76,77,77,82,82,83,85,87,88,91,92,94,98},new int[]{6,7,13,14,14,14,15,21,23,29,30,30,37,44,45,45,48,48,57,67,67,68,70,71,71,72,78,86,86,91,97,99},new int[]{4,5,12,12,13,14,14,16,18,20,21,24,24,25,25,26,33,40,47,49,51,61,64,64,68,74,81,83,83,87,89,94},new int[]{3,8,9,14,16,17,30,33,39,40,40,43,45,46,47,49,51,54,55,56,59,60,63,79,79,83,94,94,95,98,99,99},new int[]{4,6,7,9,9,10,16,17,18,21,30,33,36,37,37,39,42,53,57,66,69,70,73,77,81,82,82,84,87,88,92,99},new int[]{2,2,5,6,6,7,12,13,13,17,22,24,24,27,27,29,35,36,39,39,43,44,45,64,71,72,73,82,82,85,93,98},new int[]{1,5,8,9,12,13,22,29,30,31,36,36,40,40,41,42,52,55,57,58,61,61,61,65,76,78,82,86,86,89,94,96},new int[]{1,3,3,5,9,10,19,19,20,24,34,40,42,42,46,46,48,53,53,58,64,68,72,73,81,86,88,89,90,92,93,95},new int[]{1,1,5,5,15,19,22,23,27,29,33,41,44,44,48,51,56,56,71,77,79,79,82,82,84,86,87,90,90,91,93,98},new int[]{2,4,8,13,14,22,23,27,28,29,37,37,38,41,47,47,48,50,51,53,54,55,57,63,65,69,75,77,77,79,82,97},new int[]{4,9,10,18,20,23,24,27,39,40,41,41,42,43,45,58,58,64,66,67,68,69,74,81,83,83,84,84,86,87,90,98},new int[]{1,8,9,11,15,15,18,24,25,31,31,33,34,35,35,43,47,52,56,58,58,67,69,70,71,74,77,82,85,89,89,90},new int[]{1,3,8,8,12,12,16,21,22,25,25,25,29,31,31,31,34,34,35,35,36,37,37,42,43,55,55,59,67,72,74,85},new int[]{2,4,6,9,12,14,18,22,23,23,26,36,36,41,44,51,51,53,56,59,59,59,60,61,68,68,74,77,93,94,94,96},new int[]{1,2,5,11,12,14,19,28,33,34,37,37,38,38,38,47,49,59,62,67,71,73,73,74,80,83,84,85,89,90,92,99},new int[]{1,5,10,19,24,36,41,47,48,57,59,59,60,62,65,65,67,70,71,77,79,79,81,81,82,83,87,89,91,91,95,97},new int[]{7,10,10,10,17,18,29,29,30,31,32,32,37,38,44,50,59,59,62,63,63,73,74,80,80,81,84,85,85,89,98,99},new int[]{1,7,9,14,19,22,26,29,30,34,40,43,44,45,45,46,49,58,62,63,67,76,78,79,82,84,93,94,95,97,98,98},new int[]{5,6,8,9,12,14,22,31,34,36,38,43,46,47,48,48,50,52,54,57,67,68,68,72,75,77,79,80,92,96,97,98},new int[]{8,10,15,15,15,19,21,24,25,27,30,34,36,43,44,45,50,51,54,55,57,58,59,63,69,69,73,75,87,94,96,96},new int[]{3,4,12,13,13,16,16,19,29,32,40,43,48,49,55,58,61,64,65,66,66,69,71,72,75,83,85,88,89,90,94,96}}); param5.add(new int[][]{new int[]{-30,10,-22,92,-46,58,-12,-42,64,12,6,12,-34,-20,6,-90,-60,78,90,-72,-30,2},new int[]{-72,-60,22,-22,-12,6,80,-34,8,-66,20,-72,-34,-30,14,-54,86,96,-20,-76,34,-64},new int[]{52,8,28,-74,78,-92,-78,6,56,-76,98,4,-46,80,36,54,-70,68,-88,68,-84,-94},new int[]{94,84,60,44,-46,-44,94,60,14,76,82,84,56,68,54,46,-42,16,-46,32,-76,-6},new int[]{-8,-88,70,-48,62,4,70,-62,34,-48,48,-82,-16,60,14,-10,-56,4,-22,-96,44,22},new int[]{-34,-70,-16,-94,-22,2,-20,10,-42,52,18,-74,-84,-56,72,-24,64,-90,68,-90,60,-70},new int[]{28,-86,-52,-58,-2,-96,32,-90,88,98,-66,78,-44,-6,-44,46,-16,-76,48,-20,-68,-70},new int[]{-88,-88,-16,24,-96,-32,20,-92,-50,40,26,12,-76,50,-90,-96,6,8,-56,74,30,-46},new int[]{40,-74,-18,-36,-50,82,-72,-74,-38,16,86,56,58,80,74,4,-16,-14,-78,36,-8,-16},new int[]{-44,-18,-14,94,-4,-98,-4,-32,-84,-54,38,78,-74,62,76,30,22,24,34,42,94,-84},new int[]{60,-26,-12,14,-26,42,60,12,74,-26,66,60,32,32,-70,22,50,84,-14,-2,62,50},new int[]{-38,-28,-8,62,10,18,-78,-68,70,88,-4,24,88,-32,44,-46,58,-90,18,-32,42,32},new int[]{2,-14,62,84,-18,76,-94,-66,-64,-58,-54,40,74,32,-78,-46,44,-16,-40,32,-66,-82},new int[]{-46,26,92,96,-34,-88,-84,82,20,-12,62,92,32,66,38,66,38,-50,68,-56,-44,72},new int[]{-30,-40,-56,46,36,12,-58,-36,-36,66,-80,-24,34,-96,0,-46,-38,88,36,92,-74,-40},new int[]{-10,-54,96,-58,80,-64,-88,60,24,14,-58,30,74,64,66,96,-66,86,66,76,-90,-28},new int[]{34,6,60,62,-10,-34,58,-38,92,-28,-88,-36,84,94,2,36,22,-38,66,36,36,22},new int[]{92,64,64,-8,14,88,-64,34,-26,44,44,10,-2,-80,-50,-90,70,36,-50,32,18,72},new int[]{26,52,-88,-72,-52,78,64,-34,-96,-68,76,-50,-28,-84,22,16,40,84,-16,80,-48,38},new int[]{16,-94,-74,30,-82,24,38,8,-68,26,-96,-36,90,56,20,24,-42,-76,-20,24,76,10},new int[]{74,56,-46,84,-84,80,-26,90,-42,22,78,26,56,-12,62,-12,-30,-20,-52,42,52,-56},new int[]{34,-86,-18,-60,-64,60,-98,78,34,-40,10,-36,48,98,94,38,-32,46,-52,34,-74,60}}); param5.add(new int[][]{new int[]{0,0,0,0,0,0,1,1,1,1},new int[]{0,0,0,0,0,0,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0},new int[]{0,0,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,1,1,1,1},new int[]{0,0,0,0,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,1,1,1},new int[]{0,0,0,0,0,0,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,1,1},new int[]{0,0,0,0,0,1,1,1,1,1}}); param5.add(new int[][]{new int[]{89,45,59,5,12,1,54,1,25,40,25,45},new int[]{94,83,22,94,13,16,98,46,37,94,99,59},new int[]{7,92,73,68,63,10,45,75,56,77,66,79},new int[]{37,91,18,45,35,35,66,75,82,14,88,88},new int[]{16,44,53,11,41,41,44,53,19,11,3,99},new int[]{80,89,67,90,58,65,9,15,76,4,43,8},new int[]{39,51,95,87,68,88,84,27,15,77,95,84},new int[]{54,67,79,17,81,4,18,10,37,96,15,42},new int[]{19,49,6,4,37,50,43,83,89,44,74,21},new int[]{75,19,30,32,20,67,1,85,3,31,76,78},new int[]{94,25,26,97,28,74,96,81,36,33,21,25},new int[]{19,72,42,88,41,20,1,18,92,5,82,18}}); param5.add(new int[][]{new int[]{-96,-74,-68,-56,-40,-26,-22,-18,-6,-2,6,6,18,18,20,22,26,30,32,40,52,52,70,70},new int[]{-96,-92,-90,-90,-72,-70,-64,-52,-50,-44,-40,-32,-30,-28,-24,-18,-16,-4,14,18,28,36,50,70},new int[]{-96,-62,-60,-54,-52,-40,-36,-2,6,6,6,8,12,14,18,34,36,44,62,66,66,78,86,88},new int[]{-90,-78,-64,-58,-56,-50,-40,-32,-32,-12,0,0,16,18,26,28,30,38,40,44,48,72,84,98},new int[]{-88,-46,-34,0,10,12,16,20,26,38,48,48,50,60,60,62,66,72,72,74,84,88,94,98},new int[]{-96,-94,-88,-80,-76,-66,-62,-36,-20,-16,-6,-6,-2,0,0,18,20,24,36,40,72,76,86,98},new int[]{-66,-52,-44,-32,-28,-20,-6,-4,10,18,22,24,26,38,40,44,44,48,48,58,84,90,94,94},new int[]{-86,-78,-54,-52,-46,-38,-34,14,24,26,34,34,40,46,50,50,62,72,72,82,84,86,92,94},new int[]{-98,-84,-70,-68,-66,-60,-28,-10,4,10,16,34,34,44,46,48,52,56,56,56,60,84,84,88},new int[]{-96,-92,-82,-80,-76,-54,-52,-46,-46,-30,-26,-26,-20,-16,-10,-10,-4,26,30,32,34,78,78,86},new int[]{-92,-90,-76,-64,-50,-48,-46,-42,-36,-30,-24,-20,-14,-4,12,16,22,30,40,40,48,60,86,92},new int[]{-86,-82,-72,-46,-46,-42,-34,-34,-22,-20,-20,-14,-10,-2,-2,28,50,50,52,58,78,80,84,94},new int[]{-92,-90,-74,-64,-64,-56,-52,-50,-46,-46,-32,-26,-22,-4,-2,10,16,32,34,38,58,58,60,86},new int[]{-94,-88,-66,-58,-56,-50,-42,-30,-28,-24,-22,-12,-10,-8,0,16,24,26,30,38,44,52,80,98},new int[]{-98,-82,-74,-64,-60,-52,-48,-38,-36,-24,-20,-20,-18,26,26,36,44,44,50,50,54,78,80,96},new int[]{-84,-68,-66,-62,-60,-52,-50,-40,-36,-28,-8,-6,2,18,26,32,42,50,62,66,68,72,80,98},new int[]{-92,-90,-82,-72,-72,-58,-54,-40,-38,-34,-28,-22,-6,-6,0,0,2,6,18,44,68,70,72,74},new int[]{-92,-64,-64,-60,-58,-52,-50,-12,-8,-8,-4,-2,14,14,16,18,22,28,38,38,42,66,90,90},new int[]{-72,-70,-68,-56,-42,-40,-38,-32,-32,-22,-20,-20,-10,-10,0,24,24,34,72,80,88,92,94,96},new int[]{-84,-80,-58,-38,-32,-30,-16,-14,4,10,10,14,18,20,24,26,30,34,36,40,58,70,72,92},new int[]{-88,-78,-68,-66,-50,-42,-36,-36,-18,-14,-10,-6,-6,-2,2,6,16,18,40,68,72,76,86,94},new int[]{-82,-70,-64,-56,-52,-32,-10,-4,8,16,28,40,46,56,56,58,66,68,70,74,76,80,80,86},new int[]{-98,-90,-80,-78,-76,-74,-72,-64,-62,-42,-30,-14,-8,2,12,24,42,44,72,74,76,94,94,98},new int[]{-94,-90,-86,-82,-58,-50,-44,-20,-18,0,18,26,36,38,44,50,52,54,56,64,68,78,82,86}}); param5.add(new int[][]{new int[]{0,1,1,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,0,1,0,0,1,1,1,1,1,1},new int[]{0,0,0,1,0,1,1,1,1,1,1,1,1,0,0,1,0,0,0,0,1,0,0,0,1,1,1,0},new int[]{1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1},new int[]{0,1,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,0,1,0},new int[]{0,1,1,0,0,0,1,1,0,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,1,0,1,0},new int[]{0,0,1,0,1,1,1,0,0,1,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,1,0},new int[]{0,0,1,1,1,0,1,1,1,1,1,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,1,1},new int[]{1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,1,0,1,0,0,0,1,1,0,1},new int[]{1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,0,0,1,1,1,0,1,0,1,0,0,1,0},new int[]{0,0,0,1,1,0,1,1,1,1,0,0,0,1,0,0,1,0,0,1,1,0,0,1,1,1,1,0},new int[]{1,0,0,0,1,0,1,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1},new int[]{1,1,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,1,1,0,1,1},new int[]{1,1,1,1,1,1,1,0,0,0,1,1,0,1,1,0,1,0,1,0,0,1,0,0,1,0,1,1},new int[]{0,1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,1},new int[]{0,1,0,0,1,0,0,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,0,1,0,1,0},new int[]{0,0,1,1,0,0,0,0,0,1,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,1},new int[]{0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0},new int[]{1,0,0,1,1,1,1,0,1,0,0,1,0,0,0,0,1,1,1,0,0,1,1,0,0,0,0,1},new int[]{1,1,0,0,1,0,1,0,1,1,0,1,1,0,1,0,0,1,0,0,1,1,1,0,0,1,1,1},new int[]{1,1,1,1,0,1,0,1,0,0,1,1,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0},new int[]{1,0,1,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,1,0,0,1},new int[]{0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,1,1,0,1},new int[]{0,1,1,0,0,0,0,0,0,1,1,0,1,0,1,1,1,0,1,0,0,1,0,0,0,0,0,1},new int[]{1,1,0,0,1,1,0,1,1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,1,1,1,0,1},new int[]{0,0,0,0,1,1,0,0,0,0,1,0,1,0,1,1,0,0,1,0,0,0,1,1,0,1,0,0},new int[]{0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,0,1,0,1,1,1,0,0,0,1,1},new int[]{1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,1,1,0,1,0,1,1,1,1,1,1,1,0},new int[]{0,1,1,0,1,0,0,0,1,0,1,1,1,0,1,0,1,1,1,1,1,1,1,1,0,0,1,0}}); param5.add(new int[][]{new int[]{1,3,5,8,8,16,16,18,19,26,28,33,33,35,35,41,42,43,47,51,65,66,73,84,87,95,99},new int[]{1,3,3,21,26,29,31,40,40,43,51,53,54,62,62,65,74,75,77,77,79,81,81,84,84,92,95},new int[]{7,9,10,12,13,14,19,27,30,44,46,47,51,53,58,59,65,73,78,84,84,86,88,91,92,98,99},new int[]{5,15,15,21,24,25,31,34,47,53,53,58,60,60,69,74,75,75,76,78,79,81,86,87,88,91,97},new int[]{5,16,19,20,22,25,32,37,37,40,43,46,50,55,56,58,59,60,61,64,67,72,85,88,91,91,96},new int[]{5,6,10,14,16,19,22,25,26,31,38,41,43,45,52,56,59,66,69,78,82,87,87,88,89,92,99},new int[]{3,11,15,18,22,25,31,37,37,38,38,44,47,50,51,52,68,70,78,81,83,84,89,90,95,95,98},new int[]{3,6,8,10,13,21,22,22,22,22,23,26,33,42,49,49,50,66,72,73,75,78,83,84,92,93,99},new int[]{8,10,11,16,17,26,32,45,52,53,53,63,64,65,69,71,72,72,74,77,81,82,87,94,96,96,96},new int[]{3,4,8,11,21,25,26,31,33,35,35,38,42,43,48,50,50,61,62,63,67,67,70,79,80,84,97},new int[]{2,14,15,16,21,30,30,32,32,40,41,41,42,45,45,46,46,52,61,63,78,79,80,81,86,93,97},new int[]{4,5,5,6,7,16,16,18,20,22,23,28,30,35,38,43,63,67,72,77,82,85,85,87,87,91,92},new int[]{4,8,10,11,27,30,31,39,47,49,52,62,67,69,71,71,72,75,79,79,80,84,84,87,95,95,99},new int[]{16,17,21,24,26,32,43,43,46,49,53,56,64,72,81,82,85,85,90,90,92,92,93,95,95,97,99},new int[]{4,4,6,12,12,13,16,26,31,31,35,40,40,50,51,54,56,57,60,62,64,64,86,90,91,99,99},new int[]{13,13,16,17,18,20,21,21,23,24,25,25,27,32,33,34,45,45,64,76,77,78,78,83,88,90,97},new int[]{2,4,5,6,6,11,17,18,35,36,42,52,52,54,55,57,58,70,70,72,81,86,87,87,89,97,99},new int[]{2,5,5,10,10,13,25,27,29,29,29,30,42,48,48,52,56,57,62,64,65,66,68,76,85,89,91},new int[]{7,15,27,32,40,44,49,49,63,65,67,69,70,70,71,71,73,74,80,84,84,85,88,89,92,95,97},new int[]{4,9,10,14,27,30,30,36,37,38,39,41,44,45,46,50,52,60,62,63,68,76,77,81,82,88,94},new int[]{5,6,9,10,11,19,24,26,30,31,34,46,47,54,56,56,59,62,66,71,79,87,89,90,92,99,99},new int[]{3,5,6,6,15,21,23,28,32,50,50,56,65,66,75,76,82,85,85,87,88,90,93,94,97,97,99},new int[]{10,13,13,15,16,19,21,26,30,51,55,59,60,61,63,66,67,77,77,83,87,89,89,90,92,97,99},new int[]{8,10,10,11,12,13,16,25,31,33,34,36,36,44,48,58,62,67,73,75,76,80,84,89,91,96,98},new int[]{10,12,22,25,28,29,40,41,42,47,48,50,55,58,62,72,72,72,76,79,81,82,85,94,95,98,99},new int[]{4,5,6,7,9,15,22,23,26,27,31,33,34,37,47,52,52,54,54,56,63,72,84,91,92,99,99},new int[]{17,18,22,25,31,36,36,36,36,37,42,45,46,51,51,62,68,73,83,87,88,90,91,92,95,96,97}}); param5.add(new int[][]{new int[]{32,-72,-76,-6,4,-42,-82,-6,-52,24,88,8,78,82},new int[]{-20,18,-68,48,-64,40,-26,22,80,-52,-98,-28,-6,-76},new int[]{-68,20,-52,-90,-78,96,-20,56,-28,-88,-80,60,30,38},new int[]{-12,58,48,58,-78,14,-36,82,-66,-52,36,-26,90,-90},new int[]{-76,24,-46,-2,-76,-62,-50,-64,72,-52,-62,84,-20,12},new int[]{-66,-8,40,20,-56,-42,90,32,40,-8,-28,78,76,-78},new int[]{-82,38,28,-26,-72,-96,-60,-66,28,94,10,-30,24,-90},new int[]{66,-14,24,80,-38,-4,52,-94,-40,26,6,58,40,-74},new int[]{72,78,62,-40,-30,-4,-82,66,-32,6,-72,0,56,42},new int[]{74,62,16,-4,36,-38,-30,-18,32,-76,12,-52,40,98},new int[]{-88,52,-10,96,12,68,-12,86,4,-84,-54,-90,92,54},new int[]{68,44,-30,-90,52,-96,-44,48,-80,2,12,24,58,-74},new int[]{-78,-24,86,14,-76,46,82,14,6,-10,56,-70,20,80},new int[]{80,38,10,-76,-82,26,32,74,6,76,14,88,24,90}}); param5.add(new int[][]{new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}); param5.add(new int[][]{new int[]{32,76,68,57,32,74,11,94,55},new int[]{53,76,86,95,82,62,51,37,84},new int[]{73,35,43,64,94,53,79,61,20},new int[]{25,5,34,35,84,44,76,20,21},new int[]{18,60,47,2,26,24,80,29,63},new int[]{76,15,47,88,50,90,57,10,14},new int[]{84,17,77,25,28,1,6,19,15},new int[]{22,10,30,53,32,83,28,49,62},new int[]{73,75,57,84,1,93,80,44,55}}); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i),param3.get(i),param4.get(i),param5.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i),param3.get(i),param4.get(i),param5.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
886
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/DIFFERENCE_BETWEEN_HIGHEST_AND_LEAST_FREQUENCIES_IN_AN_ARRAY_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class DIFFERENCE_BETWEEN_HIGHEST_AND_LEAST_FREQUENCIES_IN_AN_ARRAY_1{ static int f_gold ( int arr [ ] , int n ) { Map < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int max_count = 0 , min_count = n ; for ( Map . Entry < Integer , Integer > x : mp . entrySet ( ) ) { max_count = Math . max ( max_count , x . getValue ( ) ) ; min_count = Math . min ( min_count , x . getValue ( ) ) ; } return ( max_count - min_count ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{2,3,23,24,39,53,55,57,59,60,68,87}); param0.add(new int[]{-76,46,50,90,-98,98,8,-14,24,-70,-86,-44,-88,-60,76,-16,-24,24,52,-94,-44,-76,60,-12,-70,10,90,70,64,-4,-88,28,62,74,-30,64,-78,-54,14,62,40,76,-26,26}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{61,48,24,48,26,49,90,88,55,4,49}); param0.add(new int[]{-94,-80,-76,-72,-66,-62,-62,-60,-58,-48,-46,-42,-30,-20,-12,0,8,22,30,36,52,58,64,64,66,66,70,74,78,84,84,92,94,96}); param0.add(new int[]{1,1,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0,1,0,0,0,1,1,1,1,0,0,1,0,0,0,1,0,1}); param0.add(new int[]{4,9,20,22,24,29,30,34,51,54,55,60,76,94,99}); param0.add(new int[]{2,46,72,0,60,32,24,-12,-54,86,-78,8,10,22,98,4,-56,-94,52,30,16,-14,80,96,22,86,6,-34,92,-50,0,-6,16,32,58,-74,-16,-70,-88,70,-16}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{76,63,32,60,35,16,36,56,30,32,79,21,56,40,93,54,30,89,20,74,95,1,74,18,57,59,13}); List<Integer> param1 = new ArrayList<>(); param1.add(7); param1.add(37); param1.add(19); param1.add(6); param1.add(30); param1.add(33); param1.add(11); param1.add(22); param1.add(33); param1.add(26); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
887
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/WAYS_TRANSFORMING_ONE_STRING_REMOVING_0_CHARACTERS.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class WAYS_TRANSFORMING_ONE_STRING_REMOVING_0_CHARACTERS{ static int f_gold ( String a , String b ) { int n = a . length ( ) , m = b . length ( ) ; if ( m == 0 ) { return 1 ; } int dp [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( i == 0 ) { if ( j == 0 ) { dp [ i ] [ j ] = ( a . charAt ( j ) == b . charAt ( i ) ) ? 1 : 0 ; } else if ( a . charAt ( j ) == b . charAt ( i ) ) { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + 1 ; } else { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; } } else if ( a . charAt ( j ) == b . charAt ( i ) ) { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j - 1 ] ; } else { dp [ i ] [ j ] = dp [ i ] [ j - 1 ] ; } } } return dp [ m - 1 ] [ n - 1 ] ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("abcccdf"); param0.add("aabba"); param0.add("aabsdfljk"); param0.add("IONiqV"); param0.add("9667771256770"); param0.add("10001011"); param0.add("fczbDtMDT"); param0.add("298746088"); param0.add("01100011000"); param0.add("Qk"); List<String> param1 = new ArrayList<>(); param1.add("abccdf"); param1.add("ab"); param1.add("aa"); param1.add("XKbBiGZ"); param1.add("50915176"); param1.add("01"); param1.add("FbX"); param1.add("29888"); param1.add("0"); param1.add(""); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
888
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/MARKOV_MATRIX.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class MARKOV_MATRIX{ static boolean f_gold ( double m [ ] [ ] ) { for ( int i = 0 ; i < m . length ; i ++ ) { double sum = 0 ; for ( int j = 0 ; j < m [ i ] . length ; j ++ ) sum = sum + m [ i ] [ j ] ; if ( sum != 1 ) return false ; } return true ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<double [ ] [ ]> param0 = new ArrayList<>(); param0.add(new double[][]{new double[]{ 0, 0, 1 }, new double[]{ 0.5, 0, 0.5 }, new double[]{ 1, 0, 0 }}); param0.add(new double[][]{new double[]{ 0, 0, 1 }, new double[]{ 0.5, 0, 0.51 }, new double[]{ 1, 0, 0 }}); param0.add(new double[][]{new double[]{ 0, 0, 0.9 }, new double[]{ 1, 0, 0.1 }, new double[]{ 0, 1, 0 }}); param0.add(new double[][]{new double[]{}}); param0.add(new double[][]{new double[]{ 0, 1 }, new double[]{ 0.9, 0.1}, new double[]{ 0, 1}}); param0.add(new double[][]{new double[]{ 1 }}); param0.add(new double[][]{new double[]{1800.5208165864472,5129.668497755772,4091.578454432755,9520.788540775387,9012.789443327169,5479.787317916788,4846.101760095075,9310.645104102381,6862.485564868333,6537.037513320974,7943.016882755804},new double[]{8081.404685413337,2775.350842660207,3624.18060172129,320.5505410412923,896.5298358859519,9778.851990348234,8093.842945978867,5513.194168934705,3238.213662532161,2068.183825530009,8922.404213665432,2564.415908565606,9541.992473376376,3500.695185589028,7425.292941600525,1035.1769706476443,1993.3236514377372,7516.6428866994665,7036.757321520528,4521.722941224576,6046.954992856951,1480.947630193744,2468.314968942801,6721.875264461492,729.3668691453537,7013.1702771055125,620.7860776027774,4073.8164568995426,6637.935131989998,4970.880129282128,8491.291538095455,6017.257595728452,8758.321951108288,7450.774705441449,2430.104778991052,7653.421788466134,9867.846002930755,9025.832543077806,3130.4709292949738},new double[]{4092.6187809701687,3682.191052666517,6210.3251142981435,7559.705041866003,8083.3992753238235,7027.888848387021,322.813354455147,6396.660665360345},new double[]{6712.595190644637,3351.7854488023168,3596.9007070939974,7383.906373292954,6925.055360334225,6564.096130017967,9810.727474966703,1812.3875023392943,7582.083184537618,6792.011378435494,6737.106729773401,5165.155358877282,7694.499267616087,3564.5292718018964,8125.369501443796,7515.428339325206,3373.5371602639975,8145.31715886053,6297.6183870619725,489.2402023933884,9562.673985208492,6553.732669130852,7196.924911915597,9239.272829887721,5855.3831715786055,9570.600140348652,6684.3117497126605,9977.065074407292,9210.767097725591,3456.1818868411087},new double[]{4472.26489764256,7298.311171623871,6184.798212074516,5645.069795561799,9113.123076453292,5537.618956455394,2142.794697171854,8370.190271064876,5972.2448507765475,6299.8293468991715,7388.052824286836,735.079089195314,4216.330577355761,928.9766117855969,1935.1190718709943,5606.352487792576,9764.404560908582,5301.250390178857,2250.0545430370357,8159.5544835139635,1327.0903534461743,7505.6753057440255,9918.714694238013,8827.139931812451,1859.1883736005789,8018.161213209266,7984.370920859778,288.30827861459517,1461.0614788611754,2690.173572057434,8427.499467578928,4724.15901701013,4457.387382560547,9993.904502656509},new double[]{2842.9663139830186,8957.4584498927,8686.31672019927,4832.99654565389},new double[]{1477.392902127036,7189.591229360169,8822.61208105902,4851.411807703794,9600.384550545641,5836.4581179869165,2366.7307632417446,9442.85367113618,9848.096373489492,3805.2945900367695,2741.21016804169,7787.421240650287,5163.029236960128,3839.164193518556,8999.926058466983,5787.032859796697,7669.921381103829,7893.275228211627,1051.182564195985,7017.888839448166,5215.123486606644,5208.568127672256,1134.2054935790945,7573.233029924398,6060.282198006302,1395.7596136070006,3653.7960603925126,244.94506756705502,3594.7042035479526,6272.774300983842,4043.3735550683537,2274.103544548338,4022.0181987353485,9109.556771757481,4286.57480001852,6721.662297331347,6105.99828625709,8758.359235513371,1658.875171187041,2024.5696201552444},new double[]{5912.554579767912,5341.080476025451,4305.59603125092,9800.436262778925,8097.160534980595,493.9680676037761,4047.191664109233,6070.216899309564,5697.682730828276,9448.806800500452,7698.114392101278,7020.216498152797,7091.797827878821,3273.5516687760546,3685.5162670409804,2210.2161977720316,7182.207804931318,3265.217158812098,1798.8408452362914,9318.266496779846,2859.486203159565,4314.215039310549,8313.026936365693},new double[]{8911.686558511605,5660.199086800985,6475.525180381277,4040.3172648744144,5708.611042449874,9524.099373256367,7030.627120796817,783.4145757917787,9713.798324426925,5284.149579386235,986.5900188717991,2567.146044707662,2034.3874533234496,7853.582414512236,5610.18808118777,9372.679297083534,1227.8195252860025,8558.328099907549,5800.797131024546,1345.9810037159548,8059.092655056248,1007.7145561634637,1867.8280914974055,8073.000957658564}}); param0.add(new double[][]{new double[]{9784.847472945596,1467.4849690692215,326.01056399299114,3577.1820356491303,3413.7335834614014,5621.398199278954,75.70726246875714,3072.65108747655,7278.353400799695,4703.166022097605,9423.746532838595,9651.338090892916,7908.363875282913,2112.03821823538,1975.7721197648048,1044.0925741602891,8579.267990348524,3350.769942053501,5299.788699272214,7928.710248719408,8396.62857032498,3836.1908586465343,8012.249410750618,7828.91833852811,1917.7798073113083,5120.386576342888,3678.786128839827,4600.911873999521,9497.461077450645,3000.203085004004,7858.544769795873,8325.214884003173,2451.061402910233,647.2264467569499,7282.170138249182,2285.3064693716783,5922.10840378214,6916.751327338277,7063.312743282037,6645.4394853366075,5500.794550321606,7493.492320906113,7206.786508904741,2686.298332703524,2538.8761292983,7253.98778369984},new double[]{4241.304996916518,483.6596378334046,2763.9580150656075,1405.7652499741057,258.3758368726019,6614.609227113464,2961.514732472338,9474.777783117728,2912.5365535711267,5242.8884354914,2501.548861500482,6531.229223937745,4140.476002883762,132.56892540437048,3020.289197641887,5554.185397774308,8773.09782632125,5011.890905582158,8392.625753242448,7800.7407071334765,4421.736562443395,52.49756244802284,7333.792465191643,1840.7462281638009,7908.087535935016,3036.262276198375,3509.2829531181924,7645.618711034763,5397.717763289013,3243.612078360748,34.14499888319544,3384.2995707615296,4853.062855850027,2223.4821740514067,7479.5354594110395,5969.120408179362,5192.807647536894,3509.0771162909696,7334.4495826109105,4987.315435971069,6816.016561595986,442.4714082796233,65.9273693936524,9593.436472709476,2670.0620305702496,4952.745706389296,6867.130101433143},new double[]{1926.3801797530411,4684.089278792868,1544.945305609513,712.4317947088488,6354.9413872948935,2717.619315479798,6846.354537398023,3775.3936214538207,6375.903394134439,1363.1538350088424,2277.399819529351,4091.6667790722695,3659.9052193584657,3149.203276820165,7595.555393770957,5372.782288919421,8515.657623246656,3159.662631217324,4043.737445094111,1842.2411676778072,9713.005101273826,2832.78160742499,4589.20341066574,9043.00917767472},new double[]{3498.6444148809305,2140.852698797143,4510.872710314036,2990.179189617128,7420.541642401762,1033.9572862948598},new double[]{2794.437679786802,3463.1871053331233,9732.829396187464,663.0832249897201,5276.910560721226,481.59416166211446,2090.2478003682513,4558.692561388009,8758.39373387397,4610.715817786542,9921.398649289273,1682.6982416319624,3585.6795224563066,3977.0601543964967,9993.300034767055,8757.889303531827,1287.4604767598673,9265.34884519963,9590.296620414523,3376.6132678108816,795.8613040403706,6807.576250770766,6498.575499062116,3521.0998180866904,818.8610607244495,1889.8998767199425,3567.5388991226396,3904.860163650392,7927.945627565823,5684.632085876909,2665.280318592044,3200.1780479713084,4080.5659548739804,4423.8860644441,2026.9544154357254,6542.038761607715,371.810846991496,9089.128291277799,7033.856907920886,1925.889920294268,7735.925631486304},new double[]{650.8667327357808,4738.836852826164,3985.4301749766173,1955.6572393313954,3810.217150006002,8241.6067168621,2457.8677884976973,5043.061693161945,4098.220705621862,8311.523429129516,2613.3577094067405,8951.447431099867,3413.493711945631,195.07449236425666,3526.5261452758646,5987.082440383985,7672.683285206186,8940.181891567034,8715.378318384124,1609.9269146079098,5147.181463101181,3305.462535094599,9965.648218377532,3910.7964252545266,8068.070848658828,4992.46105696117,116.74465555125413,3636.501190685493,6298.365303023811,758.4342724419646,9850.35171473097,6154.099626143185,6627.416733525318,2147.4459586732773,4542.271637456006,6116.269798885344,1404.5680346185973,5378.69792918011},new double[]{283.30445322594545,1212.7329453006353,6176.516523951887,7361.713020934436,446.2529292320283,3573.9634384317155,2866.7667140384456,716.9415721666761,2066.5957334633813,8494.234070043816,6193.876480036603},new double[]{2136.416496948584,4757.490297134756,1761.236114129905,9672.92860361088,292.470289758332,2616.287787938537,2448.153310489565,8852.291381698386,9393.592818697269,1859.3755772816644,7576.3934917486795,2082.9223147752805,2503.5367105046867,6532.795825292272,9756.064172800725},new double[]{2016.9598997834726,9246.468446682007,7917.631622499911,7530.075198225538,1619.9210624035043,8192.289210321009,111.78933513454669,1304.2859282076513,752.9875736889525,805.8026634404869,3551.4066295443845,5397.733935371496,4669.6567467481555,4794.75142820851,4543.875056844882,3805.9629250337543,5742.679148326456,3813.8720700893437,5210.151412919032,5556.602949642819,2200.424210202666,5908.92594615778,13.819841484519202,1329.454109503373,3028.833109958248,8592.293540323464,9978.59670979421,3605.121961455566,5381.409564276148,1891.7229437227568,625.9300378157828,2758.668754886496,6051.709933922486,6457.36281514481,5548.754777623672},new double[]{8850.151741072603,6337.421968969598,6419.680943286824,9156.134838807471,8322.880320938539,5346.094263229739,8840.13035584083,4662.998040082982,5049.325678804513,6885.637071688473,4883.744421558373,2324.765558938434,995.0281814899331,4461.416494281927,9543.834187148504,784.6027172885606,4558.569173648864,7373.848141952878,9152.707277929396,3448.6407116186224,3753.543292707031,4293.096821412292},new double[]{1409.0526006258365,816.3081240623837,2140.41426162899,728.4924219143152,2193.525472941873,4035.7606724635307,6500.846781261058,5527.736115595666,2134.0180018693986,6779.435167553661,1806.1545644495725,9627.301890803697},new double[]{2371.0568858922543,3268.660813251466,1707.0991863723361,5378.8673760312895,4595.50873089922,2635.8908557704995,691.8444475043295,1624.4384043918103,8928.107824993145,6825.313895904731,8182.165500835241,2451.226122788347,7782.688704839678,6441.579872434251,4321.009439314746,4899.256098629653,5519.087620918876,45.86639299398176,429.87376466871564,6270.117082341795,6415.83724491815,590.2483422808136,2744.8282476562367,3286.420684963404,9655.583401408132,5203.85048223821,8915.078884333285,2608.1519486714988,886.3789741564909,6130.506796586644,6650.901924046862,6646.892160204216,3289.49925972008,5166.474954280374,6759.760310020064,5274.430205929131,5227.164076346812,8287.373511433061,8205.14217850992,3862.4949439064203,7981.66493597097,3621.863491818439,1773.8539613657788,7194.120248679593,6717.104192113617,9016.56618386249},new double[]{4918.488645705508,4863.9376793380325,7980.4716752546,8867.75386799514,7286.076902807735,6413.32763495569,7345.819132709017,610.4954669263795,6823.681549442864,1375.05106487004,5238.380502512437,2773.5771144536634,1491.8279295443392,7856.576929303261,6541.511110001304,9898.82817639193,2431.5435459289947,2730.7902667354133,9195.287603503173,6925.56268238798,5431.128027542276,8702.555149921645,6465.507768740284,9314.270576749725,6272.806736480676,3446.023537244589,6842.356648227475,5788.729554244277,1502.222414850204,5144.345936259722,6576.536519145917,2388.5817800660634,9895.843552802167,8863.44954106686,8659.39270167813,6782.724020047004,6901.026465987045},new double[]{9835.349971287455,1349.9943677780557,9305.006231475043,7682.072854084074,7772.435685418998,6457.172433005703,2271.0896412754787,147.3581960989412,5040.667292338796,5347.141489987937,3007.9371262367195},new double[]{6024.724622587527,1333.55102363379,7543.244958334469,9460.475824602792,5402.777961971936,8618.077786578586,7680.609290490088,5356.651624620611,3081.6630316517667,9965.820175569215,7449.902533219914,2376.8033440694426,2121.6403598925017,5899.797061644942,8738.967016335799,6819.82087022954},new double[]{3658.3990216338057,5939.885133721119,6112.535663798665,4603.757105062263,3601.7182918941257,2699.3894158179332,7634.713427911456,1785.935936680989,6282.120568441831,5216.58891069557,5607.715652949593,5173.8490353923025,7091.689227700492,7231.192245003612,8164.945945372898,691.0808086432995,8884.363372959273,880.702711513005,2983.6539638181393,7041.501334247409,2686.9984210291477,6039.4806880060305,4397.578815778263,4727.811059409236,8382.722608048367,9206.150345275291,172.2170912991472,2020.4702767795213,5489.448690729701,2451.26584431948,3295.4350676203826,4629.077813268916,343.6354616846271,5913.229158529008,2178.835131759951,8464.236722574358,598.6751867838647,1890.7273951970649,9233.763123524577,3511.4462447810624,7198.449866811291,7009.77653163331,8249.84422453666,4282.457347563149,2271.24825809504,5764.120163554731,5765.436670299819,8908.501071223765,2586.0376485095303},new double[]{4178.517530004291,8230.813420124246,1482.5779208939982,9884.823630994786,7654.976401516819,7172.9744832796405,6743.457935859208,2332.0202265026755,6512.820966135465,7899.27033659936,6446.637651589306,3660.9711365100516,6983.0340219305535,8514.370249450678,1743.2333221598017,5103.440073973708,9266.372786086862,4118.043957388042,5646.298272664013,5981.854812259621,3200.6662612242185,6635.177996178426,9679.83767911182,3226.414516089032,9037.63040871817,1667.244125906292,437.75555568785876,8080.445197603589,7182.504146702597,8450.080668876279,5837.320531337393,375.1630048786392,6609.658242430057,4138.324209656617,4978.355962743171},new double[]{6943.097108273823,8155.800311882496,881.1561722205652,6892.581313027855,8870.412782607324,8669.932116289347,570.9050959816841,3403.556267239408,6454.311530504761,1789.7908209345858,7910.710586936548,5812.846543860358,6168.21145124294,2131.0842431388164,2770.4029575820955,1574.8495056694844,8538.95214350614,3406.107386087113,2908.900240552177,9882.928919376212,2844.4878840063193,43.21457208309343,7278.594953930636,9356.662142497536,6209.878587941289,3990.0985725352966,414.3501395268456,8619.011907510358,6999.1215509988015,2882.9851019850194},new double[]{9844.923038076766,6980.156846171918,3950.1442565126367,3157.4009365459556,5223.187529515773,4385.453833112532,5325.893429872211,3353.2248195726265,2442.165605224922,3655.8385765512303,3898.449238531656,8850.04098103363,6831.015148578976,4445.821672553541,9928.380860823137,9561.952605608369,1591.1130291936638,5403.707165706667,2275.6687548872,887.1665703941445,1270.6708733832606,15.351416031957887,6885.875136030228,9550.622085409022,769.7305357431617,4632.5188789504755,3118.15405662019,7553.524447042849,4528.6508356550885,6481.3993346127445,6479.947453700064,5346.224605722107,7272.600816935826,261.5836192208221,5155.049534248697,5501.689301147346,417.6298514208843,2176.1185299140107,6866.720403076896,2801.874422363495,6539.364493633207,2948.3952227572686,3413.699419210543,8937.812262772239,260.2567282196444,9974.652627956628,3607.8218449527135,4313.257989389619,5126.9798391913355},new double[]{6633.663300606726,1812.9942057781057,1654.7655510188663,8405.163469784291,1953.9035308876119,8957.383693535636,1421.2991902099047,9264.40639576394,8150.024375652974,2257.3830199676427,2479.3344627483484,4043.056101781555,9247.05324493969,7363.206663924256,8490.180569522778,2927.295097067805,3679.2436731106004,3838.815927824232,3115.4209839633218,7612.651962526704,7076.710446359618,825.7143449578574,9864.274122425695,9647.78655096705,7548.744154086509,9815.450355850051,8653.699152037381,4050.238822185216,5272.888444100065,6951.384129122965,1394.39534640736,7755.935683847396,5317.102211979815},new double[]{8829.674867773414,6689.896932346349,1968.0933078351115,4809.007582058182,6069.87219516547,9766.476615420386,8993.904574223372,281.1877463140244,5576.660306049759,7140.548946726968,2518.194869927194,2172.7143296254435,5507.955541433988,5420.491404996137,8394.755280403098,4012.132315372791,6389.889892691528,717.5893819573375,2875.0684389259386,5280.900234755885,8161.863197586057,3926.09778356536,7022.709269632878,106.07736204608864,2617.3249490483054,8109.0289788950895,4083.165322330473,5420.617161522736,4445.31100910545,9393.19511825442,176.7904030369116,514.69093147267,7614.2873289591125,6264.256156371076,1595.849249955039,4210.816847220884,127.47354248535902,9212.920824942166,2676.3018953846185,7651.925841175547,4176.854241193708,3254.032717531873,5064.677632904187},new double[]{2933.30773145417,7167.004460596055,6730.0751341762925,1612.3416038398664,9996.385398599057},new double[]{1469.1245592389023,738.4910375434861,5091.743233692105,4943.243843219373,8276.601429613058,2099.0155722034933,1123.1905308985645,8721.083497458614,9900.434613544232,7607.245058601638,5384.468994284775,7529.134743235198,6837.595578988219,4384.871356847701,63.287732870004334,2024.4193945797394,5173.262923609003,5685.6159554472,1043.3138744199034,6561.322154461737,5043.419149196029,1528.205177909735,8635.632452899306,6625.361243781218,1138.9370493081663,8600.196985866145,1988.3249787645564,2698.6573886862807,3376.856288948763,9380.474940630262,3444.5098538813136,7264.095443784668,9446.89932278781,8424.493192525451,9315.526779885298,1047.4543557980887,3662.6853228335076,3828.4452182545315,6635.496292334783,7667.419322235606,35.21225339409906,2963.565449291854,9156.290265259724,7727.156188255046},new double[]{8444.782911920447,1531.875281624423,1699.8134908798013,7098.064080652596,1705.6887525781183,4769.810129535693,4765.399059911866,3365.3409651977972,9969.592937121795,5626.5051907189345,9397.353074698978,3239.97430286867,3201.0073584794072,2131.5074414166947,5957.610797969433,1768.6186313252672,5616.852203640092},new double[]{5673.7710445882185,1647.625614019551,5656.936125270759,1461.1781245051013,6574.86009082487,6774.466975453835,3556.387873542125,6549.504662488484,886.9791309380082,3820.027258607421,5024.250405254414,3506.088366609631,2328.582902932946,3679.112881703358,3462.9919828067,3160.911388035562,1846.9062209575804,7117.953023727776,4143.612558015889,3572.534316888979,319.14170051129065,1991.6701484666844,4560.568775382851,8901.408228818616,6935.299537774818,8511.84810818133,3234.869691027137,1295.0435896601964,8851.889516538351,2489.8888199410617,2150.116130246351,4658.446390325435,5811.264860869128,685.8607919672866,5378.0726932806465,9702.618375935705,9289.55238058894,5269.520454210251,7499.026434764086,6002.394709230661},new double[]{5531.687229932249,5270.626911688324,6624.91325164783,9195.735161525663,9266.277822312304,9275.612244101923,8173.831391641886,1019.8131750228023,3540.52480573109,4983.413349807722,130.21910681093928,9770.440852859852,9084.150791955952,2173.294809269972,2626.817132323017,5925.181708485516,4528.1824472864855,8068.031788501554,3141.2705598953207,3367.1318650759276,4202.813507746614,4921.654402545408,6179.504202375986,405.8037182681518,9118.07199473433,2364.02187704932,7528.315731917878,938.6323242878248,4866.461999667605,9592.4230672652,7487.79868696995,8665.033290573028,2575.202765522496,6907.965979702926,9796.688661165712,9809.595158621196,141.61358495260566,2879.523431694646,9399.935781123395,8148.891111247624,6176.39610921895,5458.065535590684,9057.109293696058,4091.3715908046956,7455.832236582406,8438.475825901112},new double[]{9744.238368205903,7257.463958276382,3501.640602033552,5097.35039463446,8356.088347682142,1013.494789934316,7760.657819535339,2812.190929226328,2095.6075816074826,1500.6497868172942,1593.50863029047,7654.141363404645,3036.4929462046775,1264.0074125211331,7295.376768297045,4806.278483546197,7588.593079677283,862.8315269726494,9602.080432568271,8490.755890338718,6964.467603996281,846.0767010844494,3356.979090302684,8907.430974420711,2398.102582887749,4278.797398815162,830.7948679651822,2273.3942290608734,2275.2588065251434,2776.5976090708787,8490.43423277904,7033.653179624773,7101.244630276114,3462.954058628571}}); param0.add(new double[][]{new double[]{6241.900245829036,6667.025729021001,5691.351954033881,571.7284163476577,599.5121330777808,6243.463062193512,6717.298231363792,3608.7492690924137,9032.092398160055,5926.293767824268,6210.655170074396,4474.741994028476,1861.945257692308,1779.876008485327,5869.991094563328,5423.461312062491,1370.6862587942037,6873.167245632268,7649.546578266097,2351.8399326106596,1989.178556111051,422.20373285440036,2925.774069473833,6272.788011818715,8279.978442600892,5970.172054492473,6285.440742792799,7304.627499347196,372.4523079479392,2940.8339544890937,7317.6400210247875,5166.330426233502,8284.813081839371,4712.766186568946,7997.385423676035},new double[]{6452.611650019052,6533.207730947289,8807.075741968045,9613.017513620158,7551.372353415147,3814.9462465572815,3178.498657329026,807.6312013168241,629.477046023933,5989.092355191663},new double[]{1305.6504233275512,1205.5849470621283,2131.0955750784424,6257.637312213648,8633.528791950788,736.2226708854236,5119.414303257056,8804.172116612383,2288.600322833193,6674.881539883841,5432.169377077389,9984.06868017292,7926.301399413941,2449.424127914216,1688.0860689625322,260.6488247313743,1178.8654972754252,2073.6854863269373,5529.394205300341,7653.727965408834,569.9328536601145,1224.9369795814468,7797.080337878472,1005.767754018665,3090.0776894453675,455.9069614769562,9044.51867916772,1718.965140003418,6583.579031677243,4791.924601541926,7018.857860820445,9808.375188561504,1320.5685001544575,329.7136763666042,6342.892026874494,8972.682821764105,4668.29063954748,6946.344862709311,9805.303722784838,2973.069105760632,6985.874880236632,9545.021104493411,9719.80028292283,7198.598793755461},new double[]{5331.89188600143,3188.443349871333,221.02133512022948,880.68828138539,1515.4027709793838,7930.966870782095,9507.713752644831,4313.160757690817,3846.72384161552,1655.681262068367,55.170275874311116,2949.6754977555197,1910.1840751659095,4244.735303329609,8121.260273473295,3860.8176185770503,4750.489350886882,1467.6363234444666,465.8560983548199,4940.401342901576,5809.536778997865,4565.245203215682},new double[]{6828.767147722977,128.93271215892787,3797.8224655761874,8079.884381341665},new double[]{4517.275715047743,8940.097122408839,7281.039946934588,27.728369323011258,3740.264596087575,4874.93591726158,8043.314070462276,5166.097047074663,4925.980878654775,3648.0727223990084,3791.9876484136016,2912.2565199145156,3834.847575889263,1354.5777786291524,9765.026115064547,7549.4703666134255,1936.525418831999,1478.6811488485152,893.3329941262602,3586.843418684723,7367.442903319976,5813.70155527669,8396.79082639397,8247.306407746588,6074.220118587592,5634.113567301089},new double[]{7096.526417346024,7299.596512835649,6326.555025996232,3505.971650102451,4088.5960369402806,6348.481260870844,1022.4660759645033,6479.299624221714,8255.83540280519,5318.646177823633,385.5360954127318,1742.7901571985306,383.9634977990947},new double[]{8312.439822931368,7693.173653102019,9684.846018395066,5436.851517291458,2240.2570185572104,8549.76817377781,2863.1071822119657,2364.4898333606247,8387.6366465958,235.49213883719779,5635.75381122587,8824.638572201757,5855.982086624727,9390.895322287037,9729.264148554501,7581.889326800262,7539.671214598107,8212.126365277514,3414.4707187305257,2186.9037265717116,148.32911299373586,3907.974409916858,1171.2309102908814,8222.6799813232,9643.24040317058,8560.840012204286,8605.631358897996},new double[]{2080.1073040550423,2877.2637236850574,3818.077902160524,2477.6928693570053,7555.588606535247,3270.181723572487,4332.255274782373,6344.623935872137,7847.221150939287,1112.3530198820374,6944.858605401434,8337.745136833113,5061.397976451156,9552.075051082322,203.72691830435886,1225.1921990053638,3211.0942488406326,1276.8268581899101,7670.342953764469,4181.706551221689,1406.5485053574666,7060.566377790574,25.700288190759757,8334.288430677061,2867.655518166218,9739.933759812533,310.29910419946293,2246.3458997758767,8825.811097236192,8480.717272229293,8484.35331937365,9453.101358520635,5368.758902198425,6711.186412720251,4527.55608166248,9086.130657920075,1931.1440358139143,5924.407535867492,5380.415819375357},new double[]{3846.753290795024,1732.6441416861594,4543.440737272442,7218.242312741953,6321.872177360868,6764.197557825947,3503.1296065699958,4159.706453642625,2760.640834432676,6725.738873358718,593.3134928627992,6645.189779519307,1452.3664747870412,6717.461512638625,9729.597277117091,3076.719110299966,135.3391256749814,7528.0224422840265,6012.289608040301,4014.73128472828,1071.8528463489108,4668.170320820327,9114.25103505039,751.3155545422634,8509.699032980909,8679.657328254336,4057.877122536042,7402.240832613551,4542.251198006061,3308.334311294533,5502.399907436886,4604.392185814295,9896.08110125432,6017.690628500904,8830.375455102685,9694.940638011103,1270.5221941729205,3630.751473478894,6743.2106963398455,4667.728606843594,4731.991841183002,8993.050057035647,4536.511085240959,4828.172159143931,9631.71972231329,3019.3395883885764,5681.601206319076,5189.918716253909,9457.451025038778},new double[]{9858.490575174568,7707.905607803832,5021.584175638065,2126.0930665803635,1093.0428368047963,3745.011847594666,9771.166318207452,472.61146441024306,4008.6772252631677,1585.794170199577,483.33570777268295,5227.284291977262,3565.305570733922,9644.097132819306,829.7755761930725,6055.538965298497,175.36201751864766,3413.0217400469296,2640.2753174918603,9155.091839148372,2204.147217534156,9646.824594662883,5535.653721601298,6999.1296089517145,2052.106730093315,8765.774235212373,5618.504221894872,1823.101083855152,6450.228448742152,3709.0840347005037,2562.8685396231153,9404.89205337425,8223.893813893073},new double[]{2933.9119028337823,1670.1502558318027,6087.785052928502,5830.496579124935,6012.667523752366,8605.549463703592,8391.896202104264,6781.779546376485,8722.263881711979,5244.490064787881,7941.369082757103,9725.010319453018,5820.878548931412,6412.693111293454,8686.079007513366,4832.8557027198185,1971.5020676134554,4713.00315718324,23.95004735105899,2043.0266876244518,1744.4110544238877,9582.30503057717,1370.9954690178238,4895.774712815934,308.82987894597204,4401.248882448594,1374.6357709485146,4959.382604347441,3218.244984172339,1034.0450323702598,6737.440724743908,634.1304172158091,4999.24253043374,6330.331284021177,9139.827275144382},new double[]{6997.489257897447,6806.800562474949,3902.9309997574023,6376.073892981555,1670.3644171585763,7131.487894217919,1408.3540095032376,412.2056336025215,4304.210459722586,3124.575744335187,7828.129832271993,2643.8811253771487,6873.465900546271,6509.248773293544,579.0570266395179,9394.219664404045,8578.463028905046,3835.6538352530943,6162.595716602937,9170.955208900608,2407.4357214948327},new double[]{4870.0107594261635,3324.1339614958356,5932.348671574118,7765.827307806859,2031.094134376461,6089.677488554667,1434.5229583013374,1396.7772537825929,7054.601057121471,1148.3122565408987,7728.834323176571,4487.6592414211855,5517.523660019319,5899.975978067698,3265.7994047891757,7871.939795019093,9946.250158526567,5665.668416355023,6987.594052558873,5279.374685773946,9511.549579080132,431.7493942707229,3461.0964351048756,309.70060280253506,8983.523425189924,2456.575385065778,1265.8660899152085},new double[]{8529.096294439394,2980.465082017305,1247.057568565425,1683.7901051144765,2346.8054018979224,5410.236203075452,9768.449536539629,754.8137030947732,4162.952453094405,6112.1743131963,273.037880594309,808.4213368212689,4615.3391439094175,8759.276596590496,8992.405678183211,3879.2595073552816,7503.976937076325,2178.3774847327077,9626.995412254648,4762.384453793243,4304.784074817238,1051.1728645390829,4006.2527490710277,9709.333274524432,3201.6798740910435,2478.8484504271014,3115.7977329178675,1663.9006122470812,9723.917944178913,8904.652104789036,4893.318186460499,1308.7180114241014,6679.899715892782,5764.6618025963535,3532.443421003797,3583.4289228422845,9154.05602075901,4110.438471296866,547.2737136121641,8607.280965840293,6844.321723607965,7456.603075966929,3281.0807490473303,2789.154901361526,782.2666839299308,4682.115076692754,8304.025574969566},new double[]{7867.432895770139,7142.481633795158,616.3828766647327},new double[]{3387.3802798770657,7144.366061237613,9860.806002618854,8079.830027999986,960.6136403709353,3649.091708134886,2944.5665577603286,4517.417094476161,4018.920033033857,2443.3697424046786,5216.456010749324,8490.246719274373,5191.955006675276,7368.537038688761,1669.5608867539668,3879.493413167572,9889.474876929211,9992.481486612269,3660.7510158002187,8138.870105890437,4698.871535878607,8170.396330191924,2996.6723471223313,3207.835113478479,7602.8165060169995,8428.482452334038,3854.3925110712416,4292.9644291593695,3257.118330538692,3205.1510927519776,2351.8971372001183,7927.634015142587,2271.416178727619,5279.455156231754,9528.477679256916},new double[]{4809.558214848555,6512.113001668395,4126.780341230375,8132.839211158911,3910.846617356295,3156.911078233957,6491.515503128564,6847.145249167793,6321.306375289207},new double[]{5132.246799974731,6370.43772475688,758.3383190726755,3822.1912772556598,8392.762450933264,6840.7826438867105,906.171738227003,3924.4554022145207,4394.162240587243,2168.1300970892626,4967.331263775884,3161.0163687093864,5567.720858829881,7250.935239567056,3349.9827470371847,7062.4877637767795,8205.045407756192,2845.672970275027,3632.275199296913,6278.2813550024985,3311.7990092854398,1244.3732947943565,125.2291572270614,966.8954156959719,594.1764921541792,665.1263367721838,6373.084192169837,2661.853212656231,4270.594558825736,3354.1377968170336,4191.810824563139,1447.4469824976234,6100.290756172702,7643.94222186592,8064.262463824555,4159.99596569145,314.409524232685,9662.847377558683,1963.453914000497,3833.110525685618,1382.4852909355711,5216.451524604983,1923.6243302753153,9366.946960746385,7010.521276782435,6438.24964953168,6613.800664284052},new double[]{383.97664429939414,6189.259103225889,223.53430583521904,6482.472343800064,2428.333587831151,9818.068366530008,9781.347438012055},new double[]{3898.2961108062773,9291.534494677917,7317.398922809986,6426.207629331639,6967.6541718465505,3752.1475543957704,9733.352111551661,5361.463573450924,7189.933607605151,8777.4997082165,2824.233126142458,7816.366398242133,877.4402752427968,6056.868857289174,2182.6819683042677,1280.1579204947611,4436.555287965954,1661.3145376490336,2092.423589364817,8260.380550864431,5966.315646458932,2432.5698050980773,2739.185628046621,7245.886255806842,268.77157782930425,1233.0706867884178,5943.957524802674,7405.470958601446,501.9242163945048,2971.016181534857,7782.648869979246,9913.953451407731},new double[]{2235.11258828775,9865.00539197128,8231.382920563366,2952.921926617926,2929.760559635134,9595.450532333396,6384.407369365793,9412.122783013581,175.63593700402947,9514.63820403047,371.6559244036188,7825.43779507584},new double[]{5590.251121718374,1407.730019930593,6933.377338234666,538.4946470584406,3654.1200805880903,5562.66912969946,8950.192777377413,312.53390952430624,1975.0088926924968,8822.979565516376,6368.251716233585,3094.0902834724347,2238.6087134777144},new double[]{8225.011588911006,447.0286611190544,2531.794580124993,5786.881077286801,399.8362563738822,1165.8075770758226,2026.1937515817751,196.0265843025899,9049.138866114914,9141.277243142813,1800.317527008992,688.9468968954048,1037.703653911477,5719.273573098196,8613.212547189436,447.6345582866159,2408.581086134727,338.52365298329136,8235.860036451202,8121.796753653178,836.9094638861175,8.520867197108206,4628.612686002925,4344.374163287639,9274.546442753306,2372.0278182942657,3812.8030782577302,3816.980924729987,9211.587577868697,6548.961092866181,7683.6400177831965,7210.282733624986,8488.116010841984,102.69806692702055,7549.429474892514,6546.469769481529,6756.096944305571,8869.645061932615,6320.84551678245,720.6570295438963,9866.068905769132,475.1409373336379,2798.0614694422534,9503.48700738789,8161.54971021859,1975.2144598311195,3184.9270319596735,7500.649344847348,2844.260413115036},new double[]{2214.984180049143,9727.826331483277,7671.809203158182,2004.4891504845953,512.5558446894618,3765.2938342348407,831.8376948644524,4359.633550677039,3161.4136806221513,7426.701730205041},new double[]{6151.439311123929,8562.409749844177,139.99318421840434,2266.860770807414,5297.3617285961345,6076.901805064366,3547.03069618111,1096.5089121097703,6608.441477711436,8666.842749849327,1964.6619061874371,9606.368642264752,7790.148934891385,633.3946589981099,3781.3793526328354,6340.4956514955,5472.202059979498,5763.352374526418,1576.1085832246936,5536.915866053031,2880.5928523811176,4004.5592639781657,1666.2604767999255,6223.937189676776,8128.506855231704,5905.0244628740575,1954.6037073995114,7090.29168428198,5371.213723343435,9349.180160309432,1526.9429567895588,556.8638591150853,6433.413998565571,2525.8470467800466,3589.839806422006,6087.283736251727},new double[]{7911.322186291536,5780.619078872976,2943.817961220151,4381.303592508306,5014.256467510416,8988.614196928396,1582.6519734764588,6647.652615108409,877.1562024007295,1358.4933337219384},new double[]{1406.4943067285296,73.1155948257911,5031.850371822942,9438.22435420941,5108.465505806064,1042.4364006211772,1314.8948841112551,3329.40053119417,1146.2165867620633,4715.847078578909,3456.824393156518,2196.2603568035543,29.439396941270957,1270.3641942313304,4177.467361294353,1746.6041587714087,5911.9535732701015,6454.244236090103,2688.3784140475386,5617.285110191332,5303.427954073207,4387.293331306137,611.7548697546293,8811.91974824338,7078.516064797247,7901.196772955747,1924.5406523846564,4774.936619560966,7355.620204940925},new double[]{6035.935933113421,1226.8040806777858,5523.165617454097,8836.579142603414,1113.4671947565266,8213.4907263991,7745.084802654282,6340.957509377881,415.03468684295774,6608.493692843055,7044.121740102962,8825.803590215197,4881.442071527774,3642.575044234495},new double[]{6626.512216159988,308.96301872390785,8388.25754694902,5486.470145073442,997.4133362297155,4392.157919012072,8252.447545916273,8907.78626494242,3842.258839697337,3161.5035951132877,8956.139755168353,4045.1642497512407,4844.111745415444,7848.103760574075,4494.6730721434515,6180.269049242508,7409.033590289328,985.7402365643653,7196.726412389427},new double[]{269.77648903710906,1126.2237816718923},new double[]{2040.8906107327562,3413.4874201388643,489.57760152147813,3076.601982325039,9102.021349349618,1200.7208827667926,699.6162509403681,3101.634796437868,3701.554108779237,2411.9592533702184,9068.483763610337,4673.493274371369,1056.6528905404548,6871.406578573134,7815.186266363301,899.8258379586932,7810.1777339325,1923.2736881495427,4907.3553254635835,36.26787738972514,9500.035076375627,4385.290183219543,7381.672654939276,4931.537531704371,9805.425209816323},new double[]{5022.436273571402,1197.1797908028402,2513.282515620119,7293.5846831339295,7864.075502303563,2488.338611262899,6965.7072214240725,662.562087608145,4890.8534220629,5960.8202659888675,6913.129571853039,4416.960377812348,8846.58033596835,6414.317693274189,4127.7024306320955,6366.8329968171465,9450.85060725369,5628.414242086556,192.2829859747388,7182.850802625099,63.242532136027485,2300.6925952920365,8846.636183933997,3146.563889171922,3754.3555017824315,5770.426368716938},new double[]{5173.830964715877,9890.226777233238,1098.9324114713784,364.69864035620805,7723.254271184315,5517.0747971463215,6972.82355850263,4377.688324442222,3927.513417754829,4505.799939384594,7355.8915738696105,1411.590170602457,4931.86251176953,986.90822558536,8508.137950915048,2684.400565521672,7897.155849168546,8674.145789673083,2086.0891380332114,7705.480883689803,4665.449845287386,6076.212330681365,9407.328687432935,5689.684512793414,1831.0823727388226,6617.606692308336,5668.947544401989,8930.611145243207,8224.113654367518,8359.300795112244,3864.5610824686105,9390.681712139136,2815.184988367545},new double[]{2602.1776608357204},new double[]{3407.007216757638,5724.919154311412,9384.166952517773,9690.602472466697},new double[]{8102.976838398982,8849.784140503656,7407.679966884767,9836.701623369934,1872.432781723563,7281.574637677118,8845.592713310316,6876.737462800879,7233.376167426852,9591.734515742108,7484.535374322941,6180.868036361612,28.122053896075805,4850.750074639563,2077.221298467284,8422.360632110873,5304.079773970775,5150.322617258653,7715.594320512252,8676.906084883474,7063.087615208,4508.300896683666,1870.212325326055,1855.075140914788,9334.738195960335,1656.1473401916626,9367.672340533432,8863.981457613274,6546.8262011327115,9347.669364392037,4747.065472443352,5745.848959644722,9360.338955845944,2937.7200808032158},new double[]{6482.8595704273275,8499.749853293006,8440.713898627073,8891.227554738834,3180.022519782436,7880.759241944946,6056.006933773436,5912.350437476278,699.4588114039491,886.0079001140298,1822.0626664815043,381.420906591744,2607.676451122073,3181.804873120423,8202.497429425099,6359.467064904772,1496.8293150201127,6518.407076371044,9320.042455571478,2666.589843222107,3625.619379089742,7276.918882277939,1184.0298425253427,5821.374205476385,6630.175663663377,3266.1551529734134,6400.107810482856,9315.153890473555},new double[]{1696.949632803242,6995.182554254953,4565.512300553068,1555.3469991121383,3041.5235799893594,4512.822786172634,3333.4924190545357,1059.10366673576,7496.936219842324},new double[]{671.3629839557877,2236.177889510651,5329.515026552306,2048.8616958059147,5268.330992320453,7702.435041792674,2049.848128237071,6051.912730570009,2654.641081175706,6731.628675509916,245.1033485342835,7262.8856488773345,3833.741123694605,9584.561119746415,9459.311341921759,4189.750168909049,3206.6744841142604,6161.937614136377,1550.3029984999139,7403.993593415656,1347.1793632618455,8322.590251110072,659.5491192120628,9343.3284201924},new double[]{2952.3815506071505},new double[]{9115.411311885711,6190.606498203099,4032.1155657850204,7875.049545423708,9466.12681849252,5594.839737431558,8428.888075075625,1941.9962664072598,9032.133764189743,4804.826796327835,4821.763408431451,8570.546357430994,3087.060817370136,2488.6336685063193,917.2654167233518,237.61057335929036,3926.491893192462,9982.873336882416,5210.955793121945,9577.59684717213,562.8793455645009,9974.932039818228,4114.927049501123},new double[]{9536.842393889692,1523.764350514798,4576.664144907182,5555.333574049817,556.0702052726873,5695.790313120072,2940.1550048338086,8906.823029982179,9247.57985609783,5670.479097671544,1563.240912825089,2058.2368149628714,2586.2473296422704,8548.765615315135,6932.512942785251,4001.355017761662,8043.0396628980825,9741.137424824428,1872.3820437759841,7653.178445488161,4468.503690875622,6444.766160470187}}); param0.add(new double[][]{new double[]{9387.34729535443,7898.461949606736,6843.664771769185},new double[]{8854.224557496666,3138.5658050816055,7767.530379809834,7516.323745513028,2207.2409217929144,8693.6916056422,4885.133223819916,8144.646738094058,9472.851132664124,7362.5846712389975,5315.360555945713,1617.4039470690004},new double[]{1687.9209124872664,8464.46411568592,3447.047038096602,6532.400295186251},new double[]{7446.299482513876,5930.804673782114,8777.469690431497,3199.603818228027,615.6806451195662,9000.507773811101,793.3778314067674,9665.503543616267,1423.2311942967624,9058.320927066101,1099.8137862184076,4415.691600581443,8530.398535354901,8250.714975402603,9059.795084829342,90.4120532143693,9022.111328994652,6322.358533615018,9206.94022358282,4798.187993893735,4187.978740159638,8014.734995401485,693.8891854382779,4251.830314994714,6697.295656397563,6335.49700736744,8610.683236059502,6298.635031818236,4038.554993329112,6360.121170960482,4022.0110051334914,1122.5234950192687,6992.0496911377295,2883.123124720399},new double[]{1056.4492709914664,8567.000947158875,217.69313002310332,3254.5002663085174,4601.802558945174,4466.4132948941005,6128.946430118579,148.94225409799898,3118.1375747804864,196.52645396098012,4504.754960546661,9199.006855218553,6614.3828800036,2571.8878153978885,8796.432276470714,7918.001506620834,9596.031561565336,3214.753044787861,9309.630430539835,7439.472072880434,9619.018552587135,4063.006735339747,6358.964169833173,3840.2035380176226,8937.716360911025,1209.3175096114285,1721.522884166612,5216.987384793819,8684.378443881262,5495.2611059262845,2264.1919806259802,1252.543743534026,655.3386733986899,1855.3310449288451,4847.535649990685,997.5111777751711,1053.7363758500662,8535.863237331658,8822.043281415563,3018.8030141675526,503.60316905774914,6032.498466876322,7916.5948041773745,597.6478813730379},new double[]{8684.361358839811,6833.710635677209,2301.7133776801625,275.89397954013384,5627.0885508326655,5749.889984495326,2725.9411491042106,2263.60838765113,3220.8714827441454,2126.1813280018205,6336.34207671731,7815.580881958889,7692.190120063231,1706.9068872384219,7089.19633065844,154.21143066395416,6379.487447831323,6113.035840785786,9292.147103114716,7285.722660158631,4056.822238980331,4410.131230785889,6277.964120928899,8029.2274137176,7759.516664347943,7600.10262069633,6539.162345662414},new double[]{5216.963504767812,6022.3717055600055,875.1699166517468,2976.028433448088,4133.081572570095,3599.4478354607086,1431.019590353102,8171.597170603135,6676.016342458662,7869.493915359824,3017.0303643295547,8547.37163325604,6113.115846890411,72.11597385577306,2408.6468365371115,7992.691113660823,3225.521291389316,5285.023809224858,9981.08193760831,4245.283394786782,9350.710916404942,156.5062811839235,3809.4842218626645,6715.87477975451,4829.110054128289,8193.308772328679,2368.3570505600337,2988.323558107737,8440.90610248902},new double[]{593.9952608207976,9015.387427783953,2400.016721913174,6206.8118144856235,3732.352088196729,1992.9549547278602,866.736134350522},new double[]{6669.381677531302,27.319788257704758,2637.01567068781,3235.943943964311,8162.7447842874735,7427.830546891691,5632.948554742142,5789.085625226065,7072.633727802251,9801.627019837071,481.0860962500385,1929.617450695501,455.0942830517457,7426.258332777612,5315.1712596605685,2377.1485177101213,9147.659669601951,7469.859392568566,2119.6650171808783,7181.008454540089,2241.378497924079,3691.445448003328,7223.51362443932,791.8386282872325,1645.1957081534508,1079.432157932666,3581.8213870239433,1271.6267364206535,6918.799700879627,7066.402451269379,4548.9501257795355,7771.868819145048},new double[]{9581.38150545251,3410.336533530417,2856.7662356133615,2419.0079032541657,950.0224986377892,8837.283092999793,3913.2155959905404,6636.031805779068,7592.195244455631,7420.490147940853,4471.464810532584,2152.5663872694968,9950.003125615844,5917.471879140231,5763.089927390933,7213.237810657768,337.1997863178189,1856.5229771467207,6717.1769095465,3208.231458475995,7184.886781951437,458.4789706683656,6045.885158102913,2424.9990349388263,2896.116810748228,2319.061652740508,2047.4513457389999,6294.492404013903,3334.9834269859025,7368.8970490832635,284.72641721660307,9420.83255298125,9859.380369000763},new double[]{9169.208331579337,6500.7756467671825,4122.966937565739,1544.64347471575,9324.722480784405,8587.01517312793,3984.021827632204,8450.161731137936},new double[]{9258.381063410341,3512.2061527605874,9078.094037081228,8366.947143769201,6274.399530708722,1273.2656720112545,4407.4473886892565,3277.961980926288,6762.275884363325,2485.552997462922,7147.186755311224,6006.1456642302965,648.4562629752044,6627.708061728291,6708.785422640259,875.7117573180994,8684.281779960153,2439.6863224086796,7798.5461247933945,9839.935322794892},new double[]{4370.801958830066,612.4579958308252,6622.693946746825,3699.7853080311447,8397.106214715017,6938.451771935569,964.9701499567243,4097.361978551648,1123.8931687029296,1755.6273056704908,293.17328676051966,6467.777619293823,989.4719132734375,4055.8581179604757,5256.550613502351,1299.925024671782,4789.230643713135,1563.6991704648951,3267.9045898051118,7864.694377084369,1772.628562638382,9651.531346111839,2274.1630302924764,7933.6236919572975,3121.1596560775,8866.91589613497,6246.988735967703,7121.760563780332,4865.089575698644,8281.00498147027,5085.228034421677},new double[]{6404.378481173949,5131.811344485618,4610.269533313499,6136.038498844168,3243.653004693182,8675.223981532241,9075.233149089272,3285.9284650507925,5252.767520217068,9165.91955653066,692.8358131662837,2003.3532713768775},new double[]{2179.555844128038,7795.173390996032,1584.5811576718384,8026.3344366294705,7862.970621698384,7076.0766099803195,3362.8799147016252,1096.8494981635213,2497.3787517671985,6467.47480827266,8147.807275391677,474.7811361711152,3849.1485728177986,8819.114225613455,3643.8263413318837,7149.719973775268,319.94128606343986,351.5817455597814,3887.537481097733},new double[]{6182.269817013097,9932.80710355981,4375.52604490935},new double[]{5497.83023528442,7000.943515738341,9141.649955676245,3984.347222137875,5881.395660547033,432.8745332071515,1390.0548010976754,7169.852370963141,9638.074566266574,8268.269302387289,993.340087420359,8926.312495484106,9963.77867525507,86.23903812557066,6629.0543612085285,7763.969523740677,8484.748606467938,82.25115949979434,8993.610527478002,6335.178529611683,5767.486565260309,6874.79423820253,8047.152345465804,820.8184154530907,7791.514421602571,9961.965504789934,1979.4243726517634,6485.2608094874095,4213.721428033255,6607.888206233299,9702.017369245692,9974.535801268215,4696.642031529939,8132.563081807331,7622.293125092784,1834.6931258898423,7391.987759206572,6500.344830172746,136.48971242386287,4200.133204789978,2785.920779496308,804.8994719309643,2345.9269659084016,8357.06549748538},new double[]{2766.311825930985,247.82286534360765,9210.351083194728,3753.627957345187,7962.917152771212,1751.698129255792,9212.829728137283,682.3310004536054,5741.1142555813885,9761.752456788918,7812.1571286188055,3437.793780763595,7186.784717752445,191.24402764638003,6395.160525892249,5448.899650841235,6448.336342731541,2049.0552692066512,1934.8055240768304,4150.412336537698,3905.3898304258137,2943.1925104202073,7517.903523696381,5241.783668695016,9328.846774552487,7128.137571342247,3454.0132065648754,784.9234765927349,7219.1905595332155,835.6442343664172,5656.669533993148,2383.4909026049236,2681.736245406704,6966.710606643402},new double[]{2063.497842840252,5822.371347317983,5703.419199291243,6524.047902146878,2296.7642952695332},new double[]{1763.4495330058685,934.5148677695203,1619.0205544392566,959.1621826615526,4280.521969824521,1369.5693371906193,3273.1818661012935,5115.8434116212275,5985.42152117378,9527.615090861202,3354.904782657736,7101.616336504692,9762.728037978632,1269.78383882561,4875.059489948114,1497.16737837024,2422.0980602965283,5716.250236875847,6321.505597383554,1340.667838547893,8443.00252703888,3735.8841178907255,4899.856671866332,6720.5246060937625,7750.968585550362,4238.977841764919,5788.14965570911,7274.903802452901,3595.0484545350714},new double[]{9686.865788633631,8233.772964679154,660.7508618276447,6306.683868508095,8498.953442175642,8114.077760774463,1104.754624226918,311.0692755307476,2531.60881014545,8451.28820029444,3200.6570105366095,2869.6853746417128,1238.5022469776386,231.89892573873271,7233.737255599893,8333.686335655733,3494.76478845981,6358.858772951813,1592.5661835891135},new double[]{8729.302351090198,6384.546837461195,7171.290584657766,5957.659783638356,9085.037001227132,5768.356633124855,8327.482562249292,5395.921276883439,1861.2599624881498,4765.111906737132,3378.3810534074432,9947.647762912382,6959.705326382867,3716.9948860458167,3062.662164010396,4763.191664464988,7812.697916882337,7917.498627199334,8870.650688899828,5065.742181053909,2624.806153972363,2975.0483110771174,4364.205465054759,3188.4425422580866,8720.977081893758,1459.87953565746,4572.8264886204215,2324.1540757260946,5840.324208567349,659.1512944086209,6387.2382456619625,1706.1961811177118,4070.0269992801395,6180.002343467976,1707.116403493727,1552.491504085135,1627.8271363780805,710.7568621692617,2873.2219438669295,6894.1926098992,345.15307520545105,3662.3233518062393},new double[]{3211.713546228133,7896.40777964658,5300.8078149063485,6851.224397907975,5696.065461614853,5114.791911160674,2564.1730817028897,935.5405348126611,5153.847785482536,4577.349093295708,669.4749252740984,6331.618429957198,9752.5524618502,4348.913289388088,5360.501700968088,1947.5177649733143,8717.345541701521,2764.158876222086,8439.468669204629,4053.560412732092,7445.1623077869335,2681.809445597795,227.24520795759483,5796.36709151562,1742.0265345346274,8771.734793785536,7678.398207518567,5661.038366465821,3269.4432986394963,8668.907656759158,1676.1950842333351,5480.716778416091},new double[]{936.6238554926199,4417.071383868515,6954.953579576183,5108.719616062134,7182.39821842807,893.3269681291046,9329.321095066078,4580.047117025584,8767.112017513396,5860.985413993845,8199.847852762732,1222.4269503900243,6936.2060001009595,8505.84929950005,9178.71060254381,3564.7845125447475,5204.125789379878,746.5779862826249,3612.5357492902167,8863.338857356202,3207.8067128192033,6411.350131694356},new double[]{6971.463246366584,8656.829488481588,4716.397759444882,1871.0559596524602,1400.7186558055407,7972.157112200225,2785.2894228904734,1230.437360694544,8007.762276598806,2879.918281682995,7129.5575876408775,1804.8918776007638,9866.87453607941,8137.058205998907,9310.146806768604,8140.789040813295,6053.202509221739,1291.6766981885764,5042.499167167728,6617.2901410157865,5184.765799310381,8442.95630985222,5949.8689231126455,5292.165955504016,2849.4937899043603,4906.261299495095,966.3171571506301,8454.562916281682,7489.005406107537,3920.8761213857024,8798.627174192734,2997.865499624235,1711.347679688806,4027.298254353501,2665.297130518587,4207.206327946828,2414.3945246142307,4847.717343608347,1070.5167501685087,1704.8851914439756,8171.119375036566,3723.606800733539,142.2932030262325,9127.383634043443,7118.072266257432},new double[]{339.52074175386815,6222.346927985851,7378.5920594735,6483.541708564634,362.64537232048144,7138.700983753719,2240.2956832486807,2513.294144642031,5297.54986666968,7336.701719593464,8533.030287569201,5619.9926655639065,6020.148727640418,9972.565222705252,2138.7215246647575},new double[]{9334.18747439277,2305.316444035084,1496.1818919744728,2631.664575282966,1560.644447319053,8017.229344306232,6842.526322961845,2122.802524963182,1925.0851490635769,2446.861091468323,9263.77307980419,1483.1424881051537,5287.2562923501,9035.859888041217,8023.375373059005,1509.7451515868177,5603.488799339734,6952.921883793975,2520.825724984489,4774.46952604118,3150.932309635256,9437.021148222304,5408.13867691267,9230.165088724967,7807.315410083818,5405.386628850249,1262.2511910367418,697.3644405937873,698.5354770211683,1350.5821712909406,5683.304986640956,9411.453890399667,7917.412705783028,8454.459445136355,7206.496995251545,4184.077101861108,6457.784133948724,7829.579341560543,9782.181419945555,3072.675129166752},new double[]{8633.9400207655,9053.67914423705,9081.024953660442,2853.802978909221,7098.6377709172775,6442.001286495734,5352.453679308428,6033.86163930825,5295.367200513826,2677.067926657917,7715.416997612096,3788.755738261852,9546.352816383147,2191.2027293058445,5191.987053619508,7361.459537716426,7500.956977764495,370.7365519990435,2962.269562256985,661.6552510251239,1609.4504154422318,3988.587061330161,2398.369174193682,1708.5280616204134,2284.260481124326,1232.8130458617104,7282.24314102055,6095.510118039444,8316.544395798997,4280.1892659343575,8407.096352421157,3773.58249506053,5866.478536674913,1059.4976355232154,4198.072679613927,4234.325659104923,5473.390130450675,2776.1105772896135,1674.2483340926185,9810.681965224623,8123.877611121171,2880.6804254366057,611.8050413036724},new double[]{2993.2135939667937,6516.371756368651,3243.954240688501,1707.4419839480238,6117.910093882588,2728.1465292580765,6634.197180792388,4372.280063161229,9906.755136519236,5628.301297423993,4325.8026028396025,5809.6193319701715,4537.666496279663,5195.153570340511,1449.7797935032452,5993.770275452789},new double[]{4543.424826252607,8348.648362364054,804.5165023634681,1729.8028197600313,1522.5403036030073,3062.049396246639,5614.200983933174,5394.364801574996,6082.364911270015,7322.660128770181,105.67616713120897,3780.024680250308,2043.1384239018603,1911.4871928662747,6600.417413983897,5725.222210135139,3159.2736284331845,7911.867143170885,6910.232736464181,5082.363943676784,398.9266438123795,6600.002726524873,9718.957727352494,373.35598181310934,1769.8440978937858,1423.7660839786836,6709.319258322703,8863.059005113284,8818.99294307518,6869.765112779014,2299.7066087856288},new double[]{5904.333165248659,3737.2540517941134,3234.8010931379345},new double[]{8741.274694147212,8142.366348649237,7178.080069844503},new double[]{9806.546398158205,4111.328970709272,1297.6979885312844,6671.312196519337,919.8636669576166,3674.7691763561584,9558.015583014578,179.15421355732875,6633.7786907057525,5145.041583744364,9650.732970966015,2262.287535355311,4078.381954659066,9352.614142347535,979.6245727881725,1961.1517367115562,671.592570513081,4430.339128069768,2945.127026543707,6308.61484052264,639.7007227096851,5329.702461652472,4258.603814362332,2386.0945919632636,7582.27847122242,531.7809464507307,619.6474357889825,9850.258845427983,3376.8188352510665,1443.5852603295095,5965.538654258386},new double[]{4064.611605775853},new double[]{8699.678950267016,2638.8791938900504,9864.32576829143,9545.45934752491},new double[]{8967.277929781716,158.487360223436,2706.512848604518,7632.722968650326,9493.606876017158,722.3053012762348,6964.558269251513,3890.6533336777193,7324.280695126543,2114.987955696953,6493.602831666873,7861.736242257294,4577.950198510346,1258.5279257186965,8413.280602583125,9809.221728733319,9999.85897125298,2687.9513051743697,4310.701528942745,8308.434209993517,4632.868040691614,1557.6045146848705,2024.6772936559332,4584.237100857744,1162.3893821891406,9006.014395722459,8980.135554758763,9645.94750029713,5807.972419276929,9641.914592343957,6119.365848988399,8925.074625708212},new double[]{3961.038699627797,7941.386171416613,8497.2079090036,950.7156317300869,1002.2655576124373},new double[]{4770.970512462653,5751.274214977394,7374.385304920768,6583.555487016266,1354.1896365063787},new double[]{9019.53955445245,6116.076908287135,8146.602392879152,72.65131447226403,1516.6254211993412,8039.461012121285,5038.821843934121,8391.976024847978,456.503039225048,2670.191490719758,3515.763578768253,1092.421155822273,6164.620640238656,545.5694373578046,4279.737736096799,495.9879677990009,4625.2520594959715},new double[]{1439.336923533866,1302.3118323967053,167.48167583331974,6295.610633433874,6721.42085515711,6293.501666300752,443.10543686137737,5790.080920213072,8246.409203016145,1090.7269189639735,3732.488593915935,2911.804873618257,9941.921987305477,3792.731907876411,4534.224944059517,1472.278357602025,5275.2635084540525,859.5210260889396,9597.694442577425,4899.437560961888,3899.188565008336,291.1982655390333,7689.693286997743,8893.026162327125,4327.722294090344,5068.436180974043,5900.3279123267785,7465.30143721741,7167.568894492006,4383.153760951697,6514.683704147853,3810.559736196162,2522.446986633412,8028.80881494865,8593.830034608267,7739.336291343238,2193.260515869928,4073.821932851648,7770.88670948187,7663.446075181924,5361.707839001343,5038.736484800433,6054.88382711972,8169.620671795285,9367.954744778806,2939.9653782874825,9453.300074929695,2797.1126437886173},new double[]{1566.286547919663,8936.617547502176,9231.73742747379,5926.868366854842,9103.397262654895,8368.856835536099,7101.186219987764,7810.498315791292,7975.613043686254,6534.1573199897975,3221.878461550536,8047.027853088147,4308.07219595293},new double[]{4698.9398220605735,1381.493549044479,2511.354007653047,1792.9062150709663,3433.3984663747965,6310.645731404196,9282.773595893277,1436.72903578846,4255.664980727647,5442.018955197633,9070.360569097147,997.3894557292784,6111.892651874234,9341.385608723269,478.81757295908267,1351.2651210460015,1523.9132106506759,7642.007210066544,8023.924071903322},new double[]{6975.216490755457,545.726967916269,7829.418625853173,285.96897390028687,1788.3485134839195}}); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
889
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/CHOCOLATE_DISTRIBUTION_PROBLEM.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHOCOLATE_DISTRIBUTION_PROBLEM{ static int f_gold ( int arr [ ] , int n , int m ) { if ( m == 0 || n == 0 ) return 0 ; Arrays . sort ( arr ) ; if ( n < m ) return - 1 ; int min_diff = Integer . MAX_VALUE ; int first = 0 , last = 0 ; for ( int i = 0 ; i + m - 1 < n ; i ++ ) { int diff = arr [ i + m - 1 ] - arr [ i ] ; if ( diff < min_diff ) { min_diff = diff ; first = i ; last = i + m - 1 ; } } return ( arr [ last ] - arr [ first ] ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{2,5,11,23,33,35,39,51,52,56,74,76,76,79,85,88,93,98}); param0.add(new int[]{-42,76,-34,-74,16,4,88,-70,-88,-94,-24,4,-14,-56,56,-18,84,0,-48,-94,72,42,36,52,74,-84,-50,16,30}); param0.add(new int[]{0,0,1,1,1,1}); param0.add(new int[]{29,49,88,44,92,43,12,5,38,75,57,3,85,16,86,62,16,40,76,37,5,69,16,63,84,78,74,18,4,89,73,67,60}); param0.add(new int[]{-98,-80,-50,-44,-42,-36,-36,-28,-10,-8,-4,-2,2,10,18,18,26,32,36,56,80,86,88,90}); param0.add(new int[]{0,0,1,0,1,1,1,0,1,0,0,1,1,1,1,1}); param0.add(new int[]{13,15,62,65,87}); param0.add(new int[]{-50,58,78,28,4,18,-8,18,-88,-48,-26,-32,64,48,60,94,-92,48,-36,30,-80,-60,82,-62,32,-36,-76,-88,-60,22,-14,72,30}); param0.add(new int[]{0,0,0,0,1,1,1,1,1,1,1}); param0.add(new int[]{25,17,58,40,53,73,23,77,38}); List<Integer> param1 = new ArrayList<>(); param1.add(16); param1.add(15); param1.add(5); param1.add(25); param1.add(16); param1.add(13); param1.add(3); param1.add(31); param1.add(9); param1.add(8); List<Integer> param2 = new ArrayList<>(); param2.add(13); param2.add(28); param2.add(5); param2.add(18); param2.add(12); param2.add(14); param2.add(4); param2.add(17); param2.add(6); param2.add(6); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
890
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/FIND_DIFFERENCE_BETWEEN_SUMS_OF_TWO_DIAGONALS_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FIND_DIFFERENCE_BETWEEN_SUMS_OF_TWO_DIAGONALS_1{ public static int f_gold ( int arr [ ] [ ] , int n ) { int d1 = 0 , d2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { d1 += arr [ i ] [ i ] ; d2 += arr [ i ] [ n - i - 1 ] ; } return Math . abs ( d1 - d2 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ] [ ]> param0 = new ArrayList<>(); param0.add(new int[][]{new int[]{1,2,4,8,12,15,17,17,19,19,21,26,27,28,32,33,40,41,41,46,46,47,48,56,59,62,68,68,69,76,80,81,82,83,86,88,90,91,93,96,97},new int[]{3,7,8,9,10,13,16,18,20,22,22,24,26,27,31,33,33,34,37,43,45,46,46,46,47,49,50,51,55,57,67,75,75,83,87,87,90,90,92,93,97},new int[]{5,5,5,8,11,14,18,24,26,28,28,31,35,36,37,43,43,50,56,56,59,61,62,62,64,66,66,67,74,76,76,79,82,83,84,87,87,87,90,96,98},new int[]{4,13,13,20,21,22,22,29,30,31,35,38,38,39,41,42,43,43,51,56,56,63,65,66,74,79,80,82,84,84,86,87,87,89,91,92,92,94,94,96,99},new int[]{8,11,12,17,17,18,21,24,24,26,26,26,27,28,28,28,29,32,36,36,40,51,53,59,64,65,68,72,73,73,77,81,81,82,83,85,87,89,92,95,99},new int[]{1,3,6,7,7,8,9,9,12,13,13,14,15,17,20,20,21,27,36,36,40,44,51,51,55,57,62,68,68,70,81,82,87,89,90,93,94,97,97,98,99},new int[]{4,6,7,11,14,21,21,22,25,25,28,30,39,40,40,43,45,46,46,51,53,57,60,62,64,65,66,68,70,72,73,80,81,81,84,84,86,91,92,95,95},new int[]{1,1,3,5,5,9,11,11,11,13,16,17,20,28,31,31,36,37,38,38,41,42,44,47,49,53,54,58,60,67,68,70,72,72,76,80,81,82,87,88,99},new int[]{8,8,10,16,16,17,20,26,29,29,31,36,40,42,48,50,55,56,56,59,61,64,64,70,77,77,78,78,81,84,84,87,88,93,93,93,95,95,96,97,97},new int[]{2,2,5,7,9,10,11,14,15,15,16,16,22,23,26,26,31,32,33,36,42,49,51,53,56,58,61,75,76,77,77,80,80,82,82,83,84,85,90,90,94},new int[]{3,6,7,9,9,10,11,12,19,22,25,30,32,32,33,34,35,36,36,37,40,41,43,43,44,44,51,58,62,62,69,69,78,78,80,83,85,91,93,97,99},new int[]{1,4,5,7,7,7,15,16,17,18,21,21,26,31,36,39,39,47,49,53,56,59,60,63,63,64,64,66,69,70,77,79,80,80,82,84,86,87,89,98,98},new int[]{1,6,9,11,12,14,21,22,29,31,32,32,34,37,37,37,43,44,47,52,55,57,58,61,61,63,64,65,70,71,71,74,74,77,77,80,81,86,91,91,97},new int[]{1,3,4,10,10,19,20,20,21,21,23,27,27,33,35,36,36,41,41,42,49,51,51,51,54,56,59,61,61,66,67,77,81,82,82,82,85,87,93,94,95},new int[]{7,9,9,12,15,19,24,28,30,32,36,39,40,41,51,55,55,55,56,56,57,58,63,64,71,73,74,76,76,77,77,80,81,89,91,91,92,94,95,97,99},new int[]{2,2,6,11,13,15,16,17,18,21,24,30,30,33,34,35,36,40,41,44,46,47,51,52,53,53,55,56,60,62,68,73,77,78,79,83,85,91,94,96,96},new int[]{2,3,6,7,8,8,9,15,18,24,25,30,30,38,41,44,44,47,49,53,59,60,61,65,65,71,77,78,80,84,84,86,86,87,88,88,90,91,91,95,96},new int[]{1,10,11,16,16,16,25,26,28,31,31,32,33,34,34,36,37,38,46,50,52,55,56,58,61,62,67,71,72,75,77,83,84,84,85,87,88,95,96,97,99},new int[]{1,3,4,5,7,8,9,12,13,13,18,20,24,27,33,35,39,44,49,56,56,61,61,67,70,70,70,70,71,71,71,76,78,78,84,88,89,91,94,95,99},new int[]{1,1,4,5,6,7,11,16,20,22,23,27,35,36,39,39,44,46,46,49,51,51,52,55,56,56,58,65,70,77,78,82,82,82,84,88,89,96,98,98,99},new int[]{3,3,5,5,9,12,14,17,22,31,33,34,36,36,38,38,39,45,46,47,48,48,50,55,55,56,59,63,64,67,68,70,72,74,80,80,82,84,87,93,95},new int[]{4,8,16,17,17,18,18,23,24,27,28,32,36,39,40,42,45,48,48,52,52,53,55,56,57,57,66,67,68,70,71,74,74,74,75,77,80,81,84,92,92},new int[]{4,4,5,8,18,18,19,20,21,21,25,25,25,28,31,38,42,48,54,56,58,59,61,61,63,66,67,67,68,71,74,75,77,77,78,84,86,88,93,94,99},new int[]{3,5,5,8,10,12,13,20,21,22,25,33,38,39,41,44,47,47,48,49,50,52,59,62,64,65,67,68,69,70,70,75,78,79,80,81,83,84,87,90,99},new int[]{3,7,9,9,11,13,13,13,14,15,17,24,26,29,29,33,34,35,37,40,41,45,50,50,53,56,57,59,62,62,63,65,72,72,76,78,79,86,87,94,99},new int[]{2,2,6,7,12,13,13,13,15,16,17,18,22,23,24,24,27,28,34,40,40,42,43,48,49,52,53,54,55,57,60,66,71,71,71,73,74,93,96,96,97},new int[]{1,1,2,2,3,3,4,4,6,18,20,25,26,26,27,30,32,38,39,41,48,50,53,57,61,63,64,65,66,67,67,68,71,73,81,84,91,91,91,94,99},new int[]{2,3,3,4,5,7,10,11,12,13,14,14,14,15,16,17,17,18,26,27,40,41,42,43,47,47,48,48,55,63,64,75,78,83,83,87,88,89,92,98,98},new int[]{1,2,6,6,8,13,13,22,23,25,25,26,28,28,34,37,40,44,46,50,54,58,62,62,65,67,72,79,80,81,84,85,85,87,88,89,92,95,97,97,97},new int[]{3,4,6,6,11,12,12,15,19,20,22,26,34,37,41,44,52,56,56,60,69,69,70,71,72,72,73,79,79,83,85,90,90,91,93,94,95,96,97,98,99},new int[]{2,4,5,6,8,9,15,17,21,21,24,24,30,32,34,34,35,37,38,39,39,41,43,43,43,47,51,51,54,55,61,63,64,71,74,78,78,80,84,85,96},new int[]{2,2,7,8,9,9,9,10,14,14,14,15,20,21,26,26,27,28,29,36,37,39,40,40,41,45,48,49,61,62,66,67,69,70,71,75,75,76,80,90,97},new int[]{1,3,11,11,11,12,15,17,19,20,25,27,28,40,51,52,53,53,57,58,58,62,68,72,72,73,76,76,81,83,84,86,86,87,87,89,92,94,94,95,95},new int[]{7,7,8,13,16,16,23,23,24,24,30,33,37,38,39,42,48,52,53,54,56,56,64,64,65,66,66,68,70,71,72,72,78,81,83,85,86,87,90,90,92},new int[]{3,4,4,5,13,17,17,21,28,33,34,34,34,35,37,38,45,50,55,60,63,64,65,67,67,68,69,70,71,79,79,80,80,84,85,93,94,94,96,97,98},new int[]{10,13,15,17,19,20,21,21,22,29,29,30,35,39,39,44,44,47,49,49,50,50,52,53,55,57,57,59,60,61,64,67,69,72,75,78,80,87,88,89,98},new int[]{8,9,9,13,28,29,32,32,33,34,38,40,40,42,45,51,51,54,55,57,57,59,63,69,69,69,70,73,76,77,78,78,85,85,87,88,91,95,96,97,99},new int[]{2,5,7,8,14,17,19,20,21,24,25,28,29,32,33,37,44,45,52,54,58,58,62,62,63,63,65,65,71,72,74,81,86,86,91,91,91,93,93,96,98},new int[]{3,8,12,13,16,21,22,23,33,40,42,42,46,48,50,50,54,57,64,64,68,68,68,73,74,74,77,77,78,79,82,85,86,88,92,92,94,97,97,98,98},new int[]{5,6,7,8,9,12,13,19,19,27,29,34,36,38,39,41,43,44,47,49,50,53,57,57,59,61,62,65,65,68,75,77,80,81,82,84,85,88,89,92,94},new int[]{3,3,4,8,12,20,25,26,30,32,33,41,41,43,45,46,46,47,50,54,54,57,57,62,63,65,67,68,69,70,72,73,75,77,83,85,86,93,93,97,97}}); param0.add(new int[][]{new int[]{52,-18,-36,-28,-14,92,80,-48,28,-18,-46,76,-96,4,-50,-80,-40,34,36,-66,-66,48,-8,-36,10,26,-46,80,-22,-90,66,82,22,30,-32,96,30,-4,70,-92,90,-26,18,-48,72,-88},new int[]{14,-90,60,50,54,78,46,26,-46,94,46,42,-48,96,18,-84,42,16,-58,-96,-80,-66,-50,-32,-48,-8,34,42,40,34,12,-34,-94,18,60,30,-48,8,30,-24,10,-26,-12,-58,62,96},new int[]{-22,-24,-6,16,80,86,-30,-66,94,10,-42,0,-92,-28,82,-16,-94,-40,72,-76,66,-70,94,68,-20,-30,48,80,-96,-56,-70,-82,-22,-78,12,-20,-2,80,-96,-10,12,-10,32,66,26,22},new int[]{18,72,76,82,-20,-64,16,70,72,32,-34,-98,-22,24,-68,0,-14,-60,-66,16,-20,-40,-64,42,14,-70,-30,48,40,12,-82,-30,-36,-36,60,-48,78,-66,46,-52,68,-60,88,-10,-42,64},new int[]{58,-48,0,78,-74,84,-14,54,-68,48,84,-2,-74,-20,32,40,4,8,38,-24,58,56,76,-88,-18,90,-94,-64,-76,-8,-88,-20,-66,-4,-20,-70,34,66,12,8,-38,8,92,-98,-32,-44},new int[]{96,-20,6,-36,54,-82,-74,-98,-58,-32,-42,26,34,72,-98,-2,40,-90,16,-66,70,-10,36,-84,8,-22,-18,24,-92,12,34,30,-74,54,46,26,-52,-48,-86,78,16,-94,-12,-24,64,-42},new int[]{-74,-4,-70,-32,24,72,8,66,52,-34,-84,-70,82,-96,72,90,0,18,26,48,98,-92,-26,0,-78,-52,94,-12,-60,-54,16,98,96,-68,26,84,24,-28,42,-32,58,4,-78,46,-96,-2},new int[]{-74,-46,62,-52,-30,36,-52,64,66,4,18,76,8,82,90,72,-64,24,86,-46,72,58,-10,46,-8,-20,-18,-24,-4,52,96,44,-18,-84,-64,-56,76,54,-84,-12,-32,52,62,10,52,68},new int[]{-44,20,44,-20,94,76,94,-40,40,-74,-56,78,20,38,-56,-2,-34,-6,-24,-62,72,-36,42,32,56,24,38,6,8,-78,-64,-38,58,-98,16,38,92,-4,-38,-22,-62,96,34,64,-32,-98},new int[]{34,-96,-98,10,40,2,26,14,18,-12,-16,84,-74,0,-98,38,-48,18,22,-32,-52,-2,28,-50,64,10,80,6,20,0,66,80,96,14,20,-56,18,80,-16,74,-74,26,-70,58,74,32},new int[]{72,-52,2,-90,-56,98,-50,10,-60,84,24,-88,-98,-48,54,44,-84,10,-18,68,40,40,-46,-18,60,-58,-50,26,74,-24,-64,-70,44,-40,18,-88,-60,82,-60,26,-66,-68,46,60,92,84},new int[]{96,26,-46,94,-48,24,50,-10,24,-50,86,-76,-78,98,-28,-60,-62,-32,-74,-18,96,-44,-72,-56,12,-28,70,-16,48,-26,86,-24,44,56,82,-34,30,36,-34,92,-80,-50,-54,-20,-52,48},new int[]{74,-70,64,-98,-40,-14,-82,56,82,-16,-76,-56,22,64,-84,-48,44,70,30,56,-84,-80,-44,-30,-38,96,58,-18,56,-42,-54,20,-60,82,-94,-8,40,-16,-94,-70,30,-82,74,4,-36,-42},new int[]{24,-10,16,-4,50,-8,58,-24,-90,-90,52,16,96,74,36,-92,-28,-84,6,70,54,60,26,42,34,22,4,-48,-96,20,88,34,78,12,-62,-6,80,30,86,74,68,-18,42,-50,-80,32},new int[]{62,90,6,66,-26,-98,-80,46,-52,-22,10,-60,62,92,16,78,52,22,70,28,98,28,-94,70,-68,-84,32,-86,38,-6,-94,10,-4,-84,74,42,-10,-82,12,-6,-8,14,-30,72,18,12},new int[]{78,-18,56,90,-74,82,20,-90,26,40,-72,-46,-76,14,-58,58,30,-58,-62,-62,70,-4,-62,-64,-88,96,80,74,30,12,44,78,76,76,-48,-38,-12,22,-90,0,-26,28,88,80,38,66},new int[]{-58,10,22,-26,46,-48,-76,92,26,52,24,-30,56,-68,2,72,-44,34,-72,-24,34,64,72,-10,16,-26,0,60,18,-44,-18,-36,-94,38,22,80,-78,-78,-48,98,64,30,72,14,-22,22},new int[]{-30,82,38,-2,-60,-28,-4,-36,22,-64,48,-14,-26,-10,62,-10,-68,54,-6,-26,-32,-66,-84,-12,56,42,-64,14,86,76,-24,-36,38,98,56,-14,-52,44,-44,-88,-26,-10,14,-2,-12,-14},new int[]{-58,50,18,30,80,78,22,22,12,90,0,-20,50,20,82,-70,-26,-28,-90,58,-24,18,54,62,48,20,96,-10,72,70,-98,64,-56,42,76,58,-84,-62,40,-78,-22,-98,42,54,-34,10},new int[]{42,64,-40,-90,-8,-54,-42,80,-28,-18,8,28,-10,36,12,86,28,-16,66,10,6,86,60,-92,-92,-16,-84,-84,-50,76,-2,68,80,-62,54,-90,-96,48,2,-42,70,68,-24,92,14,-46},new int[]{-96,20,10,64,-66,84,-52,-74,-96,-88,-96,6,-32,-10,-40,-2,4,22,24,-60,-54,-62,-58,-30,-80,-94,-50,-72,74,50,84,-6,12,-28,46,64,-36,-52,-24,56,56,-16,80,-74,-94,50},new int[]{-66,62,46,-38,-50,78,2,96,-50,-2,-64,-86,-26,-4,-92,78,-16,64,-74,6,34,-54,40,62,-8,30,46,-88,68,52,46,84,-90,6,86,58,-70,86,54,80,-6,30,44,-6,2,42},new int[]{-44,-76,40,-30,-38,14,-24,-10,-28,-54,90,-64,66,88,62,94,-56,72,4,46,60,70,-92,-48,-62,-94,96,-40,74,-40,-28,-44,64,-54,14,-42,-74,-24,18,46,-48,60,16,-78,-74,-82},new int[]{-8,-94,-56,90,22,-36,-66,28,48,-28,92,38,-8,14,34,46,62,12,2,-38,-44,16,-66,-56,-74,98,92,-42,-42,-32,82,-42,-12,-76,18,54,16,0,92,12,96,86,94,-60,-62,-50},new int[]{-14,-88,-20,-60,36,-90,-24,90,-24,70,10,22,-10,-88,-90,-72,-60,-62,-58,98,24,-52,-70,82,84,24,94,-16,-70,-16,84,-34,72,-42,66,36,-38,-20,-22,12,-30,48,-2,-58,-26,56},new int[]{52,40,28,-48,-80,-58,50,34,-94,-24,-94,-24,-44,4,-90,84,84,-66,76,36,-62,-22,8,32,24,-86,-52,16,52,24,66,-16,38,54,56,92,84,-46,88,22,92,-58,-14,12,82,92},new int[]{-98,38,16,44,-10,32,68,-90,94,-16,-90,38,96,-82,68,-72,-80,-54,-68,0,58,-12,56,-46,68,4,-52,4,2,-96,-78,80,50,4,20,80,62,-40,-82,-22,90,44,88,68,-72,66},new int[]{-28,54,-12,96,94,40,10,-18,28,46,8,48,74,58,94,10,-30,-50,-2,-80,-22,-70,30,-16,26,78,-84,-50,-2,-66,-18,98,-94,-6,-2,-44,-48,2,78,94,-90,32,-90,-56,-90,0},new int[]{-36,-40,-28,94,-96,-16,8,12,94,52,52,-56,-66,86,-10,-68,38,-16,-72,94,-68,26,58,-74,22,-84,-50,-8,32,66,20,94,-44,-74,-72,-96,38,64,4,-72,-66,-54,44,92,-52,-62},new int[]{-98,-58,-82,-74,38,-6,-86,-98,-60,62,32,-64,12,80,-58,90,-76,-6,-98,78,-12,-20,68,-62,72,-72,90,-24,-84,-84,54,66,46,50,12,98,-4,-90,-46,12,28,76,-54,-24,-12,-26},new int[]{-48,-6,-18,80,-30,44,74,14,-54,64,-68,-2,14,-4,-68,-6,-78,-4,-30,-18,-32,-48,56,-48,-6,-46,34,-96,-44,-84,-34,-12,-20,72,-24,76,46,66,-24,-20,-8,92,92,54,64,2},new int[]{-30,26,-76,-38,-72,36,-32,-22,8,40,72,12,-58,6,-94,-70,-44,56,-88,76,50,-8,76,-74,2,54,-48,56,56,60,72,-30,-42,-54,-28,-80,-64,82,-32,-42,2,-32,-48,64,-66,26},new int[]{66,72,-98,-62,-18,-42,-50,-20,62,-96,-24,-90,-58,82,-76,0,-12,-66,-48,26,42,12,-8,46,-56,-16,-2,-94,16,90,-34,48,34,-44,-66,-70,44,66,6,74,50,96,32,64,82,-10},new int[]{84,48,94,32,44,26,64,24,28,88,42,-54,82,34,16,-14,-46,-94,-76,88,-38,42,-60,-8,4,-70,24,-60,-82,-96,40,20,98,-2,32,-24,54,52,-44,78,-58,-16,-32,56,-20,52},new int[]{34,-90,-10,-10,-8,-28,-34,46,-86,20,-90,-78,94,72,92,-4,-30,84,-32,84,16,94,92,-40,46,58,38,-8,14,58,58,38,0,-30,-30,-40,90,12,26,56,-62,40,8,16,70,4},new int[]{-32,88,70,26,30,62,-18,-50,-78,-18,40,-98,-84,-74,-68,22,8,6,-88,78,14,50,-34,-12,-58,78,32,-6,52,70,-98,32,6,-26,98,-82,-8,-88,-6,-6,84,-28,-68,78,68,12},new int[]{-2,4,82,94,72,-90,2,-8,16,76,-34,72,-26,-86,60,92,-32,82,-88,-42,14,50,94,-98,-50,-78,-86,68,-28,16,-18,-20,-6,-64,-82,68,-86,94,46,-2,78,-24,88,-82,-80,90},new int[]{40,-64,60,-14,98,98,84,34,-36,14,92,50,-30,-38,-28,68,-6,18,-36,-76,-20,-4,62,-6,-58,-50,48,-64,34,-96,76,68,66,86,-2,-90,80,-18,-68,-8,-64,-32,-14,-48,48,-2},new int[]{58,26,56,-88,-92,-10,-14,42,-96,40,24,32,16,38,34,98,54,-36,88,86,-74,40,-68,-26,-14,-74,-82,12,-48,-22,-36,98,-38,-30,-98,-34,-8,84,-34,-98,0,-76,24,-6,94,-64},new int[]{76,48,-14,70,-52,-34,4,-2,-8,84,2,14,16,-40,-90,-66,-22,40,-46,50,-66,-52,54,-68,48,46,-76,98,34,-94,26,62,-38,2,52,0,58,64,-96,52,4,58,70,-24,-96,50},new int[]{30,72,-88,-98,42,76,-52,-88,-32,-2,2,-84,-86,-34,-36,34,-38,-4,-60,-62,54,-52,92,86,6,98,76,38,-56,90,98,-10,66,88,-90,-54,-42,-22,-58,4,92,76,36,76,-68,4},new int[]{8,44,-2,-52,-76,34,-14,-42,-54,30,46,64,14,44,10,-14,-60,-18,16,-80,-6,-10,52,52,90,-88,98,-96,-36,18,-92,10,-52,74,-94,-46,36,-38,-12,66,34,-30,38,26,6,38},new int[]{-84,-22,4,-52,-12,40,-14,44,70,80,72,-16,-38,-44,16,-16,82,-90,-14,24,-98,92,52,-50,40,96,76,-16,-28,-28,28,10,0,-22,16,-62,-34,28,94,-72,20,-30,-20,40,-24,-76},new int[]{-62,98,-82,34,12,14,-64,-34,-70,-24,-34,-92,54,90,-66,-48,-52,-80,-72,-80,-46,-60,76,-2,58,-96,52,42,88,96,-58,-28,-4,48,66,-94,4,90,64,-52,62,80,-98,76,90,-64},new int[]{-88,-40,32,8,94,-12,98,-52,4,-14,52,-72,-4,-84,18,-96,74,80,-12,18,60,32,-68,-94,90,24,34,2,-70,90,52,28,92,58,-20,-52,26,-30,4,96,54,64,64,52,-24,40},new int[]{26,-84,-20,80,-82,40,68,-6,-44,48,48,-36,48,12,-92,-14,66,98,24,42,62,76,50,-62,-30,36,88,-30,-60,94,-44,70,36,-26,-44,-48,22,6,16,26,8,-4,54,-50,92,44}}); param0.add(new int[][]{new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}); param0.add(new int[][]{new int[]{81,85,4,98,56,46,38,97,79,82,85,7,80,73,25,43,23,2,31,9,16,34,18,10,89},new int[]{22,46,32,7,21,64,50,94,48,44,44,74,34,70,14,16,50,46,84,55,14,71,46,92,38},new int[]{73,57,12,47,18,80,68,28,28,21,10,76,10,23,30,16,34,78,38,86,73,50,63,68,23},new int[]{32,49,77,70,75,40,3,18,23,69,51,36,73,64,54,8,44,55,63,97,37,83,97,5,92},new int[]{79,81,22,50,43,76,4,17,78,58,48,17,84,11,65,37,33,75,51,91,26,80,79,14,61},new int[]{73,21,41,90,65,33,41,63,58,78,71,8,41,2,56,88,78,56,70,36,94,16,40,40,24},new int[]{93,81,96,8,40,57,17,29,95,31,42,70,73,58,63,66,44,8,76,4,30,9,73,30,57},new int[]{60,65,25,64,74,5,58,33,50,64,59,18,78,18,80,81,46,18,71,13,13,27,14,4,96},new int[]{97,55,80,68,84,54,56,13,59,47,59,60,60,33,90,26,26,31,2,92,59,96,69,90,78},new int[]{17,57,22,75,4,25,11,46,48,81,10,44,46,90,54,47,28,10,89,12,44,37,36,59,37},new int[]{41,5,42,76,18,86,15,31,20,18,59,24,11,3,84,95,36,72,68,77,93,26,23,46,96},new int[]{57,2,76,61,78,77,68,57,74,23,80,89,58,76,89,1,21,37,38,89,10,23,65,81,24},new int[]{53,40,5,49,23,54,48,71,45,56,70,95,93,28,74,97,71,43,26,77,59,69,57,24,61},new int[]{8,94,80,64,93,48,15,13,9,28,22,89,46,32,39,88,25,94,61,94,41,96,18,33,68},new int[]{55,12,55,98,37,89,10,59,37,2,9,61,7,60,56,43,60,72,87,13,3,53,24,69,51},new int[]{81,44,2,90,81,75,56,15,23,16,51,80,72,77,88,54,6,66,18,15,23,50,95,3,10},new int[]{20,24,35,36,38,44,43,56,39,90,78,13,88,19,5,89,11,67,25,70,41,21,47,44,46},new int[]{1,58,92,87,51,24,53,71,79,25,62,74,8,69,32,73,68,26,12,84,7,4,21,11,64},new int[]{38,69,28,6,5,64,25,11,77,56,49,62,61,28,2,93,60,63,77,83,37,79,24,61,71},new int[]{59,21,91,87,47,14,49,70,8,67,25,13,73,24,28,46,94,75,45,18,64,16,45,97,72},new int[]{84,26,36,48,75,67,66,58,81,83,71,88,31,60,67,30,22,39,49,46,75,53,25,54,95},new int[]{37,14,8,10,99,13,27,16,17,29,28,14,11,55,40,68,7,58,27,6,33,27,28,36,6},new int[]{28,3,96,18,96,58,15,46,63,70,38,76,89,71,16,68,69,3,2,52,1,78,26,24,28},new int[]{98,37,55,48,7,9,40,97,73,46,38,9,56,14,73,33,38,3,48,81,66,91,14,55,41},new int[]{42,34,27,88,76,14,69,45,7,93,56,23,36,24,90,93,91,3,49,54,5,80,31,65,66}}); param0.add(new int[][]{new int[]{-68,-68,-50,-30,0,36,44,46,56,80},new int[]{-88,-84,-80,-54,-30,-16,44,80,80,82},new int[]{-78,-66,-46,-44,2,42,52,56,62,92},new int[]{-96,-80,-56,-32,-14,0,2,20,30,92},new int[]{-80,-78,-46,-16,-12,-6,26,66,72,98},new int[]{-62,-52,-52,-22,-12,2,10,42,90,96},new int[]{-88,-74,-74,-64,-54,-52,2,34,78,82},new int[]{-78,-26,8,14,42,42,76,78,86,96},new int[]{-78,-70,-68,-22,-12,20,58,60,84,98},new int[]{-98,-56,-48,-20,-20,10,48,60,60,86}}); param0.add(new int[][]{new int[]{0,0,1,1,0,1,1},new int[]{0,1,0,1,1,0,0},new int[]{1,1,1,1,0,1,0},new int[]{0,0,1,0,0,0,1},new int[]{1,0,1,0,0,0,0},new int[]{1,1,1,1,1,1,0},new int[]{1,0,0,1,1,0,1}}); param0.add(new int[][]{new int[]{4,5,8,14,14,15,16,18,18,19,21,23,30,31,33,36,38,39,40,45,47,50,55,57,59,59,62,63,63,68,69,70,70,73,73,77,80,81,83,85,88,90,91,97,97},new int[]{1,2,2,3,7,8,11,12,15,18,27,29,31,32,35,39,43,46,47,49,50,52,54,56,56,56,57,57,60,61,62,68,68,71,77,78,79,81,81,87,87,88,89,92,93},new int[]{1,7,11,15,16,18,27,27,29,29,29,31,34,39,43,44,47,52,52,55,55,56,62,68,70,72,73,73,75,76,77,78,81,84,84,87,87,88,89,90,91,91,94,96,98},new int[]{3,3,4,12,16,17,17,19,28,28,29,29,30,30,31,31,33,33,36,44,44,44,45,45,53,54,54,54,57,63,64,66,67,69,69,75,78,79,82,87,91,92,95,95,99},new int[]{1,1,2,5,6,9,10,11,16,17,18,20,24,25,25,26,26,26,28,29,30,35,36,36,46,47,53,57,58,58,61,61,62,71,73,75,80,81,87,87,89,90,91,96,99},new int[]{4,8,14,17,17,21,24,27,29,31,34,36,37,37,40,41,42,44,44,45,46,47,50,54,63,64,65,68,73,73,73,76,77,79,80,82,82,83,84,88,90,93,93,95,95},new int[]{1,5,9,10,10,12,13,15,16,17,17,24,25,26,29,32,34,36,37,43,44,49,53,54,54,56,57,65,70,72,72,76,77,78,78,80,80,80,83,86,90,90,94,96,97},new int[]{5,9,10,10,10,11,11,11,15,18,18,19,24,26,31,31,33,36,41,43,43,45,50,51,54,54,54,62,64,64,66,71,71,72,73,73,79,82,83,84,86,88,93,96,97},new int[]{1,3,7,9,9,10,13,15,16,22,22,24,24,26,34,36,38,38,39,40,40,41,43,45,49,53,58,60,64,67,69,70,75,77,80,81,84,84,85,85,86,89,93,97,99},new int[]{3,4,5,6,7,11,11,11,13,13,15,16,19,20,21,25,25,26,27,29,38,39,44,44,50,51,51,54,54,54,61,62,65,67,68,71,71,73,73,75,77,89,89,93,95},new int[]{3,5,8,13,14,15,20,23,25,25,27,28,28,29,37,38,41,42,44,45,47,48,50,54,61,64,64,71,72,74,76,76,79,79,79,80,81,81,82,83,84,95,95,95,96},new int[]{4,5,7,8,9,10,13,14,17,19,20,27,28,29,34,36,37,38,38,42,42,43,44,45,45,47,52,52,53,59,60,62,67,69,73,80,82,83,83,84,88,92,95,98,99},new int[]{1,6,8,10,14,14,15,17,20,20,20,20,22,34,36,42,43,47,47,48,52,53,55,56,57,59,61,65,67,69,73,74,77,78,81,81,82,84,84,84,91,93,94,98,98},new int[]{2,5,8,8,10,10,11,15,16,16,18,18,18,20,21,23,37,40,41,41,42,44,46,48,50,50,52,53,59,68,68,70,73,73,74,77,77,83,86,88,92,92,94,97,99},new int[]{3,4,6,6,10,11,12,13,13,15,15,17,22,23,25,28,30,37,42,43,44,46,46,52,52,53,57,57,58,58,58,59,60,60,60,63,63,67,69,69,73,74,74,75,87},new int[]{3,4,4,7,8,11,12,14,20,22,23,24,24,31,32,39,41,42,45,45,47,47,51,57,57,61,62,62,64,65,66,67,69,72,72,72,80,81,85,88,91,95,96,99,99},new int[]{3,5,6,8,8,8,11,12,15,17,19,19,19,22,22,23,26,27,30,34,35,36,38,46,51,51,55,59,62,62,65,66,71,73,75,77,78,86,89,90,94,95,96,96,96},new int[]{3,8,9,11,13,18,18,20,21,23,23,25,27,29,32,33,36,36,44,47,49,53,58,63,64,64,66,68,68,70,71,72,72,73,74,75,75,81,82,84,85,86,88,88,96},new int[]{3,5,5,7,16,16,18,18,19,20,28,31,32,35,37,38,39,39,48,49,54,60,61,67,68,70,75,75,77,78,81,82,83,83,86,87,88,89,91,91,93,97,97,97,97},new int[]{2,2,3,5,11,16,18,19,20,22,22,24,24,26,26,29,33,34,35,37,41,41,44,44,45,56,56,57,57,59,64,64,70,77,80,80,83,88,89,93,94,95,96,96,98},new int[]{1,3,5,6,12,16,18,21,22,23,26,29,33,37,39,40,43,46,47,53,57,57,60,61,63,63,64,65,66,67,71,71,72,72,77,81,84,85,87,93,94,95,96,97,99},new int[]{3,4,6,7,10,11,16,18,19,21,22,22,32,33,34,34,36,39,40,41,42,44,47,49,49,50,54,56,63,66,71,72,73,74,74,78,79,82,83,86,89,91,92,92,93},new int[]{3,4,4,5,8,15,16,19,19,20,31,32,34,34,39,40,42,45,45,47,48,48,49,52,55,60,62,62,64,68,70,73,73,74,75,77,77,81,81,83,86,90,91,94,94},new int[]{4,5,12,15,16,16,17,20,24,24,25,25,25,28,30,30,33,37,39,41,42,48,50,51,51,54,57,62,63,65,66,68,69,72,72,72,72,74,75,75,77,86,88,92,92},new int[]{2,3,7,7,8,11,11,12,12,14,17,17,17,21,21,23,27,27,30,31,33,36,45,46,48,48,49,51,53,55,58,59,61,65,68,69,71,84,84,84,90,94,97,98,99},new int[]{1,4,7,7,10,10,12,14,15,15,16,20,21,28,28,28,29,29,35,40,43,45,48,49,51,52,56,56,66,67,69,69,70,71,73,74,78,79,82,86,89,92,96,98,98},new int[]{4,5,6,9,9,9,13,15,17,23,23,28,33,34,34,35,35,40,42,43,46,50,52,55,57,60,64,67,72,72,75,75,77,77,79,79,81,81,82,86,86,90,91,95,97},new int[]{1,4,4,5,5,6,7,9,9,9,10,11,15,15,21,22,26,26,29,31,31,34,38,40,40,42,43,44,45,49,50,52,54,55,57,62,66,68,69,70,72,82,85,86,90},new int[]{3,4,6,8,8,9,10,11,15,22,22,26,26,27,29,31,37,38,41,41,43,43,47,47,48,50,53,54,55,56,60,63,63,67,68,70,71,75,76,84,87,87,91,95,98},new int[]{2,7,8,16,17,17,23,26,26,28,31,35,36,38,39,43,48,49,53,58,59,60,68,68,70,70,71,73,73,74,76,77,77,79,79,82,82,82,82,87,88,89,90,90,98},new int[]{3,3,10,12,16,17,20,21,22,24,25,27,28,31,32,33,34,35,35,38,39,40,42,45,48,51,52,54,56,61,63,63,66,67,68,69,74,75,76,78,79,87,91,91,92},new int[]{4,6,8,8,14,17,23,23,25,25,27,27,30,30,34,35,38,40,42,48,49,51,52,53,57,57,58,58,59,67,70,71,75,76,77,78,82,84,85,87,94,94,96,97,98},new int[]{2,4,4,4,4,6,8,10,13,14,15,18,20,23,24,26,27,29,33,35,39,40,41,42,46,48,49,52,56,62,64,68,71,76,77,77,78,79,84,92,94,95,95,97,98},new int[]{1,7,8,9,12,12,14,14,16,19,23,25,27,27,27,28,29,29,33,33,41,44,45,46,51,51,52,56,57,58,59,60,64,68,69,70,73,80,82,82,86,87,90,98,98},new int[]{2,5,18,19,20,23,26,27,33,36,45,46,51,52,53,56,58,60,63,68,71,71,72,73,75,76,76,80,80,81,81,84,87,89,91,92,92,92,93,93,94,95,98,98,99},new int[]{1,1,5,5,5,6,10,10,15,16,17,22,29,31,42,48,49,49,49,53,54,54,55,56,56,59,60,62,62,64,72,72,73,75,77,81,82,82,86,89,90,91,97,97,99},new int[]{3,5,8,9,10,13,14,14,16,26,26,29,30,32,36,37,42,42,44,45,45,47,47,49,52,53,54,57,58,62,63,64,65,65,67,69,69,69,70,75,76,76,80,86,86},new int[]{1,2,4,8,8,11,12,16,21,28,30,30,30,32,36,37,38,39,40,43,46,49,49,50,55,57,60,60,61,64,65,66,73,78,79,80,80,83,86,86,87,89,90,93,98},new int[]{8,8,11,14,16,16,17,23,24,29,31,38,38,39,40,40,48,51,60,60,62,65,65,67,67,68,70,71,73,73,74,75,78,79,80,81,83,83,86,87,91,92,93,93,98},new int[]{1,3,7,10,10,11,13,14,18,18,20,21,22,25,27,27,28,30,37,38,44,48,50,52,55,57,60,63,64,65,67,71,74,75,77,79,79,85,86,90,93,94,96,98,99},new int[]{1,4,7,11,13,15,15,16,19,21,25,27,38,43,43,48,48,49,49,52,53,54,56,57,61,61,64,64,65,66,68,68,69,70,71,71,73,76,81,83,91,94,95,96,99},new int[]{1,2,4,11,12,12,15,17,20,22,28,30,31,31,31,38,38,38,41,48,48,50,51,51,51,57,59,62,68,73,75,78,81,83,86,90,90,90,92,92,94,94,96,97,98},new int[]{3,7,11,11,13,13,13,20,20,23,24,25,30,31,31,31,34,34,36,39,42,42,47,56,57,60,65,65,66,72,72,73,73,75,75,78,79,83,87,87,93,93,95,96,99},new int[]{1,2,3,4,5,6,10,11,12,14,18,20,22,24,24,26,26,31,34,35,36,38,45,45,45,45,46,47,48,52,55,57,60,63,66,76,81,82,86,86,89,90,93,95,96},new int[]{2,2,5,8,13,16,22,23,27,28,30,31,36,39,40,45,46,49,51,54,57,57,57,58,59,60,61,63,67,70,70,72,74,75,75,81,82,85,86,88,91,92,92,93,99}}); param0.add(new int[][]{new int[]{-90,64,-52,-42,98,50,-60,-30,-34,-42,-58,-10,68,24,76,-32,14,-64,10,30,-8,74,-40,4,-34,48,8,74,54,-8,-86,34,-32,-10,-94,0,16,-6,-40,-94,-84},new int[]{68,62,98,88,98,-60,-84,0,32,-28,4,-6,84,-32,-40,-48,50,-88,2,42,-56,4,-46,-66,38,26,-80,82,74,-70,-4,-12,74,-32,-12,44,-94,-72,78,-62,16},new int[]{-76,-32,58,48,-38,-38,46,-74,12,-88,82,0,8,44,22,-68,34,48,74,4,48,-82,-96,40,-78,-80,26,22,36,-22,-36,88,10,14,-98,22,4,72,-72,10,56},new int[]{-26,-32,-86,86,22,-50,56,30,-30,-44,10,58,60,-82,8,50,-10,8,80,68,34,-14,-96,24,-8,-24,52,70,80,-90,-22,-62,-4,20,-30,-4,-38,90,18,58,36},new int[]{98,-2,62,-16,-48,78,14,24,90,12,-98,-40,-16,0,10,96,-90,56,8,10,-56,90,-46,-84,86,66,-16,84,-92,26,-84,-94,-22,-94,16,-68,-18,24,-50,-80,40},new int[]{-52,16,-58,10,-76,-90,-6,98,22,14,66,-16,-14,72,34,-90,-92,-34,42,-34,66,18,18,38,28,-30,-10,-50,46,50,-98,30,-80,-20,8,-82,-4,-10,-82,22,20},new int[]{68,14,62,-22,10,-78,-48,84,-96,96,-54,6,92,38,52,16,48,80,-28,46,64,20,80,-46,-88,-98,-46,-14,-28,40,78,96,-26,10,62,-82,-22,-76,82,-60,-72},new int[]{36,-30,-78,80,10,54,-60,-84,8,-54,22,96,36,-38,-10,56,-86,40,-62,-48,-18,78,-40,-86,36,46,74,66,-10,32,-98,-18,-82,-6,-34,88,4,-2,38,96,-90},new int[]{44,-54,-40,-4,68,-74,-12,22,16,32,-66,-92,-70,40,-34,58,68,-86,34,-40,-72,30,-52,56,-88,58,84,28,-88,64,36,26,52,88,-28,34,-28,-42,-88,46,-26},new int[]{58,56,24,22,-50,-26,44,-42,-80,-44,-96,58,-50,-40,-38,-32,34,84,0,-62,16,18,-10,94,8,50,-78,20,8,-16,-94,78,30,86,-4,-54,0,-44,56,46,30},new int[]{-44,2,14,56,-2,20,-14,20,24,-90,40,-90,-6,90,-22,-64,-64,-8,-58,62,-48,-84,-44,-78,80,68,-74,6,-42,52,14,40,2,-44,24,-76,-92,82,6,6,94},new int[]{80,-84,-8,90,-72,88,-58,98,30,-28,-84,-98,14,-90,2,50,26,-32,-16,50,-28,50,18,0,-42,56,58,68,6,-26,-78,24,70,-98,52,46,-52,92,52,38,28},new int[]{50,56,-92,-68,-2,76,82,-22,-86,-70,-4,84,-30,-68,4,58,-40,-68,-46,-92,68,-56,14,-12,-98,-36,76,54,14,12,18,-14,12,-28,14,2,2,-74,90,-34,-34},new int[]{-52,90,-52,26,-66,36,38,52,-38,-62,72,78,58,-50,-28,0,-30,6,-8,82,-30,42,84,28,40,74,58,12,62,-28,-66,68,34,72,-22,70,8,38,14,38,88},new int[]{66,-2,0,-74,-20,94,90,-30,8,-36,-54,-36,26,-96,6,-8,92,-6,-98,86,48,50,48,-92,88,-68,-6,-14,80,-38,36,74,-4,-34,86,-80,-82,42,-82,-54,-82},new int[]{54,82,-16,-4,-40,36,-30,-6,-2,62,-88,-6,22,44,-80,80,88,-2,28,-38,6,98,88,-34,60,-18,-52,-74,-28,-48,-18,-28,-18,-4,12,78,-8,20,-64,-98,-94},new int[]{68,-18,-98,42,-78,56,-26,-8,-56,74,2,-12,52,-62,26,-50,-34,32,-26,-80,20,22,30,-20,66,12,22,56,-38,-4,-46,74,-30,-8,-70,-90,80,8,-56,10,-66},new int[]{-32,-26,78,18,-84,82,-36,38,18,84,30,-10,30,-74,44,82,22,98,-30,-68,-42,-72,-24,-54,82,-90,-6,40,-94,86,84,-28,54,96,4,-48,42,68,-60,90,12},new int[]{82,94,-50,62,-94,76,-62,94,30,26,-46,-16,60,-12,-80,12,-26,-60,-32,74,10,8,84,2,-48,66,50,60,-28,84,30,-76,82,-70,52,82,-6,-92,50,-2,-64},new int[]{82,2,52,-86,-84,94,96,96,-96,-38,-64,12,74,-48,-38,48,62,-24,-98,-64,-42,62,-6,36,86,-80,-80,68,70,-18,-58,-66,64,2,-14,-34,8,10,76,54,-34},new int[]{-20,48,86,-68,-44,10,-56,68,14,-24,-10,-34,8,74,22,-76,-8,76,-54,-36,-16,-66,48,-24,60,-22,-48,0,-86,-56,-98,82,16,-32,78,90,-38,-30,-34,-8,-40},new int[]{72,74,72,20,84,0,-54,-36,28,-24,24,-16,-4,54,-88,98,-16,74,80,-60,62,48,-26,84,86,-2,40,38,84,62,-12,82,-34,-78,-64,-62,-20,-72,-70,-58,70},new int[]{88,-20,-38,-64,-74,-84,70,68,-8,50,64,-60,42,-34,-74,-98,22,-38,-4,-72,26,-84,84,48,-70,-96,42,-96,40,12,50,96,94,-82,58,-64,62,12,10,-86,96},new int[]{96,-54,80,-14,78,-66,28,86,-16,-14,-26,42,72,34,-26,28,56,82,-90,-20,-26,-58,-14,20,-24,-98,-18,-16,36,28,80,60,-58,56,-18,-66,56,-80,-74,90,64},new int[]{4,-60,-40,-16,-10,-32,-90,2,-96,70,-34,12,-24,20,66,92,96,70,74,-6,26,66,64,-82,-38,68,-98,-86,-82,-12,86,-90,68,46,-16,-22,-18,2,-30,94,-90},new int[]{22,-14,94,-22,58,-4,12,28,-80,-82,-84,56,-38,-78,-30,94,68,62,2,-16,-6,46,-96,14,58,2,-66,-88,-2,-26,-66,-42,4,60,-96,88,-14,70,-64,-44,58},new int[]{-52,58,38,-80,4,-4,-74,6,-68,-82,40,40,68,-56,-20,-74,-98,54,-32,56,-38,-40,98,-60,24,-76,52,-98,12,-24,-46,-82,0,-58,64,56,22,-16,84,0,26},new int[]{-26,32,-64,-12,18,0,22,-44,68,-72,-58,-28,38,-16,-94,58,22,-32,-80,-48,70,-56,48,56,-46,50,-36,94,-44,-64,32,-26,78,-90,98,-42,-30,32,-32,-2,46},new int[]{-2,-90,-74,-50,66,-34,-48,-10,-10,-88,-6,-88,-26,22,-18,-92,66,56,82,-46,-88,66,86,-94,30,50,-40,-18,-26,-30,38,74,-54,40,-64,16,34,98,60,-30,74},new int[]{-58,74,74,-8,54,-34,-6,-96,-80,-26,-84,40,-84,46,-44,-4,22,16,50,-48,-44,48,92,-52,-26,36,-42,54,-18,-94,44,-28,-24,66,-4,96,52,40,0,82,-84},new int[]{12,66,40,10,-70,52,44,76,-22,-64,-6,-28,14,-8,10,-54,18,-98,4,-42,34,-88,10,-8,84,0,62,98,-58,88,20,-78,-40,40,42,-52,-4,18,-40,-98,22},new int[]{-86,96,2,70,6,4,62,-22,-8,-50,-22,-16,2,-18,0,94,-60,-60,84,-96,0,68,-86,-16,-90,-64,-52,88,-58,-14,62,-94,-52,58,-38,38,18,94,-52,6,-56},new int[]{-56,-28,14,-4,-2,-20,14,-94,-76,-12,50,46,-6,54,-38,-94,-98,92,-94,-84,-98,58,84,-86,-88,52,36,42,88,-94,-20,2,-66,24,-18,-90,78,6,-70,-88,-88},new int[]{96,-70,14,-2,-48,-74,-62,92,90,-22,4,-6,40,68,34,-36,24,-24,88,66,-62,-18,48,70,-92,26,-30,6,-34,18,42,42,-32,34,92,36,-24,10,90,-74,90},new int[]{64,-98,72,76,2,40,38,94,-88,30,0,80,76,-38,-24,0,-8,36,16,32,-68,38,84,-88,80,-92,-54,92,-58,20,48,76,-26,6,40,8,-22,90,-66,-54,60},new int[]{-48,44,52,-30,78,-68,54,20,-38,-82,-6,48,-64,64,-34,-74,-70,54,60,62,88,44,-6,-82,94,-76,-46,-46,-82,18,-50,-12,32,34,76,66,-10,84,80,52,86},new int[]{40,-96,-34,70,38,10,28,14,-32,52,-94,48,92,56,26,-86,42,-36,-70,-18,86,-46,16,78,76,-40,-8,26,88,10,-26,-12,-64,82,-90,-10,-92,96,40,-52,82},new int[]{-76,54,-8,22,-84,36,76,16,14,-62,30,30,-92,-80,88,98,-64,-94,-26,10,46,46,-94,6,-18,98,-52,10,-14,-14,76,22,-90,78,26,-60,86,-56,-34,-46,50},new int[]{68,68,-4,22,22,66,18,86,38,-56,-26,44,56,-70,14,94,12,-40,-96,-22,88,54,58,-94,-6,64,92,80,70,-82,70,58,-56,-68,-38,-88,-84,-78,-94,60,-72},new int[]{-28,64,-78,-54,76,66,30,-74,36,6,-26,-84,48,22,36,96,-10,-16,18,58,-58,-58,6,-44,96,-34,48,26,6,-76,-36,30,-44,48,-36,66,-48,-10,-12,74,-70},new int[]{32,4,22,-48,8,78,-70,-78,-78,30,-70,76,-36,42,-12,72,-36,54,-50,90,82,76,-34,82,28,-30,10,34,52,74,-90,-60,-46,64,-68,-60,88,8,50,48,56}}); param0.add(new int[][]{new int[]{1,1,1,1},new int[]{0,0,0,1},new int[]{0,0,0,0},new int[]{0,1,1,1}}); param0.add(new int[][]{new int[]{96,94,33,75,69,69,91,26},new int[]{10,49,56,26,54,98,70,59},new int[]{12,39,29,62,49,76,43,55},new int[]{98,30,1,23,4,81,78,3},new int[]{82,14,46,85,89,5,11,64},new int[]{46,39,97,97,4,83,99,8},new int[]{48,50,62,64,94,79,84,12},new int[]{49,69,81,46,89,69,43,5}}); List<Integer> param1 = new ArrayList<>(); param1.add(21); param1.add(36); param1.add(23); param1.add(15); param1.add(7); param1.add(5); param1.add(23); param1.add(37); param1.add(2); param1.add(7); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
891
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/ROW_WISE_COMMON_ELEMENTS_TWO_DIAGONALS_SQUARE_MATRIX.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class ROW_WISE_COMMON_ELEMENTS_TWO_DIAGONALS_SQUARE_MATRIX{ static int f_gold ( int mat [ ] [ ] , int n ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( mat [ i ] [ i ] == mat [ i ] [ n - i - 1 ] ) res ++ ; return res ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ] [ ]> param0 = new ArrayList<>(); param0.add(new int[][]{new int[]{62}}); param0.add(new int[][]{new int[]{-56,-6,-12,64,36,12,-40,-38,14,68,62,-46,-30},new int[]{56,30,-18,-92,-10,76,6,64,14,-94,34,6,12},new int[]{-80,90,-40,2,-48,-28,58,86,-14,-50,-78,36,-96},new int[]{-92,84,-86,60,-18,18,24,-16,42,66,-10,-70,16},new int[]{68,12,78,8,-44,2,-76,4,4,8,24,-74,-60},new int[]{36,-34,90,-76,92,48,-6,-46,46,0,-8,-68,24},new int[]{54,-62,10,10,88,28,-92,-4,-92,-74,86,-52,24},new int[]{22,0,24,98,2,76,-76,-76,72,66,-88,28,48},new int[]{14,10,78,34,-64,88,48,-12,-8,80,-66,-4,-92},new int[]{-22,-68,44,92,42,20,34,-14,18,-34,-76,12,-12},new int[]{26,50,10,84,-54,-56,80,-24,42,-56,80,20,-52},new int[]{-2,-98,-46,34,-22,2,18,2,-80,70,26,38,-98},new int[]{-70,44,-54,-12,78,-10,-80,44,-34,16,-54,24,-36}}); param0.add(new int[][]{new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1},new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}}); param0.add(new int[][]{new int[]{64,13,62,37,41,79,13,99,82,90,42,83,94,22,55,35,38,49,83,12,20,92,69,27,21,97,26,25,87,47,60,20,71,80,46,57,36,9,87,39,67,13,34,75,48,41,54,12,26},new int[]{51,78,95,74,11,77,69,21,55,66,93,44,55,80,79,95,39,25,8,44,78,35,14,24,2,44,74,10,7,50,29,29,50,47,68,20,37,69,52,6,15,4,54,1,41,61,53,23,17},new int[]{53,35,55,27,25,62,59,43,10,1,57,97,60,19,4,74,59,30,1,88,81,66,56,7,79,7,87,61,83,18,20,97,68,8,21,84,48,4,89,46,19,93,4,80,95,69,59,19,63},new int[]{21,59,15,68,31,60,58,61,22,82,65,88,58,71,10,5,6,25,18,20,98,68,8,63,25,16,63,56,31,28,2,7,56,29,22,42,7,60,7,14,53,25,10,32,46,3,95,18,67},new int[]{15,28,19,88,66,26,2,49,8,58,40,51,7,2,61,29,27,67,73,4,70,78,84,60,99,20,67,1,44,16,27,71,95,75,99,81,46,22,18,81,35,1,80,88,34,25,26,57,32},new int[]{26,78,58,96,76,98,27,74,52,59,48,90,61,43,2,44,99,64,93,36,70,35,96,87,2,23,45,78,79,83,91,36,61,94,69,51,34,93,91,13,32,24,81,14,98,88,1,92,50},new int[]{18,5,12,94,10,40,95,87,90,58,11,13,82,3,83,1,86,37,94,75,92,2,65,6,11,52,5,3,76,16,30,91,96,24,25,49,3,78,90,41,65,42,49,46,28,39,97,1,11},new int[]{74,11,85,75,6,42,41,60,25,36,59,14,95,10,89,93,70,44,34,6,57,32,59,74,59,35,61,48,64,16,64,46,34,14,84,89,66,36,8,87,78,72,99,83,34,88,71,17,13},new int[]{23,28,65,90,23,29,89,11,13,75,37,53,76,76,28,63,22,82,74,73,17,21,54,19,65,17,23,11,28,60,16,19,55,83,48,14,8,84,40,91,96,72,16,79,80,60,17,92,94},new int[]{40,51,57,69,48,63,30,7,43,79,82,92,48,12,12,13,10,88,10,55,16,57,29,91,11,52,99,91,81,23,37,32,29,50,49,31,85,67,37,30,70,48,90,64,14,73,31,90,71},new int[]{15,51,10,81,51,47,52,69,3,55,87,94,54,79,33,29,18,41,37,76,65,68,36,83,88,13,22,74,70,21,88,75,41,71,76,69,76,22,57,27,91,4,30,96,82,71,57,90,55},new int[]{91,67,84,54,10,88,37,45,22,67,82,92,28,55,7,94,6,23,89,35,24,33,24,8,33,21,34,55,17,31,85,79,46,15,81,87,39,77,89,36,17,98,53,8,52,74,55,88,76},new int[]{5,28,79,7,68,20,99,83,74,66,32,86,13,5,76,32,98,20,26,90,83,55,92,20,32,38,20,11,18,27,76,18,8,93,62,75,45,53,98,2,37,56,72,68,35,45,75,94,12},new int[]{74,8,85,10,58,59,35,46,78,87,33,7,37,22,61,10,79,26,1,86,65,31,25,9,55,40,94,15,57,64,88,98,23,3,48,38,20,82,73,42,24,68,47,81,33,78,37,99,80},new int[]{66,29,59,85,53,93,30,27,51,39,82,66,97,27,31,42,19,46,25,71,33,90,31,45,53,77,27,79,74,37,6,57,86,11,21,37,80,77,6,17,57,39,61,49,23,74,72,10,12},new int[]{58,96,34,23,27,20,10,25,1,6,93,17,80,48,11,23,99,64,8,69,94,29,49,85,88,19,32,53,36,86,2,3,67,79,23,76,8,26,47,41,99,81,52,39,34,50,15,39,31},new int[]{31,27,87,26,85,60,45,36,89,51,10,33,60,82,29,23,71,16,68,90,3,24,36,59,26,53,71,84,23,89,64,74,8,51,89,16,78,72,70,19,83,73,52,34,8,55,87,88,27},new int[]{14,57,68,56,58,90,49,65,72,65,73,7,79,37,37,43,44,16,82,67,95,2,47,51,70,9,89,65,90,69,94,18,97,35,38,67,77,18,4,95,78,22,67,86,74,35,72,25,6},new int[]{36,20,73,37,38,25,96,92,83,61,51,80,59,22,41,14,90,7,94,25,31,30,85,14,58,68,10,60,44,80,96,43,82,47,31,83,19,70,7,34,54,43,74,52,37,46,42,49,82},new int[]{52,52,61,51,71,67,28,85,72,35,66,48,50,49,81,31,69,15,28,87,96,97,21,1,16,37,80,92,16,8,31,58,56,44,96,7,66,11,55,18,69,90,53,15,22,57,8,98,18},new int[]{85,30,77,51,48,29,46,76,27,42,34,4,56,28,46,97,57,20,69,24,76,54,58,46,12,71,27,6,77,17,35,49,84,1,61,57,66,63,52,42,66,21,84,23,18,28,71,18,27},new int[]{25,53,3,58,79,23,32,85,49,99,90,65,88,91,98,57,30,1,46,65,7,77,74,65,30,88,77,53,38,76,90,72,46,59,56,94,82,7,33,63,81,37,57,47,29,77,28,32,90},new int[]{79,94,9,36,56,25,72,21,73,96,11,73,20,31,79,50,95,9,36,63,8,50,57,2,91,1,84,74,41,71,73,97,36,18,69,57,49,55,95,89,36,83,96,23,60,15,61,75,72},new int[]{41,24,81,57,15,46,19,53,56,45,66,62,79,11,48,73,91,48,8,65,91,88,55,36,13,38,68,66,21,45,65,41,13,34,2,85,47,28,53,60,5,9,81,40,58,51,65,9,61},new int[]{68,8,55,2,80,75,83,35,24,58,33,66,67,18,24,16,14,50,61,8,13,18,58,75,68,77,47,69,61,39,36,26,92,67,59,43,44,25,19,68,86,46,83,22,32,17,22,86,44},new int[]{67,74,20,20,55,32,97,12,21,40,7,72,34,62,49,44,38,23,14,93,61,56,6,47,19,93,63,79,12,17,83,67,72,14,88,86,45,33,35,96,28,16,31,17,27,17,54,3,27},new int[]{30,28,83,88,86,45,62,94,25,60,98,55,73,92,29,32,37,2,13,26,50,93,82,77,31,59,91,52,52,42,70,31,92,46,19,59,79,87,62,25,22,57,11,40,46,29,60,57,37},new int[]{52,73,62,86,43,59,48,9,71,90,95,39,68,64,90,25,65,50,45,25,32,90,93,79,50,42,37,9,46,17,44,83,53,23,82,30,57,35,21,48,46,1,38,38,48,51,99,99,28},new int[]{71,15,96,82,95,23,68,39,4,30,49,58,1,91,57,23,15,59,98,36,64,7,72,45,69,49,25,3,65,12,57,28,34,41,14,61,55,84,32,70,93,12,74,67,50,45,17,60,55},new int[]{51,46,30,7,56,94,95,46,18,72,71,29,67,18,12,39,84,15,56,68,71,98,26,64,83,45,70,68,65,47,94,54,90,62,25,77,81,54,44,1,27,72,50,45,42,60,11,99,19},new int[]{85,67,94,8,11,67,24,97,22,41,45,56,4,59,14,95,60,35,52,38,73,2,67,54,37,15,88,53,20,20,98,94,69,44,48,6,3,22,1,97,78,20,64,99,39,60,64,48,97},new int[]{8,26,4,9,25,32,34,80,48,56,59,21,42,94,62,18,99,74,77,26,51,91,79,20,43,79,10,37,53,62,41,31,89,18,79,89,69,86,28,94,71,27,17,29,75,94,91,86,97},new int[]{49,81,5,68,41,85,73,58,47,36,93,56,85,97,92,14,95,30,94,5,95,61,11,46,99,88,30,1,5,99,83,25,91,79,60,74,91,22,19,21,75,87,98,75,80,40,47,21,21},new int[]{88,90,31,75,50,83,38,23,51,66,47,13,78,94,58,46,1,86,14,83,63,97,81,96,17,34,68,90,74,96,27,90,82,86,92,93,70,72,19,90,75,2,43,85,53,40,56,47,15},new int[]{55,26,54,52,66,72,79,80,30,42,35,48,67,94,95,9,76,53,42,11,9,52,1,81,35,86,27,83,71,22,50,30,32,35,43,65,96,75,81,37,21,43,51,57,78,48,62,98,66},new int[]{97,93,36,10,47,33,79,54,36,6,25,62,95,60,71,17,72,41,26,67,23,11,62,46,30,10,87,32,92,34,23,34,27,30,44,46,64,28,93,60,98,46,47,66,37,52,58,43,45},new int[]{98,59,98,53,80,39,88,30,86,95,24,10,55,90,27,78,16,8,59,14,36,36,66,95,75,73,7,83,81,75,26,96,49,42,82,75,20,7,50,92,89,12,46,92,36,94,48,59,95},new int[]{11,72,86,5,87,85,61,66,57,15,50,45,95,47,47,39,60,26,24,68,21,26,8,11,74,41,55,82,88,88,15,97,9,91,86,26,60,89,71,1,2,37,53,88,88,22,19,36,48},new int[]{90,10,35,43,40,38,58,19,63,36,80,86,4,13,26,19,77,49,68,72,80,42,57,58,12,88,67,54,73,55,53,68,6,60,65,98,42,81,38,11,79,90,3,35,81,87,95,99,25},new int[]{87,42,10,89,98,84,61,9,81,79,96,1,67,76,61,43,81,22,75,93,50,90,59,58,94,23,13,77,67,69,9,84,95,4,17,56,34,59,78,24,29,33,47,95,60,84,52,68,78},new int[]{50,57,35,13,11,96,43,27,78,52,22,73,27,58,6,20,51,57,66,2,92,55,88,64,64,22,95,58,53,54,44,91,32,21,84,22,58,64,35,68,14,68,99,94,55,26,75,8,59},new int[]{13,56,30,50,9,30,68,42,25,48,64,57,76,30,61,57,84,27,77,47,10,9,40,67,37,68,54,80,72,28,26,13,7,20,81,26,43,66,16,95,19,18,18,29,68,59,4,31,40},new int[]{8,68,45,50,46,5,64,34,57,99,90,35,50,19,2,39,61,81,67,95,42,14,31,82,36,42,73,16,67,48,65,22,65,88,84,84,91,76,36,43,33,68,70,7,41,92,3,10,37},new int[]{10,37,21,61,80,35,87,10,97,91,86,92,13,26,11,12,28,78,51,94,16,20,5,78,99,42,70,34,80,61,58,6,95,51,57,58,69,75,15,36,49,71,64,87,69,5,48,77,20},new int[]{8,80,16,89,60,95,60,48,17,60,91,24,40,46,25,44,64,2,90,9,8,66,36,63,89,76,5,34,79,20,18,50,9,25,17,94,95,84,84,98,90,44,27,18,96,65,38,17,18},new int[]{24,26,1,41,26,67,32,84,65,53,53,87,3,22,85,23,39,83,5,5,7,71,51,25,94,78,50,84,81,23,61,17,28,52,94,59,50,74,57,27,91,94,92,10,24,81,67,66,79},new int[]{78,64,98,56,21,88,2,86,43,17,84,55,1,23,47,56,15,92,28,84,48,13,58,48,18,97,30,63,91,95,28,85,3,38,17,18,32,65,33,6,78,63,42,96,68,49,75,76,98},new int[]{67,87,83,38,2,96,10,65,83,24,4,35,44,21,30,21,12,78,29,14,80,20,63,34,52,42,91,56,19,31,84,91,58,64,48,62,2,95,17,19,9,83,93,47,67,52,83,34,21},new int[]{60,48,17,82,88,76,45,26,97,33,39,41,98,28,1,46,27,31,32,30,79,76,19,98,24,39,5,24,99,65,16,27,19,49,50,76,39,21,59,4,71,59,74,58,92,81,60,70,81}}); param0.add(new int[][]{new int[]{18}}); param0.add(new int[][]{new int[]{0,1,0,0,1,1,0,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,0,1,1,1,1,0,0,1,0,0,1,0,1,0,1,0,0,0,1,1,1},new int[]{1,0,1,1,1,0,1,0,0,0,0,0,1,1,1,1,1,1,1,0,1,0,0,1,1,0,0,0,1,1,0,1,0,0,1,1,0,1,0,1,1,1,0,0},new int[]{1,1,1,1,1,0,0,1,0,0,1,0,0,1,1,1,0,0,1,1,1,1,1,0,1,0,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,0,0,0},new int[]{0,0,1,1,1,1,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1,0,1,1,0,1,0,0,1,1,0},new int[]{1,0,0,0,1,0,0,0,1,1,0,1,0,1,1,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,1,1,0,0,0,1,1,0,1,0,0,0,0},new int[]{0,0,1,1,0,0,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,1,1,1,1,1,1,1,1,0,0,0,1,0,1,0,1,0,0,1,1,0,0,1},new int[]{1,1,0,0,1,1,1,1,1,0,1,0,1,0,1,0,0,0,0,1,1,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,1,1,0,1,0,0,1},new int[]{0,0,0,1,0,0,0,1,0,1,1,0,1,1,0,1,1,1,0,0,1,0,1,0,0,0,0,1,0,1,1,1,0,1,0,1,1,1,0,0,1,1,0,1},new int[]{1,1,0,1,1,1,0,1,0,0,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,0,0,1,0},new int[]{1,1,0,1,0,0,1,0,1,0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,1,0,0,0,0,0,0,0,1,0,0,1,1},new int[]{0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,1,1,0,1,0,0,1,0,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,1,1,0,1,0},new int[]{0,1,0,0,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,1,1,1,0,0,0,1,1,1,1,1,0,1,0,1,0,0,1,1,0,0,1,0,0,0},new int[]{1,0,0,0,1,0,0,1,0,1,1,0,0,0,1,0,1,1,1,0,1,0,1,0,1,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,1,1},new int[]{0,0,0,1,1,1,1,1,1,0,1,1,0,0,0,1,0,0,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,0,1,1,0,1,1},new int[]{1,1,0,1,1,1,1,1,0,1,0,1,0,1,1,1,0,0,0,0,0,1,1,1,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,1},new int[]{0,1,0,1,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,1,0,0,1,1,0,0,1,1,1,0,0,1,0,0,0,0},new int[]{1,0,1,1,0,0,1,1,0,1,0,1,1,1,1,0,0,0,1,0,0,1,0,0,0,1,1,0,0,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0},new int[]{0,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,0,0,1},new int[]{1,0,1,0,0,1,0,1,0,1,1,1,1,1,0,1,0,0,1,0,0,1,0,1,0,0,1,1,1,1,1,0,1,0,0,1,1,1,1,0,0,0,0,1},new int[]{1,0,0,1,1,0,1,1,0,0,1,1,0,1,0,0,1,0,1,0,0,0,1,1,0,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1},new int[]{0,1,0,0,1,0,0,1,0,0,0,1,0,1,1,1,1,0,1,1,0,0,0,1,1,1,1,0,0,0,0,0,0,1,1,1,0,1,1,0,1,1,1,1},new int[]{0,0,1,1,1,0,1,1,0,1,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0},new int[]{0,0,0,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0},new int[]{0,0,1,1,0,1,1,1,0,1,1,0,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,0,1,1,0,0,1,1,0,1,0,0,0,1,1,0,1,1},new int[]{1,1,0,1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,0,1,1,1,0,0,0,0,0,1,0,0,1,1,0,1,1,1,0,1,1,1,0,1,1,0},new int[]{1,1,1,0,1,1,1,0,1,1,0,0,1,0,0,0,0,1,1,1,0,0,0,0,0,1,0,1,0,1,0,0,1,0,1,0,1,1,1,0,0,1,0,0},new int[]{1,1,0,0,0,0,0,1,0,1,1,0,1,0,1,0,1,1,1,1,1,1,0,1,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,1,1,1,1,0},new int[]{1,0,0,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,1,1,1,0,1,0,1,0,0,0,1,1,0,0,0,0,0,1,1,0,0,1,1},new int[]{0,0,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1},new int[]{0,1,1,1,0,0,0,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,0,1,1,0,0,0,0,1,0,1,1,1,0,1,1,1},new int[]{0,1,0,0,0,0,1,1,0,0,0,0,0,1,1,0,1,1,1,0,1,0,0,0,0,1,0,1,0,1,1,1,1,1,0,0,0,1,1,1,0,0,1,1},new int[]{0,1,0,1,1,0,1,0,1,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,1,1,1,0,1,0,0,1,1,0},new int[]{0,1,1,0,1,0,1,0,0,0,1,0,1,0,1,1,1,1,1,0,1,1,1,0,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,1,1,1,1,0},new int[]{1,0,1,1,1,0,0,1,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,1},new int[]{0,0,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,1,0,1,0,1,0,0,1,0,0,1,1,0,1,0,0,1,1,1,1,1,0,1,0,0},new int[]{1,0,0,1,0,1,0,1,0,1,1,0,0,0,0,0,0,1,1,1,1,0,0,1,1,0,0,1,1,1,0,0,1,1,1,1,1,0,0,1,0,1,0,1},new int[]{1,1,0,0,1,0,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,0,1,0,1,1,0,0,1,0,0,1,1,0,0,0,0,1,0,0,1},new int[]{0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,1,1,0,1,1,0,0,0,0,1,0,1,0,0,1,0,0,1,1,1,1,0,0,0,0,1,0,0},new int[]{1,1,1,1,1,0,0,1,0,1,1,0,0,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,0,0,0,0},new int[]{0,1,0,1,1,0,0,0,1,1,0,0,1,0,1,0,0,0,1,1,1,0,1,1,0,0,0,1,1,1,0,0,0,1,1,0,1,1,0,1,0,0,1,0},new int[]{0,0,0,1,0,1,1,0,0,0,1,1,1,0,1,1,0,0,1,0,0,1,1,1,0,0,1,1,0,1,0,1,0,0,0,0,1,0,1,0,0,0,1,1},new int[]{1,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,1,0,1,1,1,0,0,0,1,1,0,1,0,0,1,0,0,1,0,0,1,1,0,0,0,0,0},new int[]{0,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,0,0,0,0,1,1,1,1,0,1},new int[]{1,1,0,0,1,1,1,1,1,0,0,0,1,0,1,0,1,1,1,0,1,1,0,1,1,1,0,0,0,1,1,1,0,1,0,0,1,0,1,1,0,0,1,1}}); param0.add(new int[][]{new int[]{3,15,34,40,66,69,71,88},new int[]{6,14,42,43,51,52,58,72},new int[]{14,15,17,21,78,80,87,93},new int[]{7,15,19,20,25,31,68,69},new int[]{1,3,6,68,83,83,86,97},new int[]{17,30,52,54,58,79,81,83},new int[]{1,32,43,48,70,80,93,97},new int[]{3,5,12,47,49,52,74,78}}); param0.add(new int[][]{new int[]{-56,56,12,-42,38,-78,22,-30},new int[]{-24,-28,-80,-6,18,-2,76,-8},new int[]{-46,-74,-48,-98,32,52,60,48},new int[]{42,-46,-84,44,-86,72,8,70},new int[]{80,90,50,-26,-98,84,8,-52},new int[]{-78,-46,26,2,-30,-20,-8,18},new int[]{98,42,62,74,-30,-18,26,-42},new int[]{90,34,12,-88,-60,-92,-10,-60}}); param0.add(new int[][]{new int[]{0,0,0,0,0,0,0,1,1},new int[]{0,0,0,0,0,0,0,0,1},new int[]{0,0,0,0,0,0,0,1,1},new int[]{0,0,0,1,1,1,1,1,1},new int[]{0,0,0,1,1,1,1,1,1},new int[]{0,0,0,0,0,1,1,1,1},new int[]{0,0,0,0,0,0,1,1,1},new int[]{0,0,0,1,1,1,1,1,1},new int[]{0,0,1,1,1,1,1,1,1}}); param0.add(new int[][]{new int[]{14,22,81,76,33,79,91,2,42,5,11,94,9,49,25,93,44,25,71,66,25,30,57,55,25,10,76,34,90,55,54,41},new int[]{93,50,13,70,93,30,5,44,65,70,82,31,88,11,8,95,27,52,93,35,35,72,49,59,54,51,63,50,22,53,33,54},new int[]{69,1,38,60,78,26,48,16,32,82,74,80,74,84,13,58,46,84,84,39,16,84,20,81,10,52,32,33,28,23,64,52},new int[]{87,97,97,85,72,28,33,38,78,93,82,50,33,89,11,93,18,73,82,22,13,40,45,64,13,1,41,27,35,58,40,86},new int[]{59,71,95,38,59,97,86,84,17,52,61,37,24,40,99,88,91,51,7,32,30,2,61,64,65,1,97,86,78,22,67,10},new int[]{60,60,50,9,15,68,42,35,11,9,91,9,60,94,99,34,46,21,12,92,67,19,74,90,96,16,32,25,40,21,78,84},new int[]{88,44,57,46,1,48,15,91,85,47,52,57,82,37,28,88,35,85,66,17,88,69,91,46,44,38,20,39,27,44,47,94},new int[]{32,54,58,78,33,70,52,98,49,13,25,57,99,36,93,42,96,30,56,66,43,8,17,47,67,5,97,66,65,90,97,8},new int[]{32,37,20,6,56,42,36,49,56,66,91,37,3,50,56,80,49,80,57,11,68,32,76,92,45,27,63,28,21,74,31,80},new int[]{32,82,42,52,68,46,3,65,48,75,32,30,62,55,70,31,81,80,78,71,40,20,96,20,91,38,69,42,4,63,21,54},new int[]{91,99,6,10,30,30,98,73,48,33,58,75,52,55,65,4,78,28,90,18,30,97,69,34,64,6,64,83,5,26,77,51},new int[]{70,13,73,23,38,63,40,51,18,60,37,12,52,49,68,45,24,3,82,73,66,96,22,92,29,86,66,21,6,41,56,97},new int[]{42,55,69,3,21,42,44,8,69,86,41,65,62,40,21,56,92,40,60,91,9,66,32,3,16,97,36,10,56,36,65,51},new int[]{43,69,10,87,94,30,21,13,89,38,57,50,55,31,10,36,79,66,71,4,29,90,72,24,24,84,2,97,84,46,5,50},new int[]{14,5,93,73,7,57,29,7,13,53,19,20,15,69,4,61,20,89,4,91,84,91,11,41,67,51,20,22,26,57,82,12},new int[]{44,36,65,68,45,48,92,98,39,93,30,50,75,13,22,6,61,60,74,78,62,14,51,88,17,47,49,36,41,28,8,77},new int[]{73,28,20,71,44,84,58,40,44,12,8,16,70,36,34,3,89,24,15,23,19,53,67,81,5,31,37,91,63,9,12,58},new int[]{67,39,73,31,31,45,71,71,56,93,60,77,73,3,12,67,71,54,81,41,60,31,94,96,43,65,99,95,14,17,48,78},new int[]{95,64,57,19,83,76,74,47,80,60,90,72,21,67,66,67,34,53,86,79,2,83,76,66,19,66,86,82,82,25,1,86},new int[]{3,8,21,55,35,37,20,66,21,2,12,74,68,86,46,23,35,68,35,8,64,19,6,3,14,71,68,66,8,74,34,6},new int[]{32,21,43,18,61,11,88,4,99,59,40,33,86,95,44,52,97,40,31,72,86,86,20,54,77,56,77,52,88,76,58,4},new int[]{41,62,38,39,75,54,52,17,7,28,72,57,26,44,85,79,37,99,39,9,47,4,28,27,6,6,87,66,83,42,19,11},new int[]{53,31,97,12,33,12,98,18,68,15,40,40,19,77,20,37,20,42,95,75,84,86,50,86,34,91,74,50,20,30,56,39},new int[]{4,98,74,96,97,90,64,40,45,77,34,1,15,21,74,21,51,15,42,19,53,95,48,22,2,86,35,21,70,51,99,72},new int[]{71,12,90,92,38,43,40,8,51,65,79,16,5,39,75,95,2,62,50,46,44,97,15,14,81,65,71,17,69,44,41,90},new int[]{79,53,94,59,58,8,50,44,73,12,33,62,90,57,98,46,32,38,16,62,53,48,49,56,17,26,95,42,85,83,12,48},new int[]{43,86,56,15,13,92,83,55,85,61,53,27,16,24,42,1,95,42,20,83,46,90,46,67,58,55,32,84,40,19,7,28},new int[]{70,21,57,89,23,71,62,51,44,78,23,22,43,83,86,73,96,82,52,74,45,37,46,54,23,87,59,77,96,83,94,44},new int[]{65,73,74,45,55,37,84,64,29,35,86,13,14,38,28,94,39,91,6,66,28,96,74,48,93,71,95,91,25,33,97,28},new int[]{26,99,94,14,64,28,5,9,26,31,36,88,56,60,10,56,6,74,48,93,13,22,99,43,35,13,46,52,79,34,87,16},new int[]{90,21,62,63,17,14,78,40,64,35,46,92,68,49,1,91,90,8,60,52,34,81,73,62,75,16,33,40,1,61,88,75},new int[]{10,61,27,86,2,14,32,60,68,75,21,85,49,78,99,75,53,79,16,55,83,70,7,8,86,83,48,34,73,5,69,56}}); List<Integer> param1 = new ArrayList<>(); param1.add(0); param1.add(10); param1.add(31); param1.add(48); param1.add(0); param1.add(40); param1.add(4); param1.add(4); param1.add(4); param1.add(24); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
892
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/FIND_SUBARRAY_WITH_GIVEN_SUM_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FIND_SUBARRAY_WITH_GIVEN_SUM_1{ static int f_gold ( int arr [ ] , int n , int sum ) { int curr_sum = arr [ 0 ] , start = 0 , i ; for ( i = 1 ; i <= n ; i ++ ) { while ( curr_sum > sum && start < i - 1 ) { curr_sum = curr_sum - arr [ start ] ; start ++ ; } if ( curr_sum == sum ) { int p = i - 1 ; System . out . println ( "Sum found between indexes " + start + " and " + p ) ; return 1 ; } if ( i < n ) curr_sum = curr_sum + arr [ i ] ; } System . out . println ( "No subarray found" ) ; return 0 ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{7,7,8,8,23,24,28,32,48,53,56,62,69,77,81,82,84,87,88,90}); param0.add(new int[]{-62,-62,-80,-30,-80,44,-12,-76,16,-52,-86,72,32,-60,-70,-62,-78,-96,-18,40,-4,-18,-58,30,-70,6,0,-62,-66,20,92,-64,20,-48,48,-32,64,22,16,26}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{50,25,6,87,55,86,61,97,24,30,51,43,26,1,80,47,19,36,64,62,92,5,48,27,82,76,70,59,1,43,1,36,28,9,52,22,43}); param0.add(new int[]{-86,-76,-64,-22,-16,-8,4,6,8,32,38,60,68,74}); param0.add(new int[]{0,0,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,1,1,1,1,1,0,0,1,0,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0}); param0.add(new int[]{7,7,12,25,25,32,33,34,37,39,39,41,46,48,56,56,57,58,61,62,62,63,65,66,69,72,74,78,78,79,80,85,89,94,95,99}); param0.add(new int[]{98,-60}); param0.add(new int[]{0,0,0,0,1,1,1,1,1,1}); param0.add(new int[]{80,89,83,42,75,30,64,25,95,17,90,6,11,1,77,16,75,86,96,67,27,80,27}); List<Integer> param1 = new ArrayList<>(); param1.add(16); param1.add(39); param1.add(40); param1.add(29); param1.add(7); param1.add(31); param1.add(22); param1.add(1); param1.add(8); param1.add(16); List<Integer> param2 = new ArrayList<>(); param2.add(31); param2.add(44); param2.add(7); param2.add(105); param2.add(2); param2.add(10); param2.add(39); param2.add(98); param2.add(0); param2.add(108); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i),param2.get(i)) == f_gold(param0.get(i),param1.get(i),param2.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
893
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/HYPERCUBE_GRAPH.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class HYPERCUBE_GRAPH{ static int f_gold ( int n ) { if ( n == 1 ) return 2 ; return 2 * f_gold ( n - 1 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(72); param0.add(28); param0.add(45); param0.add(41); param0.add(94); param0.add(97); param0.add(97); param0.add(36); param0.add(91); param0.add(84); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
894
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/HEXAGONAL_NUMBER.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class HEXAGONAL_NUMBER{ static int f_gold ( int n ) { return n * ( 2 * n - 1 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(38); param0.add(44); param0.add(58); param0.add(10); param0.add(31); param0.add(53); param0.add(94); param0.add(64); param0.add(71); param0.add(59); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
895
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/LEXICOGRAPHICALLY_NEXT_STRING.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class LEXICOGRAPHICALLY_NEXT_STRING{ public static String f_gold ( String str ) { if ( str == "" ) return "a" ; int i = str . length ( ) - 1 ; while ( str . charAt ( i ) == 'z' && i >= 0 ) i -- ; if ( i == - 1 ) str = str + 'a' ; else str = str . substring ( 0 , i ) + ( char ) ( ( int ) ( str . charAt ( i ) ) + 1 ) + str . substring ( i + 1 ) ; return str ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("amKIRzPiqLTIy"); param0.add("68"); param0.add("100"); param0.add("f"); param0.add("802205375"); param0.add("0111"); param0.add("GRjRYIvYwgua"); param0.add("8139910006809"); param0.add("100101"); param0.add("rw"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)).equals(f_gold(param0.get(i)))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
896
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/CHECK_LARGE_NUMBER_DIVISIBLE_9_NOT.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class CHECK_LARGE_NUMBER_DIVISIBLE_9_NOT{ static boolean f_gold ( String str ) { int n = str . length ( ) ; int digitSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) digitSum += ( str . charAt ( i ) - '0' ) ; return ( digitSum % 9 == 0 ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<String> param0 = new ArrayList<>(); param0.add("69354"); param0.add("43347276812854"); param0.add("0111111111"); param0.add("9999918"); param0.add("333"); param0.add("1011011101"); param0.add("1"); param0.add("2284737"); param0.add("011001"); param0.add("cc"); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
897
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/FIND_THE_LARGEST_SUBARRAY_WITH_0_SUM.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class FIND_THE_LARGEST_SUBARRAY_WITH_0_SUM{ static int f_gold ( int arr [ ] , int n ) { int max_len = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int curr_sum = 0 ; for ( int j = i ; j < n ; j ++ ) { curr_sum += arr [ j ] ; if ( curr_sum == 0 ) max_len = Math . max ( max_len , j - i + 1 ) ; } } return max_len ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<int [ ]> param0 = new ArrayList<>(); param0.add(new int[]{1,2,6,6,15,23,26,27,30,34,35,38,42,43,44,46,50,53,53,57,62,65,67,70,76,79,81,82,85,90}); param0.add(new int[]{72,-6,-24,-82,16,78,-82,38,-2,78,-60,40,26,-82,-32,-56,52,14,62,-18,-84,-94,48,54,2,-28}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{14,67,44,5,60,87,23,37,44,70,47,52,38,30,78,60,95,62,3,45,96,35,81,8,82,75,76,64,33,65,65,49,1,63,99,53,40,12,46,93,88,27,89,89,60,3,92,63}); param0.add(new int[]{-98,-98,-96,-86,-74,-74,-72,-70,-70,-66,-66,-66,-64,-64,-50,-50,-48,-38,-28,-24,-24,-18,-16,-14,-8,-6,-2,-2,10,28,32,38,42,54,54,62,68,84,88}); param0.add(new int[]{0,1,0,0,0,1,1,1,0,0,0,0,1,1,0,0,0,0,0,1,1,0}); param0.add(new int[]{6,14,26,27,37,50,51,54,55,67,68,72,83,84,95,99}); param0.add(new int[]{-6,-96,-46,4,-50,-56,-34,6,-72,-68,92,88,-80,18,58,20,34,-22,-18,-90,-80,-24,-82,6,54,70,22,94}); param0.add(new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); param0.add(new int[]{65,34,82,43,15,94,34,50,70,77,83,26,85,5}); List<Integer> param1 = new ArrayList<>(); param1.add(19); param1.add(24); param1.add(18); param1.add(39); param1.add(25); param1.add(12); param1.add(10); param1.add(22); param1.add(45); param1.add(10); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i),param1.get(i)) == f_gold(param0.get(i),param1.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
898
0
Create_ds/CodeGen/data/transcoder_evaluation_gfg
Create_ds/CodeGen/data/transcoder_evaluation_gfg/java/SUM_BINOMIAL_COEFFICIENTS_1.java
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // import java.util. *; import java.util.stream.*; import java.lang.*; import javafx.util.Pair; public class SUM_BINOMIAL_COEFFICIENTS_1{ static int f_gold ( int n ) { return ( 1 << n ) ; } //TOFILL public static void main(String args[]) { int n_success = 0; List<Integer> param0 = new ArrayList<>(); param0.add(48); param0.add(42); param0.add(15); param0.add(75); param0.add(23); param0.add(41); param0.add(46); param0.add(99); param0.add(36); param0.add(53); for(int i = 0; i < param0.size(); ++i) { if(f_filled(param0.get(i)) == f_gold(param0.get(i))) { n_success+=1; } } System.out.println("#Results:" + n_success + ", " + param0.size()); } }
899