Example usage for com.amazonaws.util Base64 decode

List of usage examples for com.amazonaws.util Base64 decode

Introduction

In this page you can find the example usage for com.amazonaws.util Base64 decode.

Prototype

public static byte[] decode(byte[] b64) 

Source Link

Document

Decodes the given base 64 encoded bytes.

Usage

From source file:com.amazon.sqs.javamessaging.message.SQSBytesMessage.java

License:Open Source License

/**
 * Convert received SQSMessage into BytesMessage.
 *///w w w .j a v  a  2s .  c o m
public SQSBytesMessage(Acknowledger acknowledger, String queueUrl, Message sqsMessage) throws JMSException {
    super(acknowledger, queueUrl, sqsMessage);
    try {
        /** Bytes is set by the reset() */
        dataOut.write(Base64.decode(sqsMessage.getBody()));
        /** Makes it read-only */
        reset();
    } catch (IOException e) {
        LOG.error("IOException: Message cannot be written", e);
        throw convertExceptionToJMSException(e);
    } catch (Exception e) {
        LOG.error("Unexpected exception: ", e);
        throw convertExceptionToJMSException(e);
    }
}

From source file:com.amazon.sqs.javamessaging.message.SQSObjectMessage.java

License:Open Source License

/**
 * Deserialize the <code>String</code> into <code>Serializable</code>
 * object.//from  w ww.ja va2 s. co  m
 */
protected static Serializable deserialize(String serialized) throws JMSException {
    if (serialized == null) {
        return null;
    }
    Serializable deserializedObject;
    ObjectInputStream objectInputStream = null;
    try {
        byte[] bytes = Base64.decode(serialized);
        objectInputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        deserializedObject = (Serializable) objectInputStream.readObject();
    } catch (IOException e) {
        LOG.error("IOException: Message cannot be written", e);
        throw convertExceptionToMessageFormatException(e);
    } catch (Exception e) {
        LOG.error("Unexpected exception: ", e);
        throw convertExceptionToMessageFormatException(e);
    } finally {
        if (objectInputStream != null) {
            try {
                objectInputStream.close();
            } catch (IOException e) {
                LOG.warn(e.getMessage());
            }
        }
    }
    return deserializedObject;
}

From source file:com.lasmanis.maven.pgp.loaders.helpers.AwsCryptoHelper.java

License:Apache License

/** {@inheritDoc} */
@Override/*ww  w  .  j a va  2 s .  c o  m*/
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
    try {
        DecryptRequest req = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(ciphertextBytes));
        ByteBuffer plainText = this.client.decrypt(req).getPlaintext();
        String ret = new String(plainText.array(), StandardCharsets.UTF_8);

        return ret;
    } catch (final Exception ex) {
        throw new MojoExecutionException("Failed to decrypt cipherText", ex);
    }
}

From source file:com.nextdoor.bender.utils.Passwords.java

License:Apache License

public static String decrypt(String str, Region region) throws UnsupportedEncodingException {
    if (isJUnitTest()) {
        return str;
    }/*from w  w  w  .j  a v a 2  s . c  om*/

    AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region.getName()).build();

    /*
     * The KMS ciphertext is base64 encoded and must be decoded before the request is made
     */
    String cipherString = str;
    byte[] cipherBytes = Base64.decode(cipherString);

    /*
     * Create decode request and decode
     */
    ByteBuffer cipherBuffer = ByteBuffer.wrap(cipherBytes);
    DecryptRequest req = new DecryptRequest().withCiphertextBlob(cipherBuffer);
    DecryptResult resp = kms.decrypt(req);

    /*
     * Convert the response plaintext bytes to a string
     */
    return new String(resp.getPlaintext().array(), Charset.forName("UTF-8"));
}

From source file:io.fineo.client.auth.cognito.CognitoUser.java

License:Open Source License

/**
 * Creates response for the second step of the SRP authentication.
 *
 * @param challenge                     REQUIRED: {@link InitiateAuthResult} contains next challenge.
 * @param authenticationDetails         REQUIRED: {@link AuthenticationDetails} user authentication details.
 * @param authenticationHelper          REQUIRED: Internal helper class for SRP calculations.
 * @return {@link RespondToAuthChallengeRequest}.
 *//*w  ww . ja v  a  2s  .  c o  m*/
private RespondToAuthChallengeRequest userSrpAuthRequest(InitiateAuthResult challenge,
        AuthenticationDetails authenticationDetails, AuthenticationHelper authenticationHelper) {
    this.usernameInternal = challenge.getChallengeParameters().get("USERNAME");
    this.deviceKey = devices.getDeviceKey(usernameInternal, getUserPoolId());
    secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret);

    BigInteger B = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16);
    if (B.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) {
        throw new CognitoInternalErrorException("SRP error, B cannot be zero");
    }

    BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    byte[] key = authenticationHelper.getPasswordAuthenticationKey(usernameInternal,
            authenticationDetails.getPassword(), B, salt);

    Date timestamp = new Date();
    byte[] hmac;
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(pool.getUserPoolId().split("_", 2)[1].getBytes(StringUtils.UTF8));
        mac.update(usernameInternal.getBytes(StringUtils.UTF8));
        byte[] secretBlock = Base64.decode(challenge.getChallengeParameters().get("SECRET_BLOCK"));
        mac.update(secretBlock);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        simpleDateFormat.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));
        String dateString = simpleDateFormat.format(timestamp);
        byte[] dateBytes = dateString.getBytes(StringUtils.UTF8);
        hmac = mac.doFinal(dateBytes);
    } catch (Exception e) {
        throw new CognitoInternalErrorException("SRP error", e);
    }

    SimpleDateFormat formatTimestamp = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
    formatTimestamp.setTimeZone(new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC"));

    Map<String, String> srpAuthResponses = new HashMap<String, String>();
    srpAuthResponses.put("PASSWORD_CLAIM_SECRET_BLOCK", challenge.getChallengeParameters().get("SECRET_BLOCK"));
    srpAuthResponses.put("PASSWORD_CLAIM_SIGNATURE", new String(Base64.encode(hmac), StandardCharsets.UTF_8));
    srpAuthResponses.put("TIMESTAMP", formatTimestamp.format(timestamp));
    srpAuthResponses.put("USERNAME", usernameInternal);
    srpAuthResponses.put("USER_ID_FOR_SRP", usernameInternal);
    srpAuthResponses.put("DEVICE_KEY", deviceKey);
    srpAuthResponses.put("SECRET_HASH", secretHash);

    RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest();
    authChallengeRequest.setChallengeName(challenge.getChallengeName());
    authChallengeRequest.setClientId(clientId);
    authChallengeRequest.setSession(challenge.getSession());
    authChallengeRequest.setChallengeResponses(srpAuthResponses);

    return authChallengeRequest;
}

From source file:org.apache.beam.sdk.io.aws.s3.S3TestUtils.java

License:Apache License

@Nullable
static String getSSECustomerKeyMd5(S3Options options) {
    SSECustomerKey sseCostumerKey = options.getSSECustomerKey();
    if (sseCostumerKey != null) {
        return Base64.encodeAsString(DigestUtils.md5(Base64.decode(sseCostumerKey.getKey())));
    }/*from  w w  w  . j  a  v a 2s .com*/
    return null;
}

From source file:org.apache.nifi.processors.aws.lambda.PutLambda.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {

    FlowFile flowFile = session.get();//from   w  w w  .j a va 2s .c  om
    if (flowFile == null) {
        return;
    }

    final String functionName = context.getProperty(AWS_LAMBDA_FUNCTION_NAME).getValue();

    final String qualifier = context.getProperty(AWS_LAMBDA_FUNCTION_QUALIFIER).getValue();

    // Max size of message is 6 MB
    if (flowFile.getSize() > MAX_REQUEST_SIZE) {
        getLogger().error("Max size for request body is 6mb but was {} for flow file {} for function {}",
                new Object[] { flowFile.getSize(), flowFile, functionName });
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    final AWSLambdaClient client = getClient();

    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        session.exportTo(flowFile, baos);

        InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(functionName)
                .withLogType(LogType.Tail).withInvocationType(InvocationType.RequestResponse)
                .withPayload(ByteBuffer.wrap(baos.toByteArray())).withQualifier(qualifier);
        long startTime = System.nanoTime();

        InvokeResult result = client.invoke(invokeRequest);

        flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_STATUS_CODE,
                result.getStatusCode().toString());

        if (!StringUtils.isBlank(result.getLogResult())) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_LOG,
                    new String(Base64.decode(result.getLogResult()), Charset.defaultCharset()));
        }

        if (result.getPayload() != null) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_PAYLOAD,
                    new String(result.getPayload().array(), Charset.defaultCharset()));
        }

        if (!StringUtils.isBlank(result.getFunctionError())) {
            flowFile = session.putAttribute(flowFile, AWS_LAMBDA_RESULT_FUNCTION_ERROR,
                    result.getFunctionError());
            session.transfer(flowFile, REL_FAILURE);
        } else {
            session.transfer(flowFile, REL_SUCCESS);
            final long totalTimeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            session.getProvenanceReporter().send(flowFile, functionName, totalTimeMillis);
        }
    } catch (final InvalidRequestContentException | InvalidParameterValueException | RequestTooLargeException
            | ResourceNotFoundException | UnsupportedMediaTypeException unrecoverableException) {
        getLogger().error("Failed to invoke lambda {} with unrecoverable exception {} for flow file {}",
                new Object[] { functionName, unrecoverableException, flowFile });
        flowFile = populateExceptionAttributes(session, flowFile, unrecoverableException);
        session.transfer(flowFile, REL_FAILURE);
    } catch (final TooManyRequestsException retryableServiceException) {
        getLogger().error(
                "Failed to invoke lambda {} with exception {} for flow file {}, therefore penalizing flowfile",
                new Object[] { functionName, retryableServiceException, flowFile });
        flowFile = populateExceptionAttributes(session, flowFile, retryableServiceException);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    } catch (final AmazonServiceException unrecoverableServiceException) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {} sending to fail",
                new Object[] { functionName, unrecoverableServiceException, flowFile });
        flowFile = populateExceptionAttributes(session, flowFile, unrecoverableServiceException);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    } catch (final Exception exception) {
        getLogger().error("Failed to invoke lambda {} with exception {} for flow file {}",
                new Object[] { functionName, exception, flowFile });
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}

From source file:org.iternine.jeppetto.dao.dynamodb.iterable.DynamoDBIterable.java

License:Apache License

public void setPosition(String position, String hashKeyValue) {
    if (dynamoDBIterator != null) {
        throw new JeppettoException("setPosition() only valid on a new DynamoDBIterable.");
    }//from w  ww.j  a v  a  2 s.c o m

    if (position == null) {
        return;
    }

    try {
        byte[] decodedBytes = Base64.decode(URLDecoder.decode(position, StandardCharsets.UTF_8.name()));
        String[] attributePairs = new String(decodedBytes).split("&");

        if (attributePairs.length == 0) {
            return;
        }

        Map<String, AttributeValue> exclusiveStartKey = new HashMap<String, AttributeValue>();

        for (String attributePair : attributePairs) {
            String[] parts = attributePair.split("=");

            if (parts.length != 2) {
                throw new JeppettoException(
                        "Corrupted position: " + position + "; found attribute: " + attributePair);
            }

            exclusiveStartKey.put(parts[0], decode(parts[1]));
        }

        if (hashKeyValue != null) {
            // TODO: support types other than just 'S'
            exclusiveStartKey.put(getHashKeyField(), new AttributeValue(hashKeyValue));
        }

        setExclusiveStartKey(exclusiveStartKey);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e); // Unexpected since UTF-8 is the system standard.
    }
}

From source file:org.zalando.crypto.aws.kms.KmsDecrypter.java

License:Apache License

@Override
public String decrypt(String encryptedText) {
    if (isNullOrEmpty(encryptedText)) {
        return EMPTY_STRING;
    } else {// w w w.  java2  s.  c  o m

        // Assuming the encryptedText is encoded in Base64
        final ByteBuffer encryptedBytes = ByteBuffer.wrap(Base64.decode(encryptedText.getBytes()));

        final DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(encryptedBytes);

        return extractString(decryptByKms(decryptRequest).getPlaintext());
    }
}

From source file:org.zalando.stups.fullstop.plugin.RegistryPlugin.java

License:Apache License

private Map getUserData(final CloudTrailEvent event, final String instanceId) {

    AmazonEC2Client ec2Client = cachingClientProvider.getClient(AmazonEC2Client.class,
            event.getEventData().getUserIdentity().getAccountId(),
            Region.getRegion(Regions.fromName(event.getEventData().getAwsRegion())));

    DescribeInstanceAttributeRequest describeInstanceAttributeRequest = new DescribeInstanceAttributeRequest();
    describeInstanceAttributeRequest.setInstanceId(instanceId);
    describeInstanceAttributeRequest.setAttribute(USER_DATA);

    DescribeInstanceAttributeResult describeInstanceAttributeResult;
    try {//from  w  ww  .j  ava  2s  .c om
        describeInstanceAttributeResult = ec2Client.describeInstanceAttribute(describeInstanceAttributeRequest);
    } catch (AmazonServiceException e) {
        LOG.error(e.getMessage());
        violationStore
                .save(new ViolationBuilder(format("InstanceId: %s doesn't have any userData.", instanceId))
                        .withEvent(event).build());
        return null;
    }

    String userData = describeInstanceAttributeResult.getInstanceAttribute().getUserData();

    if (userData == null) {
        violationStore
                .save(new ViolationBuilder(format("InstanceId: %s doesn't have any userData.", instanceId))
                        .withEvent(event).build());
        return null;
    }

    byte[] bytesUserData = Base64.decode(userData);
    String decodedUserData = new String(bytesUserData);

    Yaml yaml = new Yaml();

    return (Map) yaml.load(decodedUserData);
}