Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2013-2015 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.services.s3.internal.crypto;
 
 import static com.amazonaws.services.s3.internal.crypto.KMSSecuredCEK.isKMSKeyWrapped;
 import static com.amazonaws.services.s3.model.ExtraMaterialsDescription.NONE;
 import static com.amazonaws.util.BinaryUtils.copyAllBytesFrom;
 import static com.amazonaws.util.Throwables.failure;
 
 import java.util.Map;
 
 
Cryptographic material used for client-side content encrypt/decryption in S3. This includes the randomly generated one-time secured CEK (content-encryption-key) and the respective key wrapping algorithm, if any, and the cryptographic scheme in use.
 
 final class ContentCryptoMaterial {
     // null if cek is not secured via key wrapping
     private final String keyWrappingAlgorithm;
     private final CipherLite cipherLite;
 
     private final Map<StringStringkekMaterialsDescription;
     private final byte[] encryptedCEK;
 
     ContentCryptoMaterial(Map<StringStringkekMaterialsDescription,
             byte[] encryptedCEK,
             String keyWrappingAlgorithm,
             CipherLite cipherLite) {
         this. = cipherLite;
         this. = keyWrappingAlgorithm;
         this. = encryptedCEK.clone();
         this. = kekMaterialsDescription;
     }

    
Returns the key wrapping algorithm, or null if the content key is not secured via a key wrapping algorithm.

Note if the returned value is KMSSecuredCEK.KEY_PROTECTION_MECHANISM, it means the key is protected via KMS rather than a direct key-wrapping algorithm.

 
         return ;
     }

    
Returns true if KMS is used for the content key protection; false otherwise.
 
     private boolean usesKMSKey() {
         return isKMSKeyWrapped();
    }

    
Returns the content crypto scheme.
        return .getContentCryptoScheme();
    }

    
Returns the given metadata updated with this content crypto material.
        return mode == . && !usesKMSKey()
             ? toObjectMetadataEO(metadata)
             : toObjectMetadata(metadata);
    }

    
Returns the metadata in the latest format.
    private ObjectMetadata toObjectMetadata(ObjectMetadata metadata) {
        // If we generated a symmetric key to encrypt the data, store it in the
        // object metadata.
        byte[] encryptedCEK = getEncryptedCEK();
        metadata.addUserMetadata(.,
                Base64.encodeAsString(encryptedCEK));
        // Put the cipher initialization vector (IV) into the object metadata
        byte[] iv = .getIV();
        metadata.addUserMetadata(., Base64.encodeAsString(iv));
        // Put the materials description into the object metadata as JSON
                kekMaterialDescAsJson());
        // The CRYPTO_CEK_ALGORITHM, CRYPTO_TAG_LENGTH and
        // CRYPTO_KEYWRAP_ALGORITHM were not available in the Encryption Only
        // (EO) implementation
        ContentCryptoScheme scheme = getContentCryptoScheme();
                scheme.getCipherAlgorithm());
        int tagLen = scheme.getTagLengthInBits();
        if (tagLen > 0)
            metadata.addUserMetadata(.,
                    String.valueOf(tagLen));
        String keyWrapAlgo = getKeyWrappingAlgorithm();
        if (keyWrapAlgo != null)
            metadata.addUserMetadata(.,
                    keyWrapAlgo);
        return metadata;
    }

    
Returns the metadata in backward compatibility (old) format, so it can be read by older version of the AWS SDK.
    private ObjectMetadata toObjectMetadataEO(ObjectMetadata metadata) {
        // If we generated a symmetric key to encrypt the data, store it in the
        // object metadata.
        byte[] encryptedCEK = getEncryptedCEK();
        metadata.addUserMetadata(.,
                Base64.encodeAsString(encryptedCEK));
        // Put the cipher initialization vector (IV) into the object metadata
        byte[] iv = .getIV();
        metadata.addUserMetadata(., Base64.encodeAsString(iv));
        // Put the materials description into the object metadata as JSON
                kekMaterialDescAsJson());
        return metadata;
    }

    
Returns the json string in backward compatibility (old) format, so it can be read by older version of the AWS SDK.
    String toJsonString(CryptoMode mode) {
        return mode == . && !usesKMSKey()
            ? toJsonStringEO() : toJsonString();
    }

    
Returns the json string in the latest format.
    private String toJsonString() {
        Map<StringStringmap = new HashMap<StringString>();
        byte[] encryptedCEK = getEncryptedCEK();
        map.put(., Base64.encodeAsString(encryptedCEK));
        byte[] iv = .getIV();
        map.put(., Base64.encodeAsString(iv));
        // The CRYPTO_CEK_ALGORITHM, CRYPTO_TAG_LENGTH and
        // CRYPTO_KEYWRAP_ALGORITHM were not available in the Encryption Only
        // (EO) implementation
        ContentCryptoScheme scheme = getContentCryptoScheme();
        map.put(.scheme.getCipherAlgorithm());
        int tagLen = scheme.getTagLengthInBits();
        if (tagLen > 0)
            map.put(., String.valueOf(tagLen));
        String keyWrapAlgo = getKeyWrappingAlgorithm();
        if (keyWrapAlgo != null)
            map.put(.keyWrapAlgo);
        return Jackson.toJsonString(map);
    }
    private String toJsonStringEO() {
        Map<StringStringmap = new HashMap<StringString>();
        byte[] encryptedCEK = getEncryptedCEK();
        map.put(., Base64.encodeAsString(encryptedCEK));
        byte[] iv = .getIV();
        map.put(., Base64.encodeAsString(iv));
        return Jackson.toJsonString(map);
    }
    
Returns the key-encrypting-key material description as a non-null json string;
    private String kekMaterialDescAsJson() {
        Map<StringStringkekMaterialDesc = getKEKMaterialsDescription();
        if (kekMaterialDesc == null)
            kekMaterialDesc = Collections.emptyMap();
        return Jackson.toJsonString(kekMaterialDesc);
    }

    
Returns the corresponding kek material description from the given json; or null if the input is null.
    @SuppressWarnings("unchecked")
    private static Map<StringStringmatdescFromJson(String json) {
        Map<StringStringmap = Jackson.fromJsonString(jsonMap.class);
        return map == null ? null : Collections.unmodifiableMap(map);
    }

    
Returns the content encrypting key unwrapped or decrypted. Note if KMS is used for key protection, a remote call will be made to KMS to decrypt the ciphertext blob.

Parameters:
cekSecured the content encrypting key in wrapped or encrypted form; must not be null
keyWrapAlgo key wrapping algorithm; or null if direct encryption instead of key wrapping is used
materials the client key encrypting key material for the content encrypting key
securityProvider security provider or null if the default security provider of the JCE is used
    private static SecretKey cek(byte[] cekSecuredString keyWrapAlgo,
            EncryptionMaterials materialsProvider securityProvider,
            ContentCryptoScheme contentCryptoSchemeAWSKMSClient kms) {
        if (isKMSKeyWrapped(keyWrapAlgo))
            return cekByKMS(cekSecuredkeyWrapAlgomaterialscontentCryptoSchemekms);
        Key kek;
        if (materials.getKeyPair() != null) {
            // Do envelope decryption with private key from key pair
            kek = materials.getKeyPair().getPrivate();
            if (kek == null) {
                throw new AmazonClientException("Key encrypting key not available");
            }
        } else {
            // Do envelope decryption with symmetric key
            kek = materials.getSymmetricKey();
            if (kek == null) {
                throw new AmazonClientException("Key encrypting key not available");
            }
        }
        try {
            if (keyWrapAlgo != null) {
                // Key wrapping specified
                Cipher cipher = securityProvider == null ? Cipher
                        .getInstance(keyWrapAlgo) : Cipher.getInstance(
                        keyWrapAlgosecurityProvider);
                cipher.init(.kek);
                return (SecretKeycipher.unwrap(cekSecuredkeyWrapAlgo,
                        .);
            }
            // fall back to the Encryption Only (EO) key decrypting method
            Cipher cipher;
            if (securityProvider != null) {
                cipher = Cipher.getInstance(kek.getAlgorithm(),
                        securityProvider);
            } else {
                cipher = Cipher.getInstance(kek.getAlgorithm());
            }
            cipher.init(.kek);
            byte[] decryptedSymmetricKeyBytes = cipher.doFinal(cekSecured);
            return new SecretKeySpec(decryptedSymmetricKeyBytes,
                    .);
        } catch (Exception e) {
            throw failure(e"Unable to decrypt symmetric key from object metadata");
        }
    }

    
Decrypts the secured CEK via KMS; involves network calls.

Returns:
the CEK (in plaintext).
    private static SecretKey cekByKMS(byte[] cekSecuredString keyWrapAlgo,
            EncryptionMaterials materials,
            ContentCryptoScheme contentCryptoSchemeAWSKMSClient kms) {
        DecryptRequest kmsreq = new DecryptRequest()
            .withEncryptionContext(materials.getMaterialsDescription())
            .withCiphertextBlob(ByteBuffer.wrap(cekSecured));
        DecryptResult result = kms.decrypt(kmsreq);
        return new SecretKeySpec(copyAllBytesFrom(result.getPlaintext()),
                contentCryptoScheme.getKeyGeneratorAlgorithm());
    }

    

Returns:
a non-null content crypto material.
            ObjectMetadata metadata,
            EncryptionMaterialsAccessor kekMaterialAccessor,
            Provider securityProvider,
            boolean keyWrapExpected
            AWSKMSClient kms) {
        return fromObjectMetadata0(metadatakekMaterialAccessor,
                securityProvidernullkeyWrapExpectedkms);
    }

    
Factory method to return the content crypto material from the S3 object meta data, using the specified key encrypting key material accessor and an optional security provider.

Returns:
a non-null content crypto material.
            ObjectMetadata metadata,
            EncryptionMaterialsAccessor kekMaterialAccessor,
            Provider securityProvider,
            long[] range,
            ExtraMaterialsDescription extra,
            boolean keyWrapExpected,
            AWSKMSClient kms) {
        return fromObjectMetadata0(metadatakekMaterialAccessor,
                securityProviderrangeextrakeyWrapExpectedkms);
    }

    

Returns:
a non-null content crypto material.
            ObjectMetadata metadata,
            EncryptionMaterialsAccessor kekMaterialAccessor,
            Provider securityProvider,
            long[] range,
            ExtraMaterialsDescription extra,
            boolean keyWrapExpected,
            AWSKMSClient kms) {
        // CEK and IV
        Map<StringStringuserMeta = metadata.getUserMetadata();
        String b64key = userMeta.get(.);
        if (b64key == null) {
            b64key = userMeta.get(.);
            if (b64key == null)
                throw new AmazonClientException(
                        "Content encrypting key not found.");
        }
        byte[] cekWrapped = Base64.decode(b64key);
        byte[] iv = Base64.decode(userMeta.get(.));
        if (cekWrapped == null || iv == null) {
            throw new AmazonClientException(
                    "Content encrypting key or IV not found.");
        }
        // Material description
        String matdescStr = userMeta.get(.);
        final String keyWrapAlgo = userMeta.get(.);
        final boolean isKMS = isKMSKeyWrapped(keyWrapAlgo);
        final Map<StringStringcore = matdescFromJson(matdescStr);
        final Map<StringStringmerged = isKMS || extra == null
                ? core : extra.mergeInto(core);
        final EncryptionMaterials materials;
        if (isKMS) {
            materials = new KMSEncryptionMaterials(
                    core.get(.));
            materials.addDescriptions(core);
        } else {
            materials = kekMaterialAccessor == null
                ? null
                : kekMaterialAccessor.getEncryptionMaterials(merged)
                ;
            if (materials == null) {
                throw new AmazonClientException(
                        "Unable to retrieve the client encryption materials");
            }
        }
        // CEK algorithm
        String cekAlgo = userMeta.get(.);
        boolean isRangeGet = range != null;
        // The content crypto scheme may vary depending on whether
        // it is a range get operation
        ContentCryptoScheme contentCryptoScheme = 
            ContentCryptoScheme.fromCEKAlgo(cekAlgoisRangeGet);
        if (isRangeGet) {
            // Adjust the IV as needed
            iv = contentCryptoScheme.adjustIV(ivrange[0]);
        } else {
            // Validate the tag length supported
            int tagLenExpected = contentCryptoScheme.getTagLengthInBits();
            if (tagLenExpected > 0) {
                String s = userMeta.get(.);
                int tagLenActual = Integer.parseInt(s);
                if (tagLenExpected != tagLenActual) {
                    throw new AmazonClientException("Unsupported tag length: "
                            + tagLenActual + ", expected: " + tagLenExpected);
                }
            }
        }
        // Unwrap or decrypt the CEK
        if (keyWrapExpected && keyWrapAlgo == null)
            throw newKeyWrapException();
        SecretKey cek = cek(cekWrappedkeyWrapAlgomaterials,
                securityProvidercontentCryptoSchemekms);
        return new ContentCryptoMaterial(mergedcekWrappedkeyWrapAlgo,
                contentCryptoScheme.createCipherLite(cekiv,
                        .securityProvider));
    }
    
    private static KeyWrapException newKeyWrapException() {
        return new KeyWrapException(
                "Missing key-wrap for the content-encrypting-key");
    }

    

Returns:
a non-null content crypto material.
            Map<StringStringinstFile,
            EncryptionMaterialsAccessor kekMaterialAccessor,
            Provider securityProvider,
            boolean keyWrapExpected,
            AWSKMSClient kms) {
        return fromInstructionFile0(instFilekekMaterialAccessor,
                securityProvidernullkeyWrapExpectedkms);
    }

    
Factory method to return the content crypto material from the S3 instruction file, using the specified key encrypting key material accessor and an optional security provider.

Returns:
a non-null content crypto material.
            Map<StringStringinstFile,
            EncryptionMaterialsAccessor kekMaterialAccessor,
            Provider securityProvider,
            long[] range,
            ExtraMaterialsDescription extra,
            boolean keyWrapExpected,
            AWSKMSClient kms) {
        return fromInstructionFile0(instFilekekMaterialAccessor,
                securityProviderrangeextrakeyWrapExpectedkms);
    }

    

Returns:
a non-null content crypto material.
            Map<StringStringinstFile,
            EncryptionMaterialsAccessor kekMaterialAccessor,
            Provider securityProvider,
            long[] range,
            ExtraMaterialsDescription extra,
            boolean keyWrapExpected,
            AWSKMSClient kms) {
        // CEK and IV
        String b64key = instFile.get(.);
        if (b64key == null) {
            b64key = instFile.get(.);
            if (b64key == null)
                throw new AmazonClientException(
                        "Content encrypting key not found.");
        }
        byte[] cekWrapped = Base64.decode(b64key);
        byte[] iv = Base64.decode(instFile.get(.));
        if (cekWrapped == null || iv == null) {
            throw new AmazonClientException(
                    "Necessary encryption info not found in the instruction file "
                            + instFile);
        }
        final String keyWrapAlgo = instFile.get(.);
        final boolean isKMS = isKMSKeyWrapped(keyWrapAlgo);
        // Material description
        String matdescStr = instFile.get(.);
        final Map<StringStringcore = matdescFromJson(matdescStr);
        final Map<StringStringmerged = extra == null || isKMS
            ? core : extra.mergeInto(core);
        EncryptionMaterials materials;
        if (isKMS) {
            materials = new KMSEncryptionMaterials(
                    core.get(.));
            materials.addDescriptions(core);
        } else {
            materials = kekMaterialAccessor == null
                ? null
                : kekMaterialAccessor.getEncryptionMaterials(merged);
            if (materials == null) {
                throw new AmazonClientException(
                    "Unable to retrieve the encryption materials that originally "
                            + "encrypted object corresponding to instruction file "
                            + instFile);
            }
        }
        // CEK algorithm
        final String cekAlgo = instFile.get(.);
        final boolean isRangeGet = range != null;
        // The content crypto scheme may vary depending on whether
        // it is a range get operation
        ContentCryptoScheme contentCryptoScheme = ContentCryptoScheme
                .fromCEKAlgo(cekAlgoisRangeGet);
        if (isRangeGet) {
            // Adjust the IV as needed
            iv = contentCryptoScheme.adjustIV(ivrange[0]);
        } else {
            // Validate the tag length supported
            int tagLenExpected = contentCryptoScheme.getTagLengthInBits();
            if (tagLenExpected > 0) {
                String s = instFile.get(.);
                int tagLenActual = Integer.parseInt(s);
                if (tagLenExpected != tagLenActual) {
                    throw new AmazonClientException("Unsupported tag length: "
                            + tagLenActual + ", expected: " + tagLenExpected);
                }
            }
        }
        // Unwrap or decrypt the CEK
        if (keyWrapExpected && keyWrapAlgo == null)
            throw newKeyWrapException();
        SecretKey cek = cek(cekWrappedkeyWrapAlgomaterials,
                securityProvidercontentCryptoSchemekms);
        return new ContentCryptoMaterial(mergedcekWrappedkeyWrapAlgo,
                contentCryptoScheme.createCipherLite(cekiv,
                        .securityProvider));
    }

    
Parses instruction data retrieved from S3 and returns a JSON string representing the instruction. Made for testing purposes.
    static String parseInstructionFile(S3Object instructionFile) {
        try {
            return convertStreamToString(instructionFile.getObjectContent());
        } catch (Exception e) {
            throw failure(e"Error parsing JSON instruction file");
        }
    }

    
Converts the contents of an input stream to a String
    private static String convertStreamToString(InputStream inputStream)
            throws IOException {
        if (inputStream == null) {
            return "";
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            try {
                BufferedReader reader =
                    new BufferedReader(new InputStreamReader(inputStream));
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } finally {
                inputStream.close();
            }
            return stringBuilder.toString();
        }
    }

    
Return the cipher lite used for content encryption/decryption purposes.
        return ;
    }

    
Returns the description of the kek materials that were used to encrypt the cek.
        return this.;
    }

    
Returns an array of bytes representing the encrypted envelope symmetric key.

Returns:
an array of bytes representing the encrypted envelope symmetric key.
    byte[] getEncryptedCEK() {
        return this..clone();
    }

    
Recreates a new content crypto material from the current material given a new KEK material-descriptions. The purpose is to re-encrypt the CEK under a different KEK. Note network calls are involved if the CEK has been or is to be protected by KMS.

Parameters:
newKEKMatDesc material descriptions for the new KEK; never null
accessor used to retrieve the KEK given the corresponding material description
targetScheme the target crypto scheme to be used for key wrapping, etc.
p optional security provider; null means to use the default.
Throws:
java.lang.SecurityException if the old and new material description are the same; or if the old and new KEK are the same
    ContentCryptoMaterial recreate(Map<StringStringnewKEKMatDesc,
            EncryptionMaterialsAccessor accessorS3CryptoScheme targetScheme,
            Provider pAWSKMSClient kmsAmazonWebServiceRequest req) {
        if (!usesKMSKey() && newKEKMatDesc.equals()) {
            throw new SecurityException(
                "Material description of the new KEK must differ from the current one");
        }
        final EncryptionMaterials origKEK;
        if (usesKMSKey()) {
            origKEK = new KMSEncryptionMaterials(.get(
                .));
        } else {
            origKEK = accessor.getEncryptionMaterials();
        }
        EncryptionMaterials newKEK = accessor.getEncryptionMaterials(newKEKMatDesc);
        if (newKEK == null) {
            throw new AmazonClientException(
                "No material available with the description "
                    + newKEKMatDesc
                    + " from the encryption material provider");
        }
        SecretKey cek = cek(origKEKp,
                getContentCryptoScheme(), kms);
        ContentCryptoMaterial output = create(cek.getIV(), newKEK,
                getContentCryptoScheme(),  // must use same content crypto scheme
                targetScheme,
                pkmsreq);
        if (Arrays.equals(output.encryptedCEK)) {
            throw new SecurityException(
                "The new KEK must differ from the original");
        }
        return output;
    }

    
Recreates a new content crypto material from the current material given a new KEK encryption materials. The purpose is to re-encrypt the CEK under the new KEK. Note network calls are involved if the CEK has been or is to be protected by KMS.

Parameters:
newKEK encryption materials for the new KEK; must not be null
accessor used to retrieve the original KEK given the corresponding material description
targetScheme the target crypto scheme to use for recreating the content crypto material
p optional security provider; null means to use the default.
Throws:
java.lang.SecurityException if the old and new material description are the same; or if the old and new KEK are the same
            EncryptionMaterialsAccessor accessorS3CryptoScheme targetScheme,
            Provider pAWSKMSClient kmsAmazonWebServiceRequest req) {
        if (!usesKMSKey()
        &&  newKEK.getMaterialsDescription().equals()) {
            throw new SecurityException(
                "Material description of the new KEK must differ from the current one");
        }
        final EncryptionMaterials origKEK;
        if (usesKMSKey()) {
            origKEK = new KMSEncryptionMaterials(.get(
                .));
        } else {
            origKEK = accessor.getEncryptionMaterials();
        }
        SecretKey cek = cek(origKEKp,
                getContentCryptoScheme(), kms);
        ContentCryptoMaterial output =
            create(cek.getIV(), newKEK,
                   getContentCryptoScheme(),  // must use same content crypto scheme
                   targetScheme// target scheme used to recreate the content crypto material
                   pkmsreq);
        if (Arrays.equals(output.encryptedCEK)) {
            throw new SecurityException(
                "The new KEK must differ from the original");
        }
        return output;
    }

    
Returns a new instance of ContentCryptoMaterial for the input parameters using the specified content crypto scheme, and the key wrapping and secure randomness specified of the specified s3 crypto scheme. Note network calls are involved if the CEK is to be protected by KMS.

Parameters:
cek content encrypting key; must not be null.
iv initialization vector; must not be null.
contentCryptoScheme content crypto scheme to be used
targetScheme the target s3 crypto scheme to be used for recreating the content crypto material by providing the key wrapping scheme and mechanism for secure randomness
provider optional security provider
    static ContentCryptoMaterial create(SecretKey cekbyte[] iv,
            EncryptionMaterials kekMaterials,
            ContentCryptoScheme contentCryptoScheme,
            S3CryptoScheme targetScheme,
            Provider providerAWSKMSClient kms,
            AmazonWebServiceRequest req) {
        return doCreate(cekivkekMaterialscontentCryptoScheme,
                targetSchemeproviderkmsreq);
    }

    
Returns a new instance of ContentCryptoMaterial for the input parameters using the specified s3 crypto scheme. Note network calls are involved if the CEK is to be protected by KMS.

Parameters:
cek content encrypting key
iv initialization vector
kekMaterials kek encryption material used to secure the CEK; can be KMS enabled.
scheme s3 crypto scheme to be used for the content crypto material by providing the content crypto scheme, key wrapping scheme and mechanism for secure randomness
provider optional security provider
kms reference to the KMS client
req originating service request
    static ContentCryptoMaterial create(SecretKey cekbyte[] iv,
            EncryptionMaterials kekMaterials,
            S3CryptoScheme scheme,
            Provider providerAWSKMSClient kms,
            AmazonWebServiceRequest req) {
        return doCreate(cekivkekMaterialsscheme.getContentCryptoScheme(),
                schemeproviderkmsreq);
    }

    
Returns a new instance of ContentCryptoMaterial for the given input parameters by using the specified content crypto scheme, and S3 crypto scheme. Note network calls are involved if the CEK is to be protected by KMS.

Parameters:
cek content encrypting key
iv initialization vector
kekMaterials kek encryption material used to secure the CEK; can be KMS enabled.
contentCryptoScheme content crypto scheme to be used, which can differ from the one of targetS3CryptoScheme
targetS3CryptoScheme the target s3 crypto scheme to be used for providing the key wrapping scheme and mechanism for secure randomness
provider security provider
kms reference to the KMS client
req the originating AWS service request
    private static ContentCryptoMaterial doCreate(SecretKey cekbyte[] iv,
            EncryptionMaterials kekMaterials,
            ContentCryptoScheme contentCryptoScheme,
            S3CryptoScheme targetS3CryptoScheme,
            Provider provider
            AWSKMSClient kms,
            AmazonWebServiceRequest req) {
        // Secure the envelope symmetric key either by encryption, key wrapping
        // or KMS.
        SecuredCEK cekSecured = secureCEK(cekkekMaterials,
                targetS3CryptoScheme.getKeyWrapScheme(),
                targetS3CryptoScheme.getSecureRandom(),
                providerkmsreq);
        // Return a new instruction with the appropriate fields.
        return wrap(cekivkekMaterials,
                contentCryptoSchemeprovidercekSecured);
    }

    
Returns a new instance of ContentCryptoMaterial by wrapping the input parameters, including the already secured CEK. No network calls are involved.
    public static ContentCryptoMaterial wrap(
            SecretKey cekbyte[] iv
            EncryptionMaterials kekMaterials,
            ContentCryptoScheme contentCryptoScheme,
            Provider provider,
            SecuredCEK cekSecured) {
        return new ContentCryptoMaterial(
                kekMaterials.getMaterialsDescription(),
                cekSecured.getEncrypted(),
                cekSecured.getKeyWrapAlgorithm(),
                contentCryptoScheme.createCipherLite
                    (cekiv.provider));
    }

    
Secure the given CEK. Note network calls are involved if the CEK is to be protected by KMS.

Parameters:
cek content encrypting key to be secured
materials used to provide the key-encryption-key (KEK); or if it is KMS-enabled, the customer master key id and material description.
contentCryptoScheme the content crypto scheme
p optional security provider; can be null if the default is used.
Returns:
a secured CEK in the form of ciphertext or ciphertext blob.
    private static SecuredCEK secureCEK(SecretKey cek,
            EncryptionMaterials materialsS3KeyWrapScheme kwScheme,
            SecureRandom srandProvider pAWSKMSClient kms,
            AmazonWebServiceRequest req) {
        if (materials.isKMSEnabled()) {
            EncryptRequest encryptRequest = new EncryptRequest()
                .withEncryptionContext(materials.getMaterialsDescription())
                .withKeyId(materials.getCustomerMasterKeyId())
                .withPlaintext(ByteBuffer.wrap(cek.getEncoded()))
                ;
            encryptRequest
                .withGeneralProgressListener(req.getGeneralProgressListener())
                .withRequestMetricCollector(req.getRequestMetricCollector())
                ;
            EncryptResult encryptResult = kms.encrypt(encryptRequest);
            byte[] keyBlob = copyAllBytesFrom(encryptResult.getCiphertextBlob());
            return new KMSSecuredCEK(keyBlob);
        }
        Key kek;
        if (materials.getKeyPair() != null) {
            // Do envelope encryption with public key from key pair
            kek = materials.getKeyPair().getPublic();
        } else {
            // Do envelope encryption with symmetric key
            kek = materials.getSymmetricKey();
        }
        String keyWrapAlgo = kwScheme.getKeyWrapAlgorithm(kek);
        try {
            if (keyWrapAlgo != null) {
                Cipher cipher = p == null ? Cipher
                        .getInstance(keyWrapAlgo) : Cipher.getInstance(
                        keyWrapAlgop);
                cipher.init(.keksrand);
                return new SecuredCEK(cipher.wrap(cek), keyWrapAlgo);
            }
            // fall back to the Encryption Only (EO) key encrypting method
            Cipher cipher;
            byte[] toBeEncryptedBytes = cek.getEncoded();
            String algo = kek.getAlgorithm();
            if (p != null) {
                cipher = Cipher.getInstance(algop);
            } else {
                cipher = Cipher.getInstance(algo); // Use default JCE Provider
            }
            cipher.init(.kek);
            return new SecuredCEK(cipher.doFinal(toBeEncryptedBytes), null);
        } catch (Exception e) {
            throw failure(e"Unable to encrypt symmetric key");
        }
    }
New to GrepCode? Check out our FAQ X