public EncryptionMaterials getMaterialsForEncrypt()

in src/main/java/com/amazonaws/encryptionsdk/caching/CachingCryptoMaterialsManager.java [273:324]


  public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) {
    // We cannot correctly enforce size limits if the request has no known plaintext size, so bypass
    // the cache in
    // this case.
    if (request.getPlaintextSize() == -1) {
      return backingCMM.getMaterialsForEncrypt(request);
    }

    // Strip off information on the plaintext length & contents - we do this because we will be
    // (potentially)
    // reusing the result from the backing CMM across multiple requests, and as such it would be
    // misleading to pass on
    // the first such request's information to the backing CMM.

    EncryptionMaterialsRequest upstreamRequest =
        request.toBuilder().setPlaintext(null).setPlaintextSize(-1).build();

    byte[] cacheId = getCacheIdentifier(upstreamRequest);

    CryptoMaterialsCache.UsageStats increment = initialIncrementForRequest(request);

    // If our plaintext size is such that even a brand new entry would reach or exceed cache limits,
    // there's no
    // point in accessing the cache - in fact, doing so would poison a cache entry that could
    // potentially be still
    // used for a smaller request. So we'll bypass the cache and just call the backing CMM directly
    // in this case.
    if (increment.getBytesEncrypted() >= byteUseLimit) {
      return backingCMM.getMaterialsForEncrypt(request);
    }

    CryptoMaterialsCache.EncryptCacheEntry entry = cache.getEntryForEncrypt(cacheId, increment);
    if (entry != null
        && !isEntryExpired(entry.getEntryCreationTime())
        && !hasExceededLimits(entry.getUsageStats())) {
      return entry.getResult();
    } else if (entry != null) {
      // entry has potentially expired, so hint to the cache that it should be removed, in case the
      // cache stores
      // multiple entries or something
      entry.invalidate();
    }

    // Cache miss.
    EncryptionMaterials result = backingCMM.getMaterialsForEncrypt(request);

    if (result.getAlgorithm().isSafeToCache()) {
      cache.putEntryForEncrypt(cacheId, result, hint, initialIncrementForRequest(request));
    }

    return result;
  }