com.amazonaws.encryptionsdk.CryptoAlgorithm Java Examples

The following examples show how to use com.amazonaws.encryptionsdk.CryptoAlgorithm. 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: MultipleProviderFactory.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public DataKey<K> decryptDataKey(final CryptoAlgorithm algorithm,
        final Collection<? extends EncryptedDataKey> encryptedDataKeys,
        final Map<String, String> encryptionContext)
        throws UnsupportedProviderException, AwsCryptoException {
    final List<Exception> exceptions = new ArrayList<>();
    for (final MasterKeyProvider<? extends K> prov : providers_) {
        try {
            final DataKey<? extends K> result = prov
                    .decryptDataKey(algorithm, encryptedDataKeys, encryptionContext);
            if (result != null) {
                return (DataKey<K>) result;
            }
        } catch (final Exception ex) {
            exceptions.add(ex);
        }
    }
    throw buildCannotDecryptDksException(exceptions);
}
 
Example #2
Source File: TestFieldEncryptProcessor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonCacheableCipher() throws Exception {
  ProcessorFieldEncryptConfig config = new ProcessorFieldEncryptConfig();
  config.mode = EncryptionMode.ENCRYPT;
  config.cipher = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF;
  config.fieldPaths = ImmutableList.of("/");
  config.key = key;
  config.keyId = "keyId";
  config.context = aad;
  config.dataKeyCaching = true;
  config.maxKeyAge = 600;
  config.maxRecordsPerKey = 1000;
  config.maxBytesPerKey = String.valueOf(Long.MAX_VALUE);

  Processor encryptProcessor = new FieldEncryptProcessor(config);

  ProcessorRunner runner = new ProcessorRunner.Builder(
      FieldEncryptDProcessor.class,
      encryptProcessor
  ).addOutputLane("lane").build();

  List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
  assertEquals(1, issues.size());
  assertTrue(issues.get(0).toString().contains("Data key caching is not supported"));
}
 
Example #3
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<KmsMasterKey> decryptDataKey(final CryptoAlgorithm algorithm,
        final Collection<? extends EncryptedDataKey> encryptedDataKeys, final Map<String, String> encryptionContext)
        throws AwsCryptoException {
    final List<Exception> exceptions = new ArrayList<>();
    for (final EncryptedDataKey edk : encryptedDataKeys) {
        if (canProvide(edk.getProviderId())) {
            try {
                final String keyArn = new String(edk.getProviderInformation(), StandardCharsets.UTF_8);
                // This will throw if we can't use this key for whatever reason
                return getMasterKey(keyArn).decryptDataKey(algorithm, singletonList(edk), encryptionContext);
            } catch (final Exception asex) {
                exceptions.add(asex);
            }
        }
    }
    throw buildCannotDecryptDksException(exceptions);
}
 
Example #4
Source File: KmsMasterKey.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<KmsMasterKey> encryptDataKey(final CryptoAlgorithm algorithm,
        final Map<String, String> encryptionContext,
        final DataKey<?> dataKey) {
    final SecretKey key = dataKey.getKey();
    if (!key.getFormat().equals("RAW")) {
        throw new IllegalArgumentException("Only RAW encoded keys are supported");
    }
    try {
        final EncryptResult encryptResult = kms_.get().encrypt(updateUserAgent(
                new EncryptRequest()
                        .withKeyId(id_)
                        .withPlaintext(ByteBuffer.wrap(key.getEncoded()))
                        .withEncryptionContext(encryptionContext)
                        .withGrantTokens(grantTokens_)));
        final byte[] edk = new byte[encryptResult.getCiphertextBlob().remaining()];
        encryptResult.getCiphertextBlob().get(edk);
        return new DataKey<>(dataKey.getKey(), edk, encryptResult.getKeyId().getBytes(StandardCharsets.UTF_8), this);
    } catch (final AmazonServiceException asex) {
        throw new AwsCryptoException(asex);
    }
}
 
Example #5
Source File: CachingCryptoMaterialsManager.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private byte[] getCacheIdentifier(EncryptionMaterialsRequest req) {
    try {
        MessageDigest digest = MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM);

        digest.update(partitionIdHash);

        CryptoAlgorithm algorithm = req.getRequestedAlgorithm();
        digest.update((byte) (algorithm != null ? 1 : 0));
        if (algorithm != null) {
            updateDigestWithAlgorithm(digest, algorithm);
        }

        digest.update(MessageDigest.getInstance(CACHE_ID_HASH_ALGORITHM).digest(
                EncryptionContextSerializer.serialize(req.getContext())
        ));

        return digest.digest();
    } catch (GeneralSecurityException e) {
        throw new AwsCryptoException(e);
    }
}
 
Example #6
Source File: KmsMasterKey.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<KmsMasterKey> generateDataKey(final CryptoAlgorithm algorithm,
        final Map<String, String> encryptionContext) {
    final GenerateDataKeyResult gdkResult = kms_.get().generateDataKey(updateUserAgent(
            new GenerateDataKeyRequest()
                    .withKeyId(getKeyId())
                    .withNumberOfBytes(algorithm.getDataKeyLength())
                    .withEncryptionContext(encryptionContext)
                    .withGrantTokens(grantTokens_)
    ));
    final byte[] rawKey = new byte[algorithm.getDataKeyLength()];
    gdkResult.getPlaintext().get(rawKey);
    if (gdkResult.getPlaintext().remaining() > 0) {
        throw new IllegalStateException("Recieved an unexpected number of bytes from KMS");
    }
    final byte[] encryptedKey = new byte[gdkResult.getCiphertextBlob().remaining()];
    gdkResult.getCiphertextBlob().get(encryptedKey);

    final SecretKeySpec key = new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo());
    return new DataKey<>(key, encryptedKey, gdkResult.getKeyId().getBytes(StandardCharsets.UTF_8), this);
}
 
Example #7
Source File: JceMasterKey.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<JceMasterKey> decryptDataKey(final CryptoAlgorithm algorithm,
        final Collection<? extends EncryptedDataKey> encryptedDataKeys,
        final Map<String, String> encryptionContext)
        throws UnsupportedProviderException, AwsCryptoException {
    final List<Exception> exceptions = new ArrayList<>();
    // Find an encrypted key who's provider and info match us
    for (final EncryptedDataKey edk : encryptedDataKeys) {
        try {
            if (edk.getProviderId().equals(getProviderId())
                    && Utils.arrayPrefixEquals(edk.getProviderInformation(), keyIdBytes_, keyIdBytes_.length)) {
                final byte[] decryptedKey = jceKeyCipher_.decryptKey(edk, keyId_, encryptionContext);

                // Validate that the decrypted key length is as expected
                if (decryptedKey.length == algorithm.getDataKeyLength()) {
                    return new DataKey<>(new SecretKeySpec(decryptedKey, algorithm.getDataKeyAlgo()),
                            edk.getEncryptedDataKey(), edk.getProviderInformation(), this);
                }
            }
        } catch (final Exception ex) {
            exceptions.add(ex);
        }
    }
    throw buildCannotDecryptDksException(exceptions);
}
 
Example #8
Source File: TestFieldEncryptProcessor.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testInit() throws Exception {
  ProcessorFieldEncryptConfig conf = new ProcessorFieldEncryptConfig();
  conf.mode = EncryptionMode.ENCRYPT;
  conf.cipher = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384;
  conf.fieldPaths = ImmutableList.of("/message");
  conf.key = key;
  conf.keyId = "keyId";
  conf.context = aad;
  conf.maxBytesPerKey = String.valueOf(Long.MAX_VALUE);

  Processor processor = new FieldEncryptProcessor(conf);

  ProcessorRunner runner = new ProcessorRunner.Builder(FieldEncryptDProcessor.class, processor)
      .addOutputLane("lane")
      .build();

  List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
  assertTrue(issues.isEmpty());
}
 
Example #9
Source File: TestFieldEncryptProtector.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testNonCacheableCipher() throws Exception {
  ProtectorFieldEncryptConfig config = new ProtectorFieldEncryptConfig();
  config.cipher = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF;
  config.key = key;
  config.keyId = "keyId";
  config.context = aad;
  config.dataKeyCaching = true;
  config.maxKeyAge = 600;
  config.maxRecordsPerKey = 1000;
  config.maxBytesPerKey = String.valueOf(Long.MAX_VALUE);

  Processor encryptProcessor = new EncryptFieldProtector();
  ((EncryptFieldProtector) encryptProcessor).conf = config;

      ProcessorRunner runner = new ProcessorRunner.Builder(
      FieldEncryptDProcessor.class,
      encryptProcessor
  ).addOutputLane("lane").build();

  List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
  assertEquals(1, issues.size());
  assertTrue(issues.get(0).toString().contains("Data key caching is not supported"));
}
 
Example #10
Source File: JceMasterKey.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<JceMasterKey> encryptDataKey(final CryptoAlgorithm algorithm,
        final Map<String, String> encryptionContext,
        final DataKey<?> dataKey) {
    final SecretKey key = dataKey.getKey();
    if (!key.getFormat().equals("RAW")) {
        throw new IllegalArgumentException("Can only re-encrypt data keys which are in RAW format, not "
                + dataKey.getKey().getFormat());
    }
    if (!key.getAlgorithm().equalsIgnoreCase(algorithm.getDataKeyAlgo())) {
        throw new IllegalArgumentException("Incorrect key algorithm. Expected " + key.getAlgorithm()
                + " but got " + algorithm.getKeyAlgo());
    }
    EncryptedDataKey encryptedDataKey = jceKeyCipher_.encryptKey(key.getEncoded(), keyId_, providerName_, encryptionContext);
    return new DataKey<>(key, encryptedDataKey.getEncryptedDataKey(), encryptedDataKey.getProviderInformation(), this);
}
 
Example #11
Source File: TestFieldEncryptProtector.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testInit() throws Exception {
  ProtectorFieldEncryptConfig conf = new ProtectorFieldEncryptConfig();
  conf.cipher = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384;
  conf.key = key;
  conf.keyId = "keyId";
  conf.context = aad;
  conf.maxBytesPerKey = String.valueOf(Long.MAX_VALUE);

  Processor processor = new EncryptFieldProtector();
  ((EncryptFieldProtector) processor).conf = conf;

  ProcessorRunner runner = new ProcessorRunner.Builder(FieldEncryptDProcessor.class, processor)
      .addOutputLane("lane")
      .build();

  List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
  assertTrue(issues.isEmpty());
}
 
Example #12
Source File: JceMasterKeyProvider.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<JceMasterKey> decryptDataKey(
    CryptoAlgorithm algorithm,
    Collection<? extends EncryptedDataKey> encryptedDataKeys,
    Map<String, String> encryptionContext
) throws UnsupportedProviderException, AwsCryptoException {
  final List<Exception> exceptions = new ArrayList<>();
  for (final EncryptedDataKey edk : encryptedDataKeys) {
    try {
      final DataKey<JceMasterKey> result = masterKey.decryptDataKey(
          algorithm,
          Collections.singletonList(edk),
          encryptionContext);
      if (result != null) {
        return result;
      }
    } catch (final Exception ex) {
      exceptions.add(ex);
    }
  }

  throw buildCannotDecryptDksException(exceptions);
}
 
Example #13
Source File: TrailingSignatureAlgorithmTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private void testDeserialization(CryptoAlgorithm algorithm,  int[] compressedKey, int[] expectedX, int[] expectedY) {
    byte[] bytes = TestUtils.unsignedBytesToSignedBytes(compressedKey);

    String publicKey = Utils.encodeBase64String(bytes);

    PublicKey publicKeyDeserialized = TrailingSignatureAlgorithm
            .forCryptoAlgorithm(algorithm)
            .deserializePublicKey(publicKey);

    ECPublicKey desKey = (ECPublicKey) publicKeyDeserialized;

    BigInteger x = desKey.getW().getAffineX();
    BigInteger y = desKey.getW().getAffineY();

    BigInteger expectedXBigInteger = new BigInteger(1, TestUtils.unsignedBytesToSignedBytes(expectedX));
    BigInteger expectedYBigInteger = new BigInteger(1, TestUtils.unsignedBytesToSignedBytes(expectedY));

    assertEquals(expectedXBigInteger, x);
    assertEquals(expectedYBigInteger, y);
}
 
Example #14
Source File: TrailingSignatureAlgorithmTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private void testSerialization(CryptoAlgorithm algorithm, String curveName, int[] x, int[] y, int[] expected) throws Exception {
    byte[] xBytes = TestUtils.unsignedBytesToSignedBytes(x);
    byte[] yBytes = TestUtils.unsignedBytesToSignedBytes(y);

    final AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
    parameters.init(new ECGenParameterSpec(curveName));
    ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);

    PublicKey publicKey = KeyFactory.getInstance("EC").generatePublic(
            new ECPublicKeySpec(new ECPoint(new BigInteger(1, xBytes), new BigInteger(1, yBytes)), ecParameterSpec));

    int[] result = TestUtils.signedBytesToUnsignedBytes(Utils.decodeBase64String(TrailingSignatureAlgorithm
            .forCryptoAlgorithm(algorithm)
            .serializePublicKey(publicKey)));

    assertArrayEquals(expected, result);
}
 
Example #15
Source File: CipherHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = BadCiphertextException.class)
public void tamperCiphertext() {
    final CryptoAlgorithm cryptoAlgorithm = AwsCrypto.getDefaultCryptoAlgorithm();
    final byte[] content = RandomBytesGenerator.generate(contentLen_);
    final byte[] keyBytes = RandomBytesGenerator.generate(cryptoAlgorithm.getKeyLength());
    final byte[] nonce = RandomBytesGenerator.generate(cryptoAlgorithm.getNonceLen());

    final SecretKey key = new SecretKeySpec(keyBytes, cryptoAlgorithm.getKeyAlgo());
    CipherHandler cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.ENCRYPT_MODE);
    final byte[] encryptedBytes = cipherHandler.cipherData(nonce, contentAad_, content, 0, content.length);

    encryptedBytes[0] += 1; // tamper the first byte in ciphertext

    cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.DECRYPT_MODE);
    cipherHandler.cipherData(nonce, contentAad_, encryptedBytes, 0, encryptedBytes.length);
}
 
Example #16
Source File: StaticMasterKey.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DataKey<StaticMasterKey> decryptDataKey(CryptoAlgorithm algorithm,
        Collection<? extends EncryptedDataKey> encryptedDataKeys,
        Map<String, String> encryptionContext)
        throws UnsupportedProviderException, AwsCryptoException {
    try {
        for (EncryptedDataKey edk :encryptedDataKeys) {
            if (keyId_.equals(new String(edk.getProviderInformation(), StandardCharsets.UTF_8))) {
                byte[] unencryptedDataKey = masterKeyDecryptionCipher_.doFinal(edk.getEncryptedDataKey());
                SecretKey key = new SecretKeySpec(unencryptedDataKey, algorithm.getDataKeyAlgo());
                return new DataKey<>(key, edk.getEncryptedDataKey(), edk.getProviderInformation(), this);
            }
        }
    } catch (GeneralSecurityException ex) {
        throw new RuntimeException(ex);
    }
    return null;
}
 
Example #17
Source File: DecryptionHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private byte[] getTestHeaders() {
    final CryptoAlgorithm cryptoAlgorithm_ = AwsCrypto.getDefaultCryptoAlgorithm();
    final int frameSize_ = AwsCrypto.getDefaultFrameSize();
    final Map<String, String> encryptionContext = Collections.<String, String> emptyMap();

    final EncryptionMaterialsRequest encryptionMaterialsRequest = EncryptionMaterialsRequest.newBuilder()
                                                                                            .setContext(encryptionContext)
                                                                                            .setRequestedAlgorithm(cryptoAlgorithm_)
                                                                                            .build();

    final EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(masterKeyProvider_)
            .getMaterialsForEncrypt(encryptionMaterialsRequest);

    final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, encryptionMaterials);

    // create the ciphertext headers by calling encryption handler.
    final byte[] in = new byte[0];
    final int ciphertextLen = encryptionHandler.estimateOutputSize(in.length);
    final byte[] ciphertext = new byte[ciphertextLen];
    encryptionHandler.processBytes(in, 0, in.length, ciphertext, 0);
    return ciphertext;
}
 
Example #18
Source File: DecryptionMaterialsRequestTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void build() {
    CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256;
    Map<String, String> encryptionContext = new HashMap<String, String>(1);
    encryptionContext.put("DMR", "DecryptionMaterialsRequest Test");
    List<KeyBlob> kbs = new ArrayList<KeyBlob>();
    
    DecryptionMaterialsRequest request0 = DecryptionMaterialsRequest.newBuilder()
        .setAlgorithm(alg)
        .setEncryptionContext(encryptionContext)
        .setEncryptedDataKeys(kbs)
        .build();
    
    DecryptionMaterialsRequest request1 = request0.toBuilder().build();

    assertEquals(request0.getAlgorithm(), request1.getAlgorithm());
    assertEquals(request0.getEncryptionContext().size(), request1.getEncryptionContext().size());
    assertEquals(request0.getEncryptedDataKeys().size(), request1.getEncryptedDataKeys().size());
}
 
Example #19
Source File: KMSEncryptor.java    From strongbox with Apache License 2.0 6 votes vote down vote up
public KMSEncryptor(KMSManager kmsManager, AWSCredentialsProvider awsCredentials, ClientConfiguration clientConfiguration, SecretsGroupIdentifier groupIdentifier, AwsCrypto awsCrypto, EncryptionStrength encryptionStrength) {
    this.awsCredentials = awsCredentials;
    this.clientConfiguration = clientConfiguration;
    this.groupIdentifier = groupIdentifier;
    this.kmsManager = kmsManager;

    if (encryptionStrength.equals(EncryptionStrength.AES_128)) {
        awsCrypto.setEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256);
    } else if (encryptionStrength.equals(EncryptionStrength.AES_256)) {
        awsCrypto.setEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384);
    } else {
        throw new IllegalArgumentException(String.format("Unrecognized encryption strength %s", encryptionStrength.toString()));
    }

    this.crypto = awsCrypto;
}
 
Example #20
Source File: CachingCryptoMaterialsManagerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void whenInitialUsageExceedsLimit_cacheIsBypassed() throws Exception {
    EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0)
                                                          .toBuilder()
                                                          // Even at _exactly_ the byte-use limit, we won't try the cache,
                                                          // because it's unlikely to be useful to leave an entry with zero
                                                          // bytes remaining.
                                                          .setPlaintextSize(200)
                                                          .build();
    EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request).toBuilder()
                                                  .setAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF)
                                                  .build();
    setupForCacheMiss(request, result);

    assertEquals(result, cmm.getMaterialsForEncrypt(request));
    verifyNoMoreInteractions(cache);
}
 
Example #21
Source File: KMSEncryptorTest.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    AWSCredentialsProvider mockCredentials = mock(AWSCredentialsProvider.class);
    ClientConfiguration mockConfig = mock(ClientConfiguration.class);
    SecretsGroupIdentifier group = new SecretsGroupIdentifier(Region.US_WEST_1, "test.group");

    this.mockAwsCrypto = mock(AwsCrypto.class);
    this.mockKmsManager = mock(KMSManager.class);
    KMSEncryptor encryptor = new KMSEncryptor(mockKmsManager, mockCredentials, mockConfig, group, mockAwsCrypto, EncryptionStrength.AES_256);

    this.kmsEncryptor = spy(encryptor);
    this.mockProvider = mock(KmsMasterKeyProvider.class);
    doReturn(mockProvider).when(kmsEncryptor).getProvider();

    // Verify the expected encryption algorithm was set.
    verify(mockAwsCrypto, times(1)).setEncryptionAlgorithm(
            CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384);
}
 
Example #22
Source File: TrailingSignatureAlgorithmTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testBadPoint() {
    byte[] bytes = TestUtils.unsignedBytesToSignedBytes(secp384r1CompressedFixture);
    bytes[20]++;

    String publicKey = Utils.encodeBase64String(bytes);

    TrailingSignatureAlgorithm
            .forCryptoAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384)
            .deserializePublicKey(publicKey);
}
 
Example #23
Source File: CipherHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void encryptDecryptWithAllAlgos() {
    for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) {
        assertTrue(encryptDecryptContent(cryptoAlg));
        assertTrue(encryptDecryptEmptyContent(cryptoAlg));
    }
}
 
Example #24
Source File: TestFieldEncryptProcessor.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrongInputType() throws Exception {
  ProcessorFieldEncryptConfig decryptConfig = new ProcessorFieldEncryptConfig();
  decryptConfig.mode = EncryptionMode.DECRYPT;
  decryptConfig.cipher = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384;
  decryptConfig.fieldPaths = ImmutableList.of("/");
  decryptConfig.key = key;
  decryptConfig.keyId = "keyId";
  decryptConfig.context = aad;
  decryptConfig.maxBytesPerKey = String.valueOf(Long.MAX_VALUE);

  Processor decryptProcessor = new FieldEncryptProcessor(decryptConfig);

  ProcessorRunner decryptRunner = new ProcessorRunner.Builder(
      FieldEncryptDProcessor.class,
      decryptProcessor
  ).addOutputLane("lane").build();

  Record record = RecordCreator.create();
  record.set(Field.create("abcdef"));

  decryptRunner.runInit();
  StageRunner.Output output = decryptRunner.runProcess(ImmutableList.of(record));
  List<Record> decryptedRecords = output.getRecords().get("lane");
  assertEquals(0, decryptedRecords.size());
  List<Record> errors = decryptRunner.getErrorRecords();
  assertEquals(1, errors.size());
  assertEquals(record.get(), errors.get(0).get());
}
 
Example #25
Source File: CipherHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
private byte[] encryptDecrypt(final byte[] content, final CryptoAlgorithm cryptoAlgorithm) {
    final byte[] keyBytes = RandomBytesGenerator.generate(cryptoAlgorithm.getKeyLength());
    final byte[] nonce = RandomBytesGenerator.generate(cryptoAlgorithm.getNonceLen());

    final SecretKey key = new SecretKeySpec(keyBytes, cryptoAlgorithm.getKeyAlgo());
    CipherHandler cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.ENCRYPT_MODE);
    final byte[] encryptedBytes = cipherHandler.cipherData( nonce, contentAad_, content, 0, content.length);

    cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.DECRYPT_MODE);
    final byte[] decryptedBytes = cipherHandler.cipherData(nonce, contentAad_, encryptedBytes, 0, encryptedBytes.length);

    return decryptedBytes;
}
 
Example #26
Source File: CacheIdentifierTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void encryptDigestTestVector() throws Exception {
    HashMap<String, String> contextMap = new HashMap<>();

    contextMap.put("\0\0TEST", "\0\0test");
    // Note! This key is actually U+10000, but java treats it as a UTF-16 surrogate pair.
    // UTF-8 encoding should be 0xF0 0x90 0x80 0x80
    contextMap.put("\uD800\uDC00", "UTF-16 surrogate");
    contextMap.put("\uABCD", "\\uABCD");

    byte[] id = getCacheIdentifier(getCMM("partition ID"),
                                   EncryptionMaterialsRequest.newBuilder()
                                                             .setContext(contextMap)
                                                             .setRequestedAlgorithm(null)
                                                             .build()
    );

    assertEquals(
            "683328d033fc60a20e3d3936190b33d91aad0143163226af9530e7d1b3de0e96" +
                    "39c00a2885f9cea09cf9a273bef316a39616475b50adc2441b69f67e1a25145f",
            new String(Hex.encode(id)));

    id = getCacheIdentifier(getCMM("partition ID"),
                            EncryptionMaterialsRequest.newBuilder()
                                                      .setContext(contextMap)
                                                      .setRequestedAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256)
                                                      .build()
    );

    assertEquals(
            "3dc70ff1d4621059b97179563ab6592dff4319bfaf8ed1a819c96d33d3194d5c" +
                    "354a361e879d0356e4d9e868170ebc9e934fa5eaf6e6d11de4ee801645723fa9",
            new String(Hex.encode(id)));
}
 
Example #27
Source File: CacheIdentifierTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
void assertEncryptId(String partitionName, CryptoAlgorithm algo, Map<String, String> context, String expect) throws Exception {
    EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder()
                                                                   .setContext(context)
                                                                   .setRequestedAlgorithm(algo)
                                                                   .build();

    byte[] id = getCacheIdentifier(getCMM(partitionName), request);

    assertEquals(expect, Utils.encodeBase64String(id));
}
 
Example #28
Source File: CachingCryptoMaterialsManagerTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenAlgorithmIsUncachable_resultNotStoredInCache() throws Exception {
    EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0)
                                                          .toBuilder()
                                                          .setPlaintextSize(100)
                                                          .build();
    EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request).toBuilder()
                                                  .setAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF)
                                                  .build();
    setupForCacheMiss(request, result);

    assertEquals(result, cmm.getMaterialsForEncrypt(request));
    verify(cache, never()).putEntryForEncrypt(any(), any(), any(), any());
}
 
Example #29
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBogusRegionsDecrypted_doesNotLeakClients() throws Exception {
    AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>();

    KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() {
        @Override protected void snoopClientCache(
                final ConcurrentHashMap<String, AWSKMS> map
        ) {
            kmsCache.set(map);
        }
    }).build();

    try {
        mkp.decryptDataKey(
                CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256,
                Collections.singleton(
                        new KeyBlob("aws-kms",
                                    "arn:aws:kms:us-bogus-1:123456789010:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"
                                            .getBytes(StandardCharsets.UTF_8),
                                    new byte[40]
                        )
                ),
                new HashMap<>()
        );
        fail("Expected CannotUnwrapDataKeyException");
    } catch (CannotUnwrapDataKeyException e) {
        // ok
    }

    assertTrue(kmsCache.get().isEmpty());
}
 
Example #30
Source File: CacheIdentifierTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
void assertDecryptId(String partitionName, CryptoAlgorithm algo, List<KeyBlob> blobs, Map<String, String> context, String expect) throws Exception {
    DecryptionMaterialsRequest request =
            DecryptionMaterialsRequest.newBuilder()
                                      .setAlgorithm(algo)
                                      .setEncryptionContext(context)
                                      .setEncryptedDataKeys(blobs)
                                      .build();

    byte[] id = getCacheIdentifier(getCMM(partitionName), request);

    assertEquals(expect, Utils.encodeBase64String(id));
}