Example usage for com.amazonaws.util Base64 encode

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

Introduction

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

Prototype

public static byte[] encode(byte[] bytes) 

Source Link

Document

Returns a 64 encoded byte array of the given bytes.

Usage

From source file:EC2.java

License:Apache License

public List<String> launch(String workerAMI, String instanceType, int num, double price,
        List<String> securityGroups, String keyName, String userData, String charset)
        throws UnsupportedEncodingException {
    RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
    requestRequest.setSpotPrice(Double.toString(price));
    requestRequest.setInstanceCount(Integer.valueOf(num));

    LaunchSpecification launchSpecification = new LaunchSpecification();
    launchSpecification.setImageId(workerAMI);
    launchSpecification.setInstanceType(instanceType);
    launchSpecification.setSecurityGroups(securityGroups);
    launchSpecification.setUserData(new String(Base64.encode(userData.getBytes(charset))));
    launchSpecification.setKeyName(keyName); //for test

    requestRequest.setLaunchSpecification(launchSpecification);
    RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(requestRequest);
    List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

    List<String> spotInstanceRequestIds = new ArrayList<String>();

    for (SpotInstanceRequest requestResponse : requestResponses) {
        System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
        spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
    }//w  w  w.  j ava  2s  . c  o  m
    return spotInstanceRequestIds;
}

From source file:alluxio.underfs.s3a.S3AOutputStream.java

License:Apache License

@Override
public void close() throws IOException {
    if (mClosed) {
        return;/*from ww w.  j a v  a 2 s.  com*/
    }
    mLocalOutputStream.close();
    try {
        // Generate the object metadata by setting server side encryption, md5 checksum, the file
        // length, and encoding as octet stream since no assumptions are made about the file type
        ObjectMetadata meta = new ObjectMetadata();
        if (SSE_ENABLED) {
            meta.setSSEAlgorithm(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
        }
        if (mHash != null) {
            meta.setContentMD5(new String(Base64.encode(mHash.digest())));
        }
        meta.setContentLength(mFile.length());
        meta.setContentEncoding(Mimetypes.MIMETYPE_OCTET_STREAM);

        // Generate the put request and wait for the transfer manager to complete the upload, then
        // delete the temporary file on the local machine
        PutObjectRequest putReq = new PutObjectRequest(mBucketName, mKey, mFile).withMetadata(meta);
        mManager.upload(putReq).waitForUploadResult();
        if (!mFile.delete()) {
            LOG.error("Failed to delete temporary file @ {}", mFile.getPath());
        }
    } catch (Exception e) {
        LOG.error("Failed to upload {}. Temporary file @ {}", mKey, mFile.getPath());
        throw new IOException(e);
    }

    // Set the closed flag, close can be retried until mFile.delete is called successfully
    mClosed = true;
}

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

License:Open Source License

/**
 * Generates secret hash. Uses HMAC SHA256.
 *
 * @param userId            REQUIRED: User ID
 * @param clientId          REQUIRED: Client ID
 * @param clientSecret      REQUIRED: Client secret
 * @return  secret hash as a {@code String}, {@code null } if {@code clinetSecret if null}
 */// www  .j  a v  a  2  s  .co  m
public static String getSecretHash(String userId, String clientId, String clientSecret) {
    // Arguments userId and clientId have to be not-null.
    if (userId == null) {
        throw new RuntimeException("user ID cannot be null");
    }

    if (clientId == null) {
        throw new RuntimeException("client ID cannot be null");
    }

    // Return null as secret hash if clientSecret is null.
    if (clientSecret == null) {
        return null;
    }

    SecretKeySpec signingKey = new SecretKeySpec(clientSecret.getBytes(StringUtils.UTF8), HMAC_SHA_256);

    try {
        Mac mac = Mac.getInstance(HMAC_SHA_256);
        mac.init(signingKey);
        mac.update(userId.getBytes(StringUtils.UTF8));
        byte[] rawHmac = mac.doFinal(clientId.getBytes(StringUtils.UTF8));
        return new String(Base64.encode(rawHmac));
    } catch (Exception e) {
        throw new RuntimeException("errors in HMAC calculation");
    }
}

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  . j  a v  a2 s .  c  om
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.alfresco.provision.AWSService.java

License:Open Source License

private String getUserData(String[] lines) {
    String str = new String(Base64.encode(join(lines, "\n").getBytes()));
    return str;
}

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

License:Apache License

@Override
public String encrypt(String text) {
    if (isNullOrEmpty(text)) {

        return EMPTY_STRING;
    } else {//from w w  w.ja v a2 s.  com
        final EncryptRequest encryptRequest = new EncryptRequest().withKeyId(kmsKeyId) //
                .withPlaintext(ByteBuffer.wrap(text.getBytes()));

        final ByteBuffer encryptedBytes = kms.encrypt(encryptRequest).getCiphertextBlob();

        return extractString(ByteBuffer.wrap(Base64.encode(encryptedBytes.array())));
    }
}