/**
 * Copyright © 2017 Michael Lasmanis (michael@lasmanis.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.lasmanis.maven.pgp.loaders.helpers;

import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.util.Base64;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import org.apache.maven.plugin.MojoExecutionException;

/**
 * Wrapper around AWS Crypto library
 * @author mpl
 */
public class AwsCryptoHelper 
        implements CryptoHelper
{
    @Override
    public String decrypt(final String cipherText) 
            throws MojoExecutionException
    {
        // check
        if (cipherText == null || cipherText.isEmpty())
        {
            throw new MojoExecutionException("Empty cipherText.");            

        }

        // parse the cipher text
        final byte[] ciphertextBytes;
        try
        {
            ciphertextBytes = Base64.decode(cipherText);
        } 
        catch (final IllegalArgumentException ex) 
        {
            throw new MojoExecutionException("Invalid base 64 in cipherText", ex);
        }

        // decrypt
        AWSKMS kms = AWSKMSClientBuilder.defaultClient();
        DecryptRequest req = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(ciphertextBytes));
        ByteBuffer plainText = kms.decrypt(req).getPlaintext();
        String ret = new String(plainText.array(),Charset.defaultCharset());

        return ret;
    }
}

@@ -907,23 +907,32 @@
 charset.
+Standard
 Charset
+s
 ;%0Aimport
@@ -1728,16 +1728,42 @@
 decrypt%0A
+        try%0A        %7B%0A    
         
@@ -1820,16 +1820,20 @@
         
+ 
+   
 DecryptR
@@ -1920,16 +1920,20 @@
 ytes));%0A
+    
         
@@ -1996,16 +1996,20 @@
         
+    
 String r
@@ -2046,55 +2046,205 @@
 y(),
-Charset.defaultCharset());%0A%0A        return ret;
+ StandardCharsets.UTF_8);%0A%0A            return ret;%0A        %7D%0A        catch (final Exception ex)%0A        %7B%0A            throw new MojoExecutionException(%22Failed to decrypt cipherText%22, ex);%0A        %7D
 %0A   

handle decryption errors