Java Code Examples for com.amazonaws.util.Base64#decode()

The following examples show how to use com.amazonaws.util.Base64#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CompressUtil.java    From s3-bucket-loader with Apache License 2.0 6 votes vote down vote up
public static char[] decompressAndB64DecodeUTF8Bytes(byte[] b64EncodedCompressedBytes) throws Exception {

		byte[] input = Base64.decode(b64EncodedCompressedBytes);
		
		// Compressor with highest level of compression
	    Inflater inflater = new Inflater();
	    
	    // Give the compressor the data to compress
	    inflater.setInput(input);
	    
	    ByteArrayOutputStream stream = new ByteArrayOutputStream();
	    byte[] buf = new byte[32];
	    while (!inflater.finished()) {
	        int count = inflater.inflate(buf);
	        stream.write(buf, 0, count);
	    }
	    return new String(stream.toByteArray(),"UTF-8").toCharArray();
	}
 
Example 2
Source File: Passwords.java    From bender with Apache License 2.0 6 votes vote down vote up
public static String decrypt(String str, Region region) throws UnsupportedEncodingException {
  if (isJUnitTest()) {
    return str;
  }

  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"));
}
 
Example 3
Source File: StorageObjectSummary.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
private static String convertBase64ToHex(String base64String)
{
  try
  {
    byte[] bytes = Base64.decode(base64String);

    final StringBuilder builder = new StringBuilder();
    for (byte b : bytes)
    {
      builder.append(String.format("%02x", b));
    }
    return builder.toString();
    // return empty string if input is not a valid Base64 string
  }
  catch (Exception e)
  {
    return "";
  }
}
 
Example 4
Source File: DynamoDBUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static byte[] decodeSortableBase64(final byte[] original) {
  final byte[] bytes = new byte[original.length];
  for (int i = 0; i < bytes.length; i++) {
    bytes[i] = sortableToDefault[original[i]];
  }
  return Base64.decode(bytes);
}
 
Example 5
Source File: AvatarServiceImpl.java    From konker-platform with Apache License 2.0 5 votes vote down vote up
@Override
   public ServiceResponse<User> updateAvatar(User user) {

   	User fromStorage = userRepository.findOne(user.getEmail());

       if(!StringUtils.isEmpty(user.getAvatar())
               && user.getAvatar().contains("data:image")) {

       	String base64File = user.getAvatar();

   		String fileExt = base64File.split(",")[0].split("/")[1].split(";")[0];
   		String base64Content = base64File.split(",")[1];
   		
   		InputStream is = new ByteArrayInputStream(Base64.decode(base64Content.getBytes()));

   		ServiceResponse<InputStream> resizeResponse =  cropAndResizeAvatar(is, fileExt);
   		if (!resizeResponse.isOk()) {
               return ServiceResponseBuilder.<User>error()
                       .withMessages(resizeResponse.getResponseMessages())
                       .build();
   		}
   		
   		is = resizeResponse.getResult();
   		
           ServiceResponse<String> response = uploadService.upload(is, getUniqueFileName(), fileExt, true);
           if(!response.getStatus().equals(ServiceResponse.Status.OK)){
               return ServiceResponseBuilder.<User>error()
                       .withMessages(response.getResponseMessages())
                       .build();
           }
           user.setAvatar(response.getResult());
       } else {
           user.setAvatar(fromStorage.getAvatar());
       }

       return ServiceResponseBuilder.<User>ok()
               .withResult(user)
               .build();

}
 
Example 6
Source File: AttributeValueMarshallerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testVersioningCompatibility() {
    AttributeValue newObject = buildComplexAttributeValue();
    byte[] oldBytes = Base64.decode(COMPLEX_ATTRIBUTE_MARSHALLED);
    byte[] newBytes = marshall(newObject).array();
    AssertJUnit.assertArrayEquals(oldBytes, newBytes);

    AttributeValue oldObject = unmarshall(ByteBuffer.wrap(oldBytes));
    assertEquals(oldObject, newObject);
}
 
Example 7
Source File: SQSSpanProcessor.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
private void process(final List<Message> messages) {
  if (messages.size() == 0) return;

  final List<DeleteMessageBatchRequestEntry> toDelete = new ArrayList<>();
  int count = 0;
  for (Message message : messages) {
    final String deleteId = String.valueOf(count++);
    try {
      String stringBody = message.getBody();
      if (stringBody.isEmpty() || stringBody.equals("[]")) continue;
      // allow plain-text json, but permit base64 encoded thrift or json
      byte[] serialized =
          stringBody.charAt(0) == '[' ? stringBody.getBytes(UTF_8) : Base64.decode(stringBody);
      metrics.incrementMessages();
      metrics.incrementBytes(serialized.length);
      collector.acceptSpans(
          serialized,
          new Callback<Void>() {
            @Override
            public void onSuccess(Void value) {
              toDelete.add(
                  new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
            }

            @Override
            public void onError(Throwable t) {
              logger.log(Level.WARNING, "collector accept failed", t);
              // for cases that are not recoverable just discard the message,
              // otherwise ignore so processing can be retried.
              if (t instanceof IllegalArgumentException) {
                toDelete.add(
                    new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
              }
            }
          });
    } catch (RuntimeException | Error e) {
      logger.log(Level.WARNING, "message decoding failed", e);
      toDelete.add(new DeleteMessageBatchRequestEntry(deleteId, message.getReceiptHandle()));
    }
  }

  if (!toDelete.isEmpty()) {
    delete(toDelete);
  }
}
 
Example 8
Source File: AmazonSQSRule.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
static Stream<? extends Span> decodeSpans(Message m) {
  byte[] bytes =
      m.getBody().charAt(0) == '['
          ? m.getBody().getBytes(Charset.forName("UTF-8"))
          : Base64.decode(m.getBody());
  if (bytes[0] == '[') {
    return SpanBytesDecoder.JSON_V2.decodeList(bytes).stream();
  }
  return SpanBytesDecoder.PROTO3.decodeList(bytes).stream();
}
 
Example 9
Source File: KeyStoreMaterialsProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {

    KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
    macGen.init(256, Utils.getRng());
    macKey = macGen.generateKey();

    KeyGenerator aesGen = KeyGenerator.getInstance("AES");
    aesGen.init(128, Utils.getRng());
    encryptionKey = aesGen.generateKey();

    keyStore = KeyStore.getInstance("jceks");
    keyStore.load(null, password.toCharArray());

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec rsaSpec = new PKCS8EncodedKeySpec(Base64.decode(keyPem));
    privateKey = kf.generatePrivate(rsaSpec);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certPem)));


    keyStore.setEntry("enc", new SecretKeyEntry(encryptionKey), passwordProtection);
    keyStore.setEntry("sig", new SecretKeyEntry(macKey), passwordProtection);
    keyStore.setEntry("enc-a", new PrivateKeyEntry(privateKey, new Certificate[]{certificate}), passwordProtection);
    keyStore.setEntry("sig-a", new PrivateKeyEntry(privateKey, new Certificate[]{certificate}), passwordProtection);
    keyStore.setCertificateEntry("trustedCert", certificate);
}
 
Example 10
Source File: S3Service.java    From fullstop with Apache License 2.0 5 votes vote down vote up
public String writeToS3(final String accountId, final String region, final Date instanceBootTime,
                        final String logData, final String logType, final String instanceId) {
    String fileName = null;

    final DateTime dateTime = new DateTime(instanceBootTime, UTC);

    final String keyName = Paths.get(
            accountId, region, dateTime.toString("YYYY"), dateTime.toString("MM"),
            dateTime.toString("dd"), instanceId + "-" + dateTime).toString();

    switch (LogType.valueOf(logType)) {

        case USER_DATA:
            fileName = TAUPAGE_YAML;
            break;

        case AUDIT_LOG:
            fileName = AUDIT_LOG_FILE_NAME + new DateTime(UTC) + LOG_GZ;
            break;

        default:
            log.error("Wrong logType given: " + logType);
            break;
    }

    final ObjectMetadata metadata = new ObjectMetadata();
    final byte[] decodedLogData = Base64.decode(logData);
    metadata.setContentLength(decodedLogData.length);

    final InputStream stream = new ByteArrayInputStream(decodedLogData);

    putObjectToS3(bucketName, fileName, keyName, metadata, stream);

    return Paths.get(bucketName, keyName, fileName).toString();
}
 
Example 11
Source File: SnowflakeGCSClient.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
private void setupGCSClient(StageInfo stage, RemoteStoreFileEncryptionMaterial encMat)
throws IllegalArgumentException, SnowflakeSQLException
{
  // Save the client creation parameters so that we can reuse them,
  // to reset the GCS client.
  this.stageInfo = stage;
  this.encMat = encMat;

  logger.debug("Setting up the GCS client ");

  try
  {
    String accessToken = (String) stage.getCredentials().get("GCS_ACCESS_TOKEN");
    GoogleCredentials googleCreds;
    if (accessToken != null)
    {
      AccessToken googleAccessToken = new AccessToken(accessToken, null);

      googleCreds = GoogleCredentials.create(googleAccessToken);
      // We are authenticated with an oauth access token.
      this.gcsClient = StorageOptions.newBuilder()
          .setCredentials(googleCreds)
          .build()
          .getService();
    }
    else
    {
      // Use anonymous authentication.
      this.gcsClient = StorageOptions.getUnauthenticatedInstance()
          .getService();
    }

    if (encMat != null)
    {
      byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());
      encryptionKeySize = decodedKey.length * 8;

      if (encryptionKeySize != 128 &&
          encryptionKeySize != 192 &&
          encryptionKeySize != 256)
      {
        throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR,
                                        ErrorCode.INTERNAL_ERROR.getMessageCode(),
                                        "unsupported key size", encryptionKeySize);
      }
    }
  }
  catch (Exception ex)
  {
    throw new IllegalArgumentException("invalid_gcs_credentials");
  }
}
 
Example 12
Source File: SnowflakeS3Client.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
private void setupSnowflakeS3Client(Map<?, ?> stageCredentials,
                                    ClientConfiguration clientConfig,
                                    RemoteStoreFileEncryptionMaterial encMat,
                                    String stageRegion,
                                    String stageEndPoint)
throws SnowflakeSQLException
{
  // Save the client creation parameters so that we can reuse them,
  // to reset the AWS client. We won't save the awsCredentials since
  // we will be refreshing that, every time we reset the AWS client
  this.clientConfig = clientConfig;
  this.stageRegion = stageRegion;
  this.encMat = encMat;
  this.stageEndPoint = stageEndPoint; // FIPS endpoint, if needed

  logger.debug("Setting up AWS client ");

  // Retrieve S3 stage credentials
  String awsID = (String) stageCredentials.get("AWS_KEY_ID");
  String awsKey = (String) stageCredentials.get("AWS_SECRET_KEY");
  String awsToken = (String) stageCredentials.get("AWS_TOKEN");

  // initialize aws credentials
  AWSCredentials awsCredentials = (awsToken != null) ?
                                  new BasicSessionCredentials(awsID, awsKey, awsToken)
                                                     : new BasicAWSCredentials(awsID, awsKey);


  clientConfig.withSignerOverride("AWSS3V4SignerType");
  clientConfig.getApacheHttpClientConfig().setSslSocketFactory(
      getSSLConnectionSocketFactory());
  HttpUtil.setProxyForS3(clientConfig);
  AmazonS3Builder<?, ?> amazonS3Builder = AmazonS3Client.builder();
  if (encMat != null)
  {
    byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());
    encryptionKeySize = decodedKey.length * 8;

    if (encryptionKeySize == 256)
    {
      SecretKey queryStageMasterKey =
          new SecretKeySpec(decodedKey, 0, decodedKey.length, AES);
      EncryptionMaterials encryptionMaterials =
          new EncryptionMaterials(queryStageMasterKey);
      encryptionMaterials.addDescription("queryId",
                                         encMat.getQueryId());
      encryptionMaterials.addDescription("smkId",
                                         Long.toString(encMat.getSmkId()));
      CryptoConfiguration cryptoConfig =
          new CryptoConfiguration(CryptoMode.EncryptionOnly);

      amazonS3Builder = AmazonS3EncryptionClient.encryptionBuilder()
          .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
          .withEncryptionMaterials(new StaticEncryptionMaterialsProvider(encryptionMaterials))
          .withClientConfiguration(clientConfig)
          .withCryptoConfiguration(cryptoConfig);

    }
    else if (encryptionKeySize == 128)
    {
      amazonS3Builder = AmazonS3Client.builder()
          .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
          .withClientConfiguration(clientConfig);
    }
    else
    {
      throw new SnowflakeSQLException(SqlState.INTERNAL_ERROR,
                                      ErrorCode.INTERNAL_ERROR.getMessageCode(),
                                      "unsupported key size", encryptionKeySize);
    }
  }
  else
  {
    amazonS3Builder = AmazonS3Client.builder()
        .withCredentials(new AWSStaticCredentialsProvider(awsCredentials))
        .withClientConfiguration(clientConfig);
  }

  if (stageRegion != null)
  {
    Region region = RegionUtils.getRegion(stageRegion);
    if (region != null)
    {
      amazonS3Builder.withRegion(region.getName());
    }
  }
  // Explicitly force to use virtual address style
  amazonS3Builder.withPathStyleAccessEnabled(false);

  amazonClient = (AmazonS3) amazonS3Builder.build();
  if (this.stageEndPoint != null && this.stageEndPoint != "")
  {
    // Set the FIPS endpoint if we need it. GS will tell us if we do by
    // giving us an endpoint to use if required and supported by the region.
    amazonClient.setEndpoint(this.stageEndPoint);
  }
}
 
Example 13
Source File: EncryptionProvider.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
public static CipherInputStream encrypt(StorageObjectMetadata meta,
                                        long originalContentLength,
                                        InputStream src,
                                        RemoteStoreFileEncryptionMaterial encMat,
                                        SnowflakeStorageClient client)
throws InvalidKeyException,
       InvalidAlgorithmParameterException,
       NoSuchAlgorithmException,
       NoSuchProviderException,
       NoSuchPaddingException,
       FileNotFoundException,
       IllegalBlockSizeException,
       BadPaddingException
{
  final byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());
  final int keySize = decodedKey.length;
  final byte[] fileKeyBytes = new byte[keySize];
  final byte[] ivData;
  final CipherInputStream cis;
  final int blockSz;
  {
    final Cipher fileCipher = Cipher.getInstance(FILE_CIPHER);
    blockSz = fileCipher.getBlockSize();

    // Create IV
    ivData = new byte[blockSz];
    getSecRnd().nextBytes(ivData);
    final IvParameterSpec iv = new IvParameterSpec(ivData);

    // Create file key
    getSecRnd().nextBytes(fileKeyBytes);
    SecretKey fileKey = new SecretKeySpec(fileKeyBytes, 0, keySize, AES);

    // Init cipher
    fileCipher.init(Cipher.ENCRYPT_MODE, fileKey, iv);

    // Create encrypting input stream
    cis = new CipherInputStream(src, fileCipher);
  }

  // Encrypt the file key with the QRMK
  {
    final Cipher keyCipher = Cipher.getInstance(KEY_CIPHER);
    SecretKey queryStageMasterKey =
        new SecretKeySpec(decodedKey, 0, keySize, AES);

    // Init cipher
    keyCipher.init(Cipher.ENCRYPT_MODE, queryStageMasterKey);
    byte[] encKeK = keyCipher.doFinal(fileKeyBytes);

    // Store metadata
    MatDesc matDesc =
        new MatDesc(encMat.getSmkId(), encMat.getQueryId(), keySize * 8);
    // Round up length to next multiple of the block size
    // Sizes that are multiples of the block size need to be padded to next
    // multiple
    long contentLength = ((originalContentLength + blockSz) / blockSz) * blockSz;
    client.addEncryptionMetadata(meta, matDesc, ivData, encKeK, contentLength);
  }

  return cis;
}
 
Example 14
Source File: AuthenticationHelper.java    From alexa-web-information-service-api-samples with MIT License 4 votes vote down vote up
/**
 * Method is used to respond to the Auth challange from the user pool
 *
 * @param challenge The authenticaion challange returned from the cognito user pool
 * @param password  The password to be used to respond to the authentication challenge.
 * @return the Request created for the previous authentication challenge.
 */
private RespondToAuthChallengeRequest userSrpAuthRequest(InitiateAuthResult challenge,
                                                         String password
) {
    String userIdForSRP = challenge.getChallengeParameters().get("USER_ID_FOR_SRP");
    String usernameInternal = challenge.getChallengeParameters().get("USERNAME");

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

    BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    byte[] key = getPasswordAuthenticationKey(userIdForSRP, password, B, salt);

    Date timestamp = new Date();
    byte[] hmac = null;
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(this.userPoolID.split("_", 2)[1].getBytes(StringUtils.UTF8));
        mac.update(userIdForSRP.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) {
        System.out.println(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<>();
    srpAuthResponses.put("PASSWORD_CLAIM_SECRET_BLOCK", challenge.getChallengeParameters().get("SECRET_BLOCK"));
    srpAuthResponses.put("PASSWORD_CLAIM_SIGNATURE", new String(Base64.encode(hmac), StringUtils.UTF8));
    srpAuthResponses.put("TIMESTAMP", formatTimestamp.format(timestamp));
    srpAuthResponses.put("USERNAME", usernameInternal);

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

    return authChallengeRequest;
}
 
Example 15
Source File: UploadServiceTest.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldUploadInputStreamFile() {
    InputStream is = new ByteArrayInputStream(Base64.decode(base64Img.getBytes()));
    ServiceResponse<String> response = service.upload(is, fileName, "jpg", true);
    Assert.assertNotNull(response);
}
 
Example 16
Source File: AwsUploadRepository.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Override
public String upload(String base64, String fileName, String suffix, boolean isPublic) throws Exception {
    InputStream is = new ByteArrayInputStream(Base64.decode(base64.getBytes()));
    return upload(is, fileName, suffix, isPublic);
}
 
Example 17
Source File: Encoder.java    From strongbox with Apache License 2.0 4 votes vote down vote up
public static byte[] base64decode(String value) {
    return Base64.decode(value);
}
 
Example 18
Source File: EncryptionProvider.java    From snowflake-jdbc with Apache License 2.0 3 votes vote down vote up
/**
 * Decrypt a InputStream
 */
public static InputStream decryptStream(InputStream inputStream,
                                        String keyBase64,
                                        String ivBase64,
                                        RemoteStoreFileEncryptionMaterial encMat)
throws NoSuchPaddingException, NoSuchAlgorithmException,
       InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
       InvalidAlgorithmParameterException
{
  byte[] decodedKey = Base64.decode(encMat.getQueryStageMasterKey());

  byte[] keyBytes = Base64.decode(keyBase64);

  byte[] ivBytes = Base64.decode(ivBase64);

  SecretKey queryStageMasterKey =
      new SecretKeySpec(decodedKey, 0, decodedKey.length, AES);

  Cipher keyCipher = Cipher.getInstance(KEY_CIPHER);

  keyCipher.init(Cipher.DECRYPT_MODE, queryStageMasterKey);

  byte[] fileKeyBytes = keyCipher.doFinal(keyBytes);

  SecretKey fileKey =
      new SecretKeySpec(fileKeyBytes, 0, decodedKey.length, AES);

  Cipher dataCipher = Cipher.getInstance(FILE_CIPHER);

  IvParameterSpec ivy = new IvParameterSpec(ivBytes);

  dataCipher.init(Cipher.DECRYPT_MODE, fileKey, ivy);

  return new CipherInputStream(inputStream, dataCipher);

}