private SecretKey getNonCommittedEncryptionKey()

in src/main/java/com/amazonaws/encryptionsdk/CryptoAlgorithm.java [343:394]


  private SecretKey getNonCommittedEncryptionKey(
      final SecretKey dataKey, final CiphertextHeaders headers) throws InvalidKeyException {
    final String macAlgorithm;

    switch (this) {
      case ALG_AES_128_GCM_IV12_TAG16_NO_KDF:
      case ALG_AES_192_GCM_IV12_TAG16_NO_KDF:
      case ALG_AES_256_GCM_IV12_TAG16_NO_KDF:
        return dataKey;
      case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256:
      case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256:
      case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256:
      case ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256:
        macAlgorithm = "HmacSHA256";
        break;
      case ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384:
      case ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384:
        macAlgorithm = "HmacSHA384";
        break;
      default:
        throw new UnsupportedOperationException("Support for " + this + " not yet built.");
    }
    if (!dataKey.getFormat().equalsIgnoreCase("RAW")) {
      throw new InvalidKeyException(
          "Currently only RAW format keys are supported for HKDF algorithms. Actual format was "
              + dataKey.getFormat());
    }
    final byte[] messageId = headers.getMessageId();
    final ByteBuffer info = ByteBuffer.allocate(messageId.length + 2);
    info.order(ByteOrder.BIG_ENDIAN);
    info.putShort(getValue());
    info.put(messageId);

    final byte[] rawDataKey = dataKey.getEncoded();
    if (rawDataKey.length != getDataKeyLength()) {
      throw new InvalidKeyException(
          "DataKey of incorrect length. Expected "
              + getDataKeyLength()
              + " but was "
              + rawDataKey.length);
    }

    final HmacKeyDerivationFunction hkdf;
    try {
      hkdf = HmacKeyDerivationFunction.getInstance(macAlgorithm);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }

    hkdf.init(rawDataKey);
    return new SecretKeySpec(hkdf.deriveKey(info.array(), getKeyLength()), getKeyAlgo());
  }