com.amazonaws.services.dynamodbv2.model.AttributeValue Java Examples

The following examples show how to use com.amazonaws.services.dynamodbv2.model.AttributeValue. 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: HiveDynamoDBTypeTest.java    From emr-dynamodb-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleTypeList() {
  List<AttributeValue> avList = new ArrayList<>();
  avList.add(new AttributeValue(STRING_LIST.get(0)));
  avList.add(new AttributeValue().withN(STRING_LIST.get(0)));
  AttributeValue av = new AttributeValue().withL(avList);

  HiveDynamoDBType ddType = HiveDynamoDBTypeFactory.getTypeObjectFromHiveType(STRING_LIST_OBJECT_INSPECTOR);
  List<String> expectedStringList = Lists.newArrayList(STRING_LIST.get(0), null);
  Object actualList = ddType.getHiveData(av, STRING_LIST_OBJECT_INSPECTOR);
  assertEquals(expectedStringList, actualList);

  ddType = HiveDynamoDBTypeFactory.getTypeObjectFromHiveType(LONG_LIST_OBJECT_INSPECTOR);
  List<Long> expectedLongList = Lists.newArrayList(null, LONG_LIST.get(0));
  actualList = ddType.getHiveData(av, LONG_LIST_OBJECT_INSPECTOR);
  assertEquals(expectedLongList, actualList);
}
 
Example #2
Source File: DelegatedEncryptionTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void signedOnlyNullCryptoKey() throws GeneralSecurityException {
    prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap());
    encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
    Map<String, AttributeValue> encryptedAttributes =
            encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept(encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
    assertThat(decryptedAttributes, AttrMatcher.match(attribs));

    // Make sure keys and version are not encrypted
    assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
    assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
    assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));

    // Make sure String has not been encrypted (we'll assume the others are correct as well)
    assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
 
Example #3
Source File: NumericSetAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    for ( Map<String, AttributeValue> attr : attrs ) {
        NumberSetAttributeTestClass x = util.load(NumberSetAttributeTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        
        // Convert all numbers to the most inclusive type for easy comparison
        assertNumericSetsEquals(x.getBigDecimalAttribute(), attr.get(BIG_DECIMAL_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getBigIntegerAttribute(), attr.get(BIG_INTEGER_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getFloatObjectAttribute(), attr.get(FLOAT_OBJECT_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getDoubleObjectAttribute(), attr.get(DOUBLE_OBJECT_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getIntegerAttribute(), attr.get(INTEGER_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getLongObjectAttribute(), attr.get(LONG_OBJECT_ATTRIBUTE).getNS());
        assertNumericSetsEquals(x.getByteObjectAttribute(), attr.get(BYTE_OBJECT_ATTRIBUTE).getNS());
        assertSetsEqual(toSet("0", "1"), attr.get(BOOLEAN_ATTRIBUTE).getNS());
    }
}
 
Example #4
Source File: DelegatedEnvelopeEncryptionTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void signedOnlyNullCryptoKey() throws GeneralSecurityException {
    prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap());
    encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
    Map<String, AttributeValue> encryptedAttributes =
            encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    Map<String, AttributeValue> decryptedAttributes = encryptor.decryptAllFieldsExcept(encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
    assertThat(decryptedAttributes, AttrMatcher.match(attribs));

    // Make sure keys and version are not encrypted
    assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
    assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
    assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));

    // Make sure String has not been encrypted (we'll assume the others are correct as well)
    assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
 
Example #5
Source File: AttributeValueCoderTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPassForMapType() throws IOException {
  AttributeValue expected = new AttributeValue();

  Map<String, AttributeValue> attrMap = new HashMap<>();
  attrMap.put("innerMapAttr1", new AttributeValue("innerMapValue1"));
  attrMap.put(
      "innerMapAttr2",
      new AttributeValue().withB(ByteBuffer.wrap("8976234".getBytes(StandardCharsets.UTF_8))));

  expected.setM(attrMap);

  AttributeValueCoder coder = AttributeValueCoder.of();
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  coder.encode(expected, output);

  ByteArrayInputStream in = new ByteArrayInputStream(output.toByteArray());

  AttributeValue actual = coder.decode(in);

  Assert.assertEquals(expected, actual);
}
 
Example #6
Source File: AttributeEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void fullEncryption() {
    Parameters<BaseClass> params = FakeParameters.getInstance(BaseClass.class, attribs, null,
            TABLE_NAME, HASH_KEY, RANGE_KEY);
    Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    params = FakeParameters.getInstance(BaseClass.class, encryptedAttributes, null, TABLE_NAME,
            HASH_KEY, RANGE_KEY);
    Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
    assertThat(decryptedAttributes, AttrMatcher.match(attribs));

    // Make sure keys and version are not encrypted
    assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY));
    assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY));
    assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));

    // Make sure String has been encrypted (we'll assume the others are correct as well)
    assertTrue(encryptedAttributes.containsKey("stringValue"));
    assertNull(encryptedAttributes.get("stringValue").getS());
    assertNotNull(encryptedAttributes.get("stringValue").getB());
}
 
Example #7
Source File: BinaryAttributesITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoad() throws Exception {
    DynamoDBMapper util = TestDynamoDBMapperFactory.createDynamoDBMapper(dynamo);

    for ( Map<String, AttributeValue> attr : attrs ) {
    	// test BinaryAttributeClass
        BinaryAttributeByteBufferTestClass x = util.load(BinaryAttributeByteBufferTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(x.getKey(), attr.get(KEY_NAME).getS());
        assertEquals(x.getBinaryAttribute(), ByteBuffer.wrap(generateByteArray(contentLength)));
        assertTrue(x.getBinarySetAttribute().contains(ByteBuffer.wrap(generateByteArray(contentLength))));
        assertTrue(x.getBinarySetAttribute().contains(ByteBuffer.wrap(generateByteArray(contentLength + 1))));

        // test BinaryAttributeByteArrayTestClass
        BinaryAttributeByteArrayTestClass y = util.load(BinaryAttributeByteArrayTestClass.class, attr.get(KEY_NAME).getS());
        assertEquals(y.getKey(), attr.get(KEY_NAME).getS());
        assertTrue(Arrays.equals(y.getBinaryAttribute(), (generateByteArray(contentLength))));
        assertTrue(2 == y.getBinarySetAttribute().size());
        assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength)));
        assertTrue(setContainsBytes(y.getBinarySetAttribute(), generateByteArray(contentLength+1)));
    }

}
 
Example #8
Source File: AttributeEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncryptWithFieldLevelDoNotTouchAnnotation() {
    Map<String, AttributeValue> attributes = new HashMap<>(attribs);
    attributes.put("value", new AttributeValue().withN("100"));
    Parameters<? extends DoNotTouchField> params = FakeParameters.getInstance(
        DoNotTouchField.class, attributes, null,
        TABLE_NAME, HASH_KEY, RANGE_KEY);
    Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
    assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
    assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
    params = FakeParameters.getInstance(
        DoNotTouchField.class, encryptedAttributes, null,
        TABLE_NAME, HASH_KEY, RANGE_KEY);
    Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
    assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
 
Example #9
Source File: AttributeEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testSignOnlyWithUnknownAttributeAnnotationBadSignature() {
    Map<String, AttributeValue> attributes = new HashMap<>(attribs);
    attributes.put("newAttribute", new AttributeValue().withS("foo"));
    Parameters<? extends SignOnlyWithUnknownAttributeAnnotation> params = FakeParameters.getInstance(
            SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.class, attributes, null,
            TABLE_NAME, HASH_KEY, RANGE_KEY);
    Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
    assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
    assertAttrEquals(new AttributeValue().withS("foo"), encryptedAttributes.get("newAttribute"));
    params = FakeParameters.getInstance(
            SignOnlyWithUnknownAttributeAnnotation.class, encryptedAttributes, null,
            TABLE_NAME, HASH_KEY, RANGE_KEY);
    encryptedAttributes.get("newAttribute").setS("bar");
    encryptor.untransform(params);
}
 
Example #10
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getItemCommittedInsert() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValue> key1 = newKey(INTEG_HASH_TABLE_NAME);
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(key1);
    item1.put("asdf", new AttributeValue("wef"));
    
    t1.putItem(new PutItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withItem(item1));
    
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    Map<String, AttributeValue> item = manager.getItem(new GetItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key1), IsolationLevel.COMMITTED).getItem();
    assertNull(item);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key1, item1, t1.getId(), true, true);
    
    t1.rollback();
}
 
Example #11
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void updateItemAllNewOverwrite() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> item1 = new HashMap<String, AttributeValue>(item0);
    item1.put("asdf", new AttributeValue("wef"));
    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put("asdf", new AttributeValueUpdate().withAction(AttributeAction.PUT).withValue(new AttributeValue("wef")));
    
    Map<String, AttributeValue> result1 = t1.updateItem(new UpdateItemRequest()
        .withTableName(INTEG_HASH_TABLE_NAME)
        .withKey(key0)
        .withAttributeUpdates(updates)
        .withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item1, t1.getId(), false, true);
    assertEquals(result1, item1);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item1, true);
}
 
Example #12
Source File: AbstractDynamoDBQueryCriteria.java    From spring-data-dynamodb with Apache License 2.0 6 votes vote down vote up
protected Condition createSingleValueCondition(String propertyName, ComparisonOperator comparisonOperator, Object o,
		Class<?> propertyType, boolean alreadyMarshalledIfRequired) {

	Assert.notNull(o, "Creating conditions on null property values not supported: please specify a value for '"
			+ propertyName + "'");

	Object attributeValue = !alreadyMarshalledIfRequired ? getPropertyAttributeValue(propertyName, o) : o;

	boolean marshalled = !alreadyMarshalledIfRequired && attributeValue != o
			&& !entityInformation.isCompositeHashAndRangeKeyProperty(propertyName);

	Class<?> targetPropertyType = marshalled ? String.class : propertyType;
	List<AttributeValue> attributeValueList = new ArrayList<AttributeValue>();
	attributeValueList = addAttributeValue(attributeValueList, attributeValue, propertyName, targetPropertyType, true);
	return new Condition().withComparisonOperator(comparisonOperator).withAttributeValueList(attributeValueList);

}
 
Example #13
Source File: DynamoDBOperations.java    From geowave with Apache License 2.0 6 votes vote down vote up
private ScanResult getResults(
    final String tableName,
    final short adapterId,
    final List<GeoWaveRow> resultList,
    final Map<String, AttributeValue> lastEvaluatedKey) {
  final ScanRequest request = new ScanRequest(tableName);
  if ((lastEvaluatedKey != null) && !lastEvaluatedKey.isEmpty()) {
    request.setExclusiveStartKey(lastEvaluatedKey);
  }
  final ScanResult result = client.scan(request);
  result.getItems().forEach(objMap -> {
    final byte[] dataId = objMap.get(DynamoDBRow.GW_PARTITION_ID_KEY).getB().array();
    final AttributeValue valueAttr = objMap.get(DynamoDBRow.GW_VALUE_KEY);
    final byte[] value = valueAttr == null ? null : valueAttr.getB().array();
    final AttributeValue visAttr = objMap.get(DynamoDBRow.GW_VISIBILITY_KEY);
    final byte[] vis = visAttr == null ? new byte[0] : visAttr.getB().array();

    resultList.add(DataIndexUtils.deserializeDataIndexRow(dataId, adapterId, value, vis));
  });
  return result;
}
 
Example #14
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getThenUpdateExistingItem() {
    Transaction t1 = manager.newTransaction();
    
    Map<String, AttributeValue> item0a = new HashMap<String, AttributeValue>(item0);
    item0a.put("wef", new AttributeValue("new attr"));
    
    Map<String, AttributeValueUpdate> updates1 = new HashMap<String, AttributeValueUpdate>();
    updates1.put("wef", new AttributeValueUpdate(new AttributeValue("new attr"), AttributeAction.PUT));
    
    Map<String, AttributeValue> getResult = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    assertEquals(item0, getResult);
    
    Map<String, AttributeValue> updateResult = t1.updateItem(new UpdateItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)
            .withAttributeUpdates(updates1).withReturnValues(ReturnValue.ALL_NEW)).getAttributes();
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0a, t1.getId(), false, true);
    assertEquals(item0a, updateResult);
    
    t1.commit();
    
    assertItemNotLocked(INTEG_HASH_TABLE_NAME, key0, item0a, true);
}
 
Example #15
Source File: DelegatedEncryptionTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void RsaSignedOnly() throws GeneralSecurityException {
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    encryptor = DynamoDBEncryptor.getInstance(
            new SymmetricStaticProvider(encryptionKey, sigPair,
                    Collections.<String, String>emptyMap()), "encryptor-");

    Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    Map<String, AttributeValue> decryptedAttributes =
            encryptor.decryptAllFieldsExcept(encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
    assertThat(decryptedAttributes, AttrMatcher.match(attribs));

    // Make sure keys and version are not encrypted
    assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
    assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
    assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));

    // Make sure String has not been encrypted (we'll assume the others are correct as well)
    assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
 
Example #16
Source File: AttributeEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = DynamoDBMappingException.class)
public void badVersionNumber() {
    Parameters<BaseClass> params = FakeParameters.getInstance(BaseClass.class, attribs, null,
            TABLE_NAME, HASH_KEY, RANGE_KEY);
    Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
    ByteBuffer materialDescription = encryptedAttributes.get(
            encryptor.getEncryptor().getMaterialDescriptionFieldName()).getB();
    byte[] rawArray = materialDescription.array();
    assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version.
    rawArray[0] = 100;
    encryptedAttributes.put(encryptor.getEncryptor().getMaterialDescriptionFieldName(),
            new AttributeValue().withB(ByteBuffer.wrap(rawArray)));
    params = FakeParameters.getInstance(BaseClass.class, encryptedAttributes, null, TABLE_NAME,
            HASH_KEY, RANGE_KEY);
    encryptor.untransform(params);
}
 
Example #17
Source File: TransactionsIntegrationTest.java    From dynamodb-transactions with Apache License 2.0 6 votes vote down vote up
@Test
public void getItemWithDelete() {
    Transaction t1 = manager.newTransaction();
    Map<String, AttributeValue> getResult1 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertEquals(getResult1, item0);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    
    t1.deleteItem(new DeleteItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0));
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    
    Map<String, AttributeValue> getResult2 = t1.getItem(new GetItemRequest().withTableName(INTEG_HASH_TABLE_NAME).withKey(key0)).getItem();
    assertNull(getResult2);
    assertItemLocked(INTEG_HASH_TABLE_NAME, key0, item0, t1.getId(), false, false);
    
    t1.commit();
}
 
Example #18
Source File: DynamoDBUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static byte[] getVisibility(final Map<String, AttributeValue> map) {
  final AttributeValue v = map.get(DynamoDBOperations.METADATA_VISIBILITY_KEY);
  if (v != null) {
    return v.getB().array();
  }
  return null;
}
 
Example #19
Source File: DynamoDBUnmarshallerUtil.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
public static NSUnmarshaller getByteNSUnmarshaller() {
    return new NSUnmarshaller() {

        @Override
        public Object unmarshall(final AttributeValue value) {
            final Set<Byte> argument = new HashSet<Byte>();
            for (final String s : value.getNS()) {
                argument.add(Byte.parseByte(s));
            }
            return argument;
        }
    };
}
 
Example #20
Source File: DynamoDBEncryptor.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
/**
 * @see #decryptAllFieldsExcept(Map, EncryptionContext, String...)
 */
public Map<String, AttributeValue> decryptAllFieldsExcept(
        Map<String, AttributeValue> itemAttributes,
        EncryptionContext context, Collection<String> doNotDecrypt)
        throws GeneralSecurityException {
    Map<String, Set<EncryptionFlags>> attributeFlags = allDecryptionFlagsExcept(
            itemAttributes, doNotDecrypt);
    return decryptRecord(itemAttributes, attributeFlags, context);
}
 
Example #21
Source File: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = SignatureException.class)
public void macChangedAssociatedData() throws GeneralSecurityException {
    Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
    Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>();

    itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
    attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key2", new AttributeValue().withN("100"));
    attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[]{0, 1, 2, 3})));
    attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
    byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[]{3, 2, 1}, macKey);

    signerRsa.verifySignature(itemAttributes, attributeFlags, new byte[]{1, 2, 3}, macKey, ByteBuffer.wrap(signature));
}
 
Example #22
Source File: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void sigEcdsa() throws GeneralSecurityException {
    Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
    Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>();

    itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
    attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key2", new AttributeValue().withN("100"));
    attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[]{0, 1, 2, 3})));
    attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
    byte[] signature = signerEcdsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyEcdsa);

    signerEcdsa.verifySignature(itemAttributes, attributeFlags, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature));
}
 
Example #23
Source File: TransactionManager.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
public GetItemResult getItem(GetItemRequest request, IsolationLevel isolationLevel) {
    if (request.getAttributesToGet() != null) {
        Set<String> attributesToGet = new HashSet<String>(request.getAttributesToGet());
        attributesToGet.addAll(Transaction.SPECIAL_ATTR_NAMES);
        request.setAttributesToGet(attributesToGet);
    }
    GetItemResult result = getClient().getItem(request);
    Map<String, AttributeValue> item = getReadIsolationHandler(isolationLevel).handleItem(result.getItem(), request.getAttributesToGet(), request.getTableName());
    Transaction.stripSpecialAttributes(item);
    result.setItem(item);
    return result;
}
 
Example #24
Source File: DirectKmsMaterialProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleWithKmsEc() throws GeneralSecurityException {
    DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);

    Map<String, AttributeValue> attrVals = new HashMap<>();
    attrVals.put("hk", new AttributeValue("HashKeyValue"));
    attrVals.put("rk", new AttributeValue("RangeKeyValue"));

    ctx = new EncryptionContext.Builder().withHashKeyName("hk").withRangeKeyName("rk")
            .withTableName("KmsTableName").withAttributeValues(attrVals).build();
    EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
    SecretKey encryptionKey = eMat.getEncryptionKey();
    assertNotNull(encryptionKey);
    Key signingKey = eMat.getSigningKey();
    assertNotNull(signingKey);
    Map<String, String> kmsCtx = kms.getSingleEc();
    assertEquals("HashKeyValue", kmsCtx.get("hk"));
    assertEquals("RangeKeyValue", kmsCtx.get("rk"));
    assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*"));

    EncryptionContext dCtx = new EncryptionContext.Builder(ctx(eMat)).withHashKeyName("hk")
            .withRangeKeyName("rk").withTableName("KmsTableName").withAttributeValues(attrVals)
            .build();

    DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx);
    assertEquals(encryptionKey, dMat.getDecryptionKey());
    assertEquals(signingKey, dMat.getVerificationKey());
}
 
Example #25
Source File: DynamoDBDynamicFaultInjection.java    From aws-dynamodb-examples with Apache License 2.0 5 votes vote down vote up
private static Map<String, AttributeValue> newItem(String name, int year, String rating, String... fans)
{
    Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
    item.put("name", new AttributeValue(name));
    item.put("year", new AttributeValue().withN(Integer.toString(year)));
    item.put("rating", new AttributeValue(rating));
    item.put("fans", new AttributeValue().withSS(fans));

    return item;
}
 
Example #26
Source File: QueryITCase.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that exception should be raised when user provides an index name
 * when making query with the primary range key.
 */
@Test
public void testUnnecessaryIndexNameException() {
    try {
        DynamoDBMapper mapper = TestDynamoDBMapperFactory
                .createDynamoDBMapper(dynamo);
        long hashKey = System.currentTimeMillis();
        RangeKeyTestClass keyObject = new RangeKeyTestClass();
        keyObject.setKey(hashKey);
        DynamoDBQueryExpression<RangeKeyTestClass> queryExpression = new DynamoDBQueryExpression<RangeKeyTestClass>()
                .withHashKeyValues(keyObject);
        queryExpression
                .withRangeKeyCondition(
                        "rangeKey",
                        new Condition().withComparisonOperator(
                                ComparisonOperator.GT.toString())
                                .withAttributeValueList(
                                        new AttributeValue().withN("1.0")))
                .withLimit(11).withIndexName("some_index");
        mapper.query(RangeKeyTestClass.class, queryExpression);
        fail("User should not provide index name when making query with the primary range key");
    } catch (IllegalArgumentException expected) {
        System.out.println(expected.getMessage());
    } catch (Exception e) {
        fail("Should trigger AmazonClientException.");
    }

}
 
Example #27
Source File: DynamoDBSignerTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test
public void sig() throws GeneralSecurityException {
    Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
    Map<String, Set<EncryptionFlags>> attributeFlags = new HashMap<String, Set<EncryptionFlags>>();

    itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
    attributeFlags.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key2", new AttributeValue().withN("100"));
    attributeFlags.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
    itemAttributes.put("Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[]{0, 1, 2, 3})));
    attributeFlags.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
    byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeFlags, new byte[0], privKeyRsa);

    signerRsa.verifySignature(itemAttributes, attributeFlags, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
 
Example #28
Source File: DeviceAuthentication.java    From amazon-cognito-developer-authentication-sample with Apache License 2.0 5 votes vote down vote up
/**
 * Returns device info for given device ID (UID)
 * 
 * @param uid
 *            Unique device identifier
 * @return device info for the given uid
 */
public DeviceInfo getDeviceInfo(String uid) throws DataAccessException {
    HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
    key.put(ATTRIBUTE_UID, new AttributeValue().withS(uid));

    GetItemRequest getItemRequest = new GetItemRequest()
            .withTableName(DEVICE_TABLE)
            .withKey(key);

    try {
        return DeviceInfo.fromData(ddb.getItem(getItemRequest).getItem());
    } catch (AmazonClientException e) {
        throw new DataAccessException("Failed to get device: " + uid, e);
    }
}
 
Example #29
Source File: DynamoDBEncryptorTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = SignatureException.class)
public void RsaSignedOnlyBadSignature() throws GeneralSecurityException {
    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    rsaGen.initialize(2048, Utils.getRng());
    KeyPair sigPair = rsaGen.generateKeyPair();
    encryptor = DynamoDBEncryptor.getInstance(
            new SymmetricStaticProvider(encryptionKey, sigPair,
                    Collections.<String, String>emptyMap()), "encryptor-");

    Map<String, AttributeValue> encryptedAttributes = encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
    assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
    encryptedAttributes.get("hashKey").setN("666");
    encryptor.decryptAllFieldsExcept(encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
 
Example #30
Source File: TransactionDynamoDBFacadeTest.java    From dynamodb-transactions with Apache License 2.0 5 votes vote down vote up
@Test
public void testCheckExpectedBinaryValueWithMatchingItem() {
    Map<String, AttributeValue> item = Collections.singletonMap("Foo", new AttributeValue().withB(ByteBuffer.wrap(new byte[] { 1, 127, -127 })));
    Map<String, ExpectedAttributeValue> expected = Collections.singletonMap("Foo", new ExpectedAttributeValue(new AttributeValue().withB(ByteBuffer.wrap(new byte[] { 1, 127, -127 }))));

    TransactionDynamoDBFacade.checkExpectedValues(expected, item);
    // no exception expected
}