com.amazonaws.encryptionsdk.exception.AwsCryptoException Java Examples

The following examples show how to use com.amazonaws.encryptionsdk.exception.AwsCryptoException. 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: DefaultCryptoMaterialsManagerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void decrypt_whenTrailingSigMissing_throwsException() throws Exception {
    for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) {
        if (algorithm.getTrailingSignatureLength() == 0) {
            continue;
        }

        EncryptionMaterials encryptMaterials = easyGenMaterials(
                builder -> builder.setRequestedAlgorithm(algorithm)
        );

        DecryptionMaterialsRequest request = DecryptionMaterialsRequest.newBuilder()
                                                                       .setEncryptedDataKeys(encryptMaterials.getEncryptedDataKeys())
                                                                       .setAlgorithm(algorithm)
                                                                       .setEncryptionContext(Collections.emptyMap())
                                                                       .build();

        try {
            new DefaultCryptoMaterialsManager(mk1).decryptMaterials(request);
            fail("expected exception");
        } catch (AwsCryptoException e) {
            // ok
            continue;
        }
    }
}
 
Example #2
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithDuplicateEntries() {
    final Map<String, String> ctx = Collections.singletonMap("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);
    // Don't duplicate the entry count
    final ByteBuffer dupCtxBuff = ByteBuffer.allocate((2 * ctxBytes.length) - 2);

    // Set to 2 entries
    dupCtxBuff.putShort((short) 2);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();
    // From here to the end is a single entry, copy it
    final byte[] entry = new byte[ctxBuff.remaining()];
    ctxBuff.get(entry);

    dupCtxBuff.put(entry);
    dupCtxBuff.put(entry);

    EncryptionContextSerializer.deserialize(dupCtxBuff.array());
}
 
Example #3
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithShortValue() {
    final Map<String, String> ctx = new HashMap<String, String>();
    ctx.put("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();

    // Pull out key length and bytes.
    final short keyLen = ctxBuff.getShort();
    final byte[] key = new byte[keyLen];
    ctxBuff.get(key);

    // Overwrite value length
    ctxBuff.putShort((short) 0);

    // The actual call which should fail
    EncryptionContextSerializer.deserialize(ctxBuff.array());
}
 
Example #4
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 #5
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithLargeValue() {
    final Map<String, String> ctx = new HashMap<String, String>();
    ctx.put("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();

    // Pull out key length and bytes.
    final short keyLen = ctxBuff.getShort();
    final byte[] key = new byte[keyLen];
    ctxBuff.get(key);

    // Overwrite value length
    ctxBuff.putShort((short) Constants.UNSIGNED_SHORT_MAX_VAL);

    // The actual call which should fail
    EncryptionContextSerializer.deserialize(ctxBuff.array());
}
 
Example #6
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithShortKey() {
    final Map<String, String> ctx = new HashMap<String, String>();
    ctx.put("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();
    // Overwrite key length with 0
    ctxBuff.putShort((short) 0);

    // The actual call which should fail
    EncryptionContextSerializer.deserialize(ctxBuff.array());
}
 
Example #7
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 #8
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 #9
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithNegativeValue() {
    final Map<String, String> ctx = new HashMap<String, String>();
    ctx.put("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();

    // Pull out key length and bytes.
    final short keyLen = ctxBuff.getShort();
    final byte[] key = new byte[keyLen];
    ctxBuff.get(key);

    // Overwrite value length
    ctxBuff.putShort((short) -1);

    // The actual call which should fail
    EncryptionContextSerializer.deserialize(ctxBuff.array());
}
 
Example #10
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the master key provider.
 * @return
 */
public KmsMasterKeyProvider build() {
    // If we don't have a default region, we need to check that all key IDs will be usable
    if (defaultRegion_ == null) {
        for (String keyId : keyIds_) {
            if (parseRegionfromKeyArn(keyId) == null) {
                throw new AwsCryptoException("Can't use non-ARN key identifiers or aliases when " +
                                                     "no default region is set");
            }
        }
    }

    RegionalClientSupplier supplier = clientFactory();

    return new KmsMasterKeyProvider(supplier, defaultRegion_, keyIds_, emptyList(), false);
}
 
Example #11
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 #12
Source File: KMSEncryptor.java    From strongbox with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] decrypt(byte[] ciphertext, EncryptionContext context) {
    try {
        final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(getProvider(), ciphertext);

        verify(decryptResult, context);

        return decryptResult.getResult();
    } catch (AwsCryptoException e) {
        if (isInvalidKeyException(e)) {
            throw new UnlimitedEncryptionNotSetException();
        } else {
            throw e;
        }
    }
}
 
Example #13
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithNegativeKey() {
    final Map<String, String> ctx = new HashMap<String, String>();
    ctx.put("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();
    // Overwrite key length with -1.
    ctxBuff.putShort((short) -1);

    // The actual call which should fail
    EncryptionContextSerializer.deserialize(ctxBuff.array());
}
 
Example #14
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 #15
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void contextWithLargeKey() {
    final Map<String, String> ctx = new HashMap<String, String>();
    ctx.put("Alice:", "trusts Bob");

    final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx));
    final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes);

    // Pull out entry count to move to key pos
    ctxBuff.getShort();
    // Overwrite key length
    ctxBuff.putShort((short) Constants.UNSIGNED_SHORT_MAX_VAL);

    // The actual call which should fail
    EncryptionContextSerializer.deserialize(ctxBuff.array());
}
 
Example #16
Source File: CipherFrameHeaders.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize the header into a byte array.
 * 
 * @return
 *         the serialized bytes of the header.
 */
public byte[] toByteArray() {
    try {
        ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
        DataOutputStream dataStream = new DataOutputStream(outBytes);

        if (isFinalFrame_) {
            dataStream.writeInt(Constants.ENDFRAME_SEQUENCE_NUMBER);
        }

        dataStream.writeInt(sequenceNumber_);
        dataStream.write(nonce_);

        if (includeFrameSize_ || isFinalFrame_) {
            dataStream.writeInt(frameContentLength_);
        }

        dataStream.close();
        return outBytes.toByteArray();
    } catch (IOException e) {
        throw new AwsCryptoException("Failed to serialize cipher frame headers", e);
    }
}
 
Example #17
Source File: KeyBlob.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Set the information on the key provider identifier.
 * 
 * @param keyProviderInfo
 *            the bytes containing information on the key provider
 *            identifier.
 */
//@ public normal_behavior
//@   requires !isDeserializing;
//@   requires keyProviderInfo != null && keyProviderInfo.length <= Constants.UNSIGNED_SHORT_MAX_VAL;
//@   assignable providerInformation;
//@   ensures \fresh(providerInformation);
//@   ensures Arrays.equalArrays(providerInformation, keyProviderInfo);
//@ also
//@ private normal_behavior  // TODO: this behavior is a temporary workaround
//@   requires !isDeserializing;
//@   requires keyProviderInfo != null && keyProviderInfo.length <= Constants.UNSIGNED_SHORT_MAX_VAL;
//@   assignable keyProviderInfo_, keyProviderInfoLen_;
//@ also private exceptional_behavior
//@   requires !isDeserializing;
//@   requires keyProviderInfo != null;
//@   requires keyProviderInfo.length > Constants.UNSIGNED_SHORT_MAX_VAL;
//@   assignable \nothing;
//@   signals_only AwsCryptoException;
public void setKeyProviderInfo(final byte[] keyProviderInfo) {
    if (keyProviderInfo.length > Constants.UNSIGNED_SHORT_MAX_VAL) {
        throw new AwsCryptoException(
                "Key provider identifier information length exceeds the max value of an unsigned short primitive.");
    }
    keyProviderInfo_ = keyProviderInfo.clone();
    keyProviderInfoLen_ = keyProviderInfo.length;
}
 
Example #18
Source File: KeyBlob.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Set the encrypted data key.
 * 
 * @param encryptedDataKey
 *            the bytes containing the encrypted data key.
 */
//@ public normal_behavior
//@   requires !isDeserializing;
//@   requires encryptedDataKey != null && encryptedDataKey.length <= Constants.UNSIGNED_SHORT_MAX_VAL;
//@   assignable this.encryptedDataKey;
//@   ensures \fresh(this.encryptedDataKey);
//@   ensures Arrays.equalArrays(this.encryptedDataKey, encryptedDataKey);
//@ also
//@ private normal_behavior  // TODO: this behavior is a temporary workaround
//@   requires !isDeserializing;
//@   requires encryptedDataKey != null && encryptedDataKey.length <= Constants.UNSIGNED_SHORT_MAX_VAL;
//@   assignable encryptedKey_, encryptedKeyLen_;
//@ also
//@ public exceptional_behavior
//@   requires !isDeserializing;
//@   requires encryptedDataKey != null;
//@   requires encryptedDataKey.length > Constants.UNSIGNED_SHORT_MAX_VAL;
//@   assignable \nothing;
//@   signals_only AwsCryptoException;
public void setEncryptedDataKey(final byte[] encryptedDataKey) {
    if (encryptedDataKey.length > Constants.UNSIGNED_SHORT_MAX_VAL) {
        throw new AwsCryptoException("Key length exceeds the max value of an unsigned short primitive.");
    }
    encryptedKey_ = encryptedDataKey.clone();
    encryptedKeyLen_ = encryptedKey_.length;
}
 
Example #19
Source File: EncryptionHandler.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Finish encryption of the plaintext bytes.
 * 
 * @param out
 *            space for any resulting output data.
 * @param outOff
 *            offset into out to start copying the data at.
 * @return number of bytes written into out.
 * @throws BadCiphertextException
 *             thrown by the underlying cipher handler.
 */
@Override
public int doFinal(final byte[] out, final int outOff) throws BadCiphertextException {
    if (complete_) {
        throw new IllegalStateException("Attempted to call doFinal twice");
    }

    complete_ = true;

    checkPlaintextSizeLimit(0);

    int written = contentCryptoHandler_.doFinal(out, outOff);
    updateTrailingSignature(out, outOff, written);
    if (cryptoAlgo_.getTrailingSignatureLength() > 0) {
        try {
            CiphertextFooters footer = new CiphertextFooters(signContent());
            byte[] fBytes = footer.toByteArray();
            System.arraycopy(fBytes, 0, out, outOff + written, fBytes.length);
            return written + fBytes.length;
        } catch (final SignatureException ex) {
            throw new AwsCryptoException(ex);
        }
    } else {
        return written;
    }
}
 
Example #20
Source File: CiphertextHeaders.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize the header fields into a byte array. This method serializes all
 * the header fields including the header nonce and tag.
 * 
 * @return
 *         the serialized bytes of the entire header.
 */
public byte[] toByteArray() {
    if (headerNonce_ == null || headerTag_ == null) {
        throw new AwsCryptoException("Header nonce and tag cannot be null.");
    }

    final byte[] serializedFields = serializeAuthenticatedFields();
    final int outLen = serializedFields.length + headerNonce_.length + headerTag_.length;
    final ByteBuffer serializedBytes = ByteBuffer.allocate(outLen);

    serializedBytes.put(serializedFields);
    serializedBytes.put(headerNonce_);
    serializedBytes.put(headerTag_);

    return serializedBytes.array();
}
 
Example #21
Source File: CipherBlockHeaders.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Construct the single block headers using the provided nonce
 * and length of content.
 * 
 * @param nonce
 *            the bytes containing the nonce.
 * @param contentLen
 *            the length of the content in the block.
 */
//@ public normal_behavior
//@   requires nonce != null && nonce.length <= Constants.MAX_NONCE_LENGTH;
//@   ensures \fresh(nonce_) && nonce_.length == nonce.length;
//@   ensures Arrays.equalArrays(nonce_, nonce);
//@   ensures contentLength_ == contentLen;
//@   ensures nonceLength_ == 0;
//@   ensures isComplete_ == false;
//@ also private exceptional_behavior
//@   requires nonce == null || nonce.length > Constants.MAX_NONCE_LENGTH;
//@   signals_only AwsCryptoException;
//@ pure
public CipherBlockHeaders(/*@ nullable @*/ final byte[] nonce, final long contentLen) {
    if (nonce == null) {
        throw new AwsCryptoException("Nonce cannot be null.");
    }
    if (nonce.length > Constants.MAX_NONCE_LENGTH) {
        throw new AwsCryptoException(
                "Nonce length is greater than the maximum value of an unsigned byte.");
    }

    nonce_ = nonce.clone();
    contentLength_ = contentLen;
}
 
Example #22
Source File: JceKeyCipher.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypts the given key, incorporating the given keyName and encryptionContext.
 * @param key The key to encrypt.
 * @param keyName A UTF-8 encoded representing a name for the key.
 * @param keyNamespace A UTF-8 encoded value that namespaces the key.
 * @param encryptionContext A key-value mapping of arbitrary, non-secret, UTF-8 encoded strings used
 *                         during encryption and decryption to provide additional authenticated data (AAD).
 * @return The encrypted data key.
 */
public EncryptedDataKey encryptKey(final byte[] key, final String keyName, final String keyNamespace,
                                   final Map<String, String> encryptionContext) {

    final byte[] keyNameBytes = keyName.getBytes(KEY_NAME_ENCODING);

    try {
        final JceKeyCipher.WrappingData wData = buildWrappingCipher(wrappingKey, encryptionContext);
        final Cipher cipher = wData.cipher;
        final byte[] encryptedKey = cipher.doFinal(key);

        final byte[] provInfo;
        if (wData.extraInfo.length == 0) {
            provInfo = keyNameBytes;
        } else {
            provInfo = new byte[keyNameBytes.length + wData.extraInfo.length];
            System.arraycopy(keyNameBytes, 0, provInfo, 0, keyNameBytes.length);
            System.arraycopy(wData.extraInfo, 0, provInfo, keyNameBytes.length, wData.extraInfo.length);
        }

        return new KeyBlob(keyNamespace, provInfo, encryptedKey);
    } catch (final GeneralSecurityException gsex) {
        throw new AwsCryptoException(gsex);
    }
}
 
Example #23
Source File: DecryptionHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void maxLenProcessBytes() {
    final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create(masterKeyProvider_);
    // Create input of size 3 bytes: 1 byte containing version, 1 byte
    // containing type, and 1 byte containing half of the algoId short
    // primitive. Only 1 byte of the algoId is provided because this
    // forces the decryption handler to buffer that 1 byte while waiting for
    // the other byte. We do this so we can specify an input of max
    // value and the total bytes to parse will become max value + 1.
    final byte[] in = new byte[3];
    final byte[] out = new byte[3];
    in[1] = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA.getValue();

    decryptionHandler.processBytes(in, 0, in.length, out, 0);
    decryptionHandler.processBytes(in, 0, Integer.MAX_VALUE, out, 0);
}
 
Example #24
Source File: DefaultCryptoMaterialsManagerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void encrypt_whenNoMasterKeys_throws() throws Exception {
    EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder().build();

    new DefaultCryptoMaterialsManager(new MasterKeyProvider() {
        @Override public String getDefaultProviderId() {
            return "provider ID";
        }

        @Override public MasterKey getMasterKey(String provider, String keyId) throws UnsupportedProviderException,
                NoSuchMasterKeyException {
            throw new NoSuchMasterKeyException();
        }

        @Override public List getMasterKeysForEncryption(MasterKeyRequest request) {
            return Collections.emptyList();
        }

        @Override public DataKey decryptDataKey(
                CryptoAlgorithm algorithm, Collection encryptedDataKeys, Map encryptionContext
        ) throws UnsupportedProviderException, AwsCryptoException {
            return null;
        }
    }).getMaterialsForEncrypt(req);
}
 
Example #25
Source File: BlockDecryptionHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void decryptMaxContentLength() {
    final BlockEncryptionHandler blockEncryptionHandler = new BlockEncryptionHandler(
            dataKey_,
            nonceLen_,
            cryptoAlgorithm_,
            messageId_);
    final byte[] in = new byte[0];
    final int outLen = blockEncryptionHandler.estimateOutputSize(in.length);
    final byte[] out = new byte[outLen];

    blockEncryptionHandler.processBytes(in, 0, in.length, out, 0);
    blockEncryptionHandler.doFinal(out, 0);

    final ByteBuffer outBuff = ByteBuffer.wrap(out);
    // pull out nonce to get to content length.
    final byte[] nonce = new byte[nonceLen_];
    outBuff.get(nonce);
    // set content length to integer max value + 1.
    outBuff.putLong(Integer.MAX_VALUE + 1L);

    final int decryptedOutLen = blockDecryptionHandler_.estimateOutputSize(outLen);
    final byte[] decryptedOut = new byte[decryptedOutLen];
    blockDecryptionHandler_.processBytes(outBuff.array(), 0, outBuff.array().length, decryptedOut, 0);
}
 
Example #26
Source File: FrameDecryptionHandlerTest.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void processBytesCalledWhileComplete() {
    final FrameEncryptionHandler frameEncryptionHandler = new FrameEncryptionHandler(
            dataKey_,
            nonceLen_,
            cryptoAlgorithm_,
            messageId_,
            frameSize_);
    final byte[] in = new byte[0];
    final int outLen = frameEncryptionHandler.estimateOutputSize(in.length);
    final byte[] out = new byte[outLen];

    frameEncryptionHandler.processBytes(in, 0, in.length, out, 0);
    frameEncryptionHandler.doFinal(out, 0);

    final byte[] decryptedOut = new byte[outLen];

    frameDecryptionHandler_.processBytes(out, 0, out.length, decryptedOut, 0);
    frameDecryptionHandler_.processBytes(out, 0, out.length, decryptedOut, 0);
}
 
Example #27
Source File: CipherFrameHeaders.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Construct the frame headers using the provided sequence number, nonce,
 * length of content, and boolean value indicating if it is the final frame.
 * 
 * @param sequenceNumber
 *            the sequence number of the frame
 * @param nonce
 *            the bytes containing the nonce.
 * @param frameContentLen
 *            the length of the content in the frame.
 * @param isFinal
 *            boolean value indicating if it is the final frame.
 */
public CipherFrameHeaders(final int sequenceNumber, final byte[] nonce, final int frameContentLen,
        final boolean isFinal) {
    sequenceNumber_ = sequenceNumber;

    if (nonce == null) {
        throw new AwsCryptoException("Nonce cannot be null.");
    }
    if (nonce.length > Constants.MAX_NONCE_LENGTH) {
        throw new AwsCryptoException(
                "Nonce length is greater than the maximum value of an unsigned byte.");
    }

    nonce_ = nonce.clone();
    isFinalFrame_ = isFinal;
    frameContentLength_ = frameContentLen;
}
 
Example #28
Source File: EncContextSerializerTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void overlyLargeValue() {
    final int size = 10;
    final Map<String, String> ctx = new HashMap<String, String>(size);
    final char[] valueChars = new char[Short.MAX_VALUE + 1];
    final String value = new String(valueChars);

    for (int x = 0; x < size; x++) {
        ctx.put(UUID.randomUUID().toString(), value);
    }
    testMap(ctx);
}
 
Example #29
Source File: CiphertextHeadersTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void serializeWithNullHeaderTag() {
    final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(
            version_,
            type_,
            cryptoAlgo_,
            new byte[0],
            Collections.singletonList(keyBlob_),
            contentType_,
            frameSize_);
    ciphertextHeaders.setHeaderNonce(headerNonce_);

    ciphertextHeaders.toByteArray();
}
 
Example #30
Source File: CiphertextHeadersTest.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = AwsCryptoException.class)
public void serializeWithNullHeaderNonce() {
    final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(
            version_,
            type_,
            cryptoAlgo_,
            new byte[0],
            Collections.singletonList(keyBlob_),
            contentType_,
            frameSize_);
    ciphertextHeaders.setHeaderTag(headerTag_);

    ciphertextHeaders.toByteArray();
}