Created
June 6, 2017 16:18
-
-
Save pabloogc/c0d55300853e8cbf6798a43379b8a95a to your computer and use it in GitHub Desktop.
Fresco + Conceal, Image Loading with encrypted cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.facebook.binaryresource.BinaryResource | |
import com.facebook.cache.common.CacheKey | |
import com.facebook.cache.common.WriterCallback | |
import com.facebook.cache.disk.FileCache | |
import com.facebook.crypto.Crypto | |
import com.facebook.crypto.Entity | |
import java.io.InputStream | |
fun configureFresco() { | |
val frescoConfig = ImagePipelineConfig.newBuilder(context) | |
//... your configuration | |
.setFileCacheFactory { diskCacheConfig -> | |
val defaultFactory = DiskStorageCacheFactory(DynamicDefaultDiskStorageFactory()) | |
CryptoFileCache(crypto, defaultFactory.get(diskCacheConfig)) | |
} | |
.build() | |
Fresco.initialize(context, frescoConfig) | |
} | |
class CryptoFileCache(val crypto: Crypto, val delegate: FileCache) : FileCache by delegate { | |
override fun insert(key: CacheKey, realWriter: WriterCallback): BinaryResource { | |
return delegate.insert(key) { outputStream -> | |
val cipherOutputStream = crypto.getCipherOutputStream(outputStream, Entity.create(key.uriString)) | |
realWriter.write(cipherOutputStream) | |
//This is important, the delegate will only flush / close the incoming stream | |
cipherOutputStream.flush() | |
cipherOutputStream.close() | |
} | |
} | |
override fun getResource(key: CacheKey): BinaryResource? { | |
val encryptedResource = delegate.getResource(key) ?: return null | |
return object : BinaryResource { | |
//This size will be ~30 bytes off depending on Conceal algorithm (version + cypher + IV) | |
override fun size(): Long = encryptedResource.size() | |
override fun openStream(): InputStream { | |
return crypto.getCipherInputStream(encryptedResource.openStream(), Entity.create(key.uriString)) | |
} | |
override fun read(): ByteArray { | |
return crypto.decrypt(encryptedResource.read(), Entity.create(key.uriString)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment