Create Facebook Conceal Crypto With User Supplied Password (Kotlin)

April 14, 2018

Create PasswordGeneratedKeyChain as shown by helios175.

class PasswordGeneratedKeyChain(private val mConfig: CryptoConfig) : KeyChain {
    private val mDerivation: PasswordBasedKeyDerivation
    private var mKey: ByteArray? = null

    init {
        // mDerivation = PasswordBasedKeyDerivation(AndroidConceal.get().nativeLibrary)
        mDerivation = AndroidConceal.get().createPasswordBasedKeyDerivation()
        mDerivation.keyLengthInBytes = mConfig.keyLength
    }


    /// implementing Key Chain
    override fun getCipherKey(): ByteArray {
        if (mKey == null) throw IllegalStateException("You need to call generate() first")
        return mKey as ByteArray
    }

    // key for mac
    // if you need mac you need a second derivation object
    override fun getMacKey(): ByteArray {
        throw UnsupportedOperationException("implemented only for encryption, not mac")
    }

    // this is just a glorified "get me a new nonce"
    override fun getNewIV(): ByteArray {
        val result = ByteArray(mConfig.ivLength)
        AndroidConceal.get().secureRandom.nextBytes(result)
        return result
    }

    override fun destroyKeys() {
        Arrays.fill(mKey, 0.toByte())
        mKey = null
    }

    // used only for encrypting, you will need to store it in the same place you're writing the encrypted content
    // used only for reading, it should read the salt from the same place the encrypted content is
    var salt: ByteArray
        get() = mDerivation.salt
        set(salt) {
            mDerivation.salt = salt
        }

    fun setPassword(pwd: String) {
        mDerivation.password = pwd
    }

    fun generate() {
        mKey = mDerivation.generate()
    }
}

To create the crypto.

val pgkc = PasswordGeneratedKeyChain(CryptoConfig.KEY_256)
pgkc.setPassword(password)
pgkc.salt = salt.toByteArray()
pgkc.generate()
val crypto = AndroidConceal.get().createDefaultCrypto(pgkc)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.