private static SecuredCEK secureCEK ( SecretKey cek , EncryptionMaterials materials , S3KeyWrapScheme kwScheme , SecureRandom srand , Provider p , AWSKMS kms , AmazonWebServiceRequest req ) { final Map < String , String > matdesc ; if ( materials . isKMSEnabled ( ) ) { matdesc = mergeMaterialDescriptions ( materials , req ) ; EncryptRequest encryptRequest = new EncryptRequest ( ) . withEncryptionContext ( matdesc ) . 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 , matdesc ) ; } else { matdesc = materials . getMaterialsDescription ( ) ; } 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 ( keyWrapAlgo , p ) ; cipher . init ( Cipher . WRAP_MODE , kek , srand ) ; return new SecuredCEK ( cipher . wrap ( cek ) , keyWrapAlgo , matdesc ) ; } // 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 ( algo , p ) ; } else { cipher = Cipher . getInstance ( algo ) ; // Use default JCE Provider } cipher . init ( Cipher . ENCRYPT_MODE , kek ) ; return new SecuredCEK ( cipher . doFinal ( toBeEncryptedBytes ) , null , matdesc ) ; } catch ( Exception e ) { throw failure ( e , "Unable to encrypt symmetric key" ) ; } }
Secure the given CEK . Note network calls are involved if the CEK is to be protected by KMS .