KOpenSSL.kt 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
* Copyright 2020 Matthew Nelson
*
* https://github.com/05nelsonm
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* */
package com.samourai.wallet.crypto

20 21
import org.bouncycastle.crypto.digests.SHA256Digest
import org.bouncycastle.crypto.params.KeyParameter
22 23 24 25 26 27 28 29 30 31
import java.nio.ByteBuffer
import java.nio.charset.Charset
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import java.security.spec.InvalidKeySpecException
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
32 33 34
import org.bouncycastle.util.encoders.Base64
import org.bouncycastle.util.encoders.DecoderException
import org.bouncycastle.util.encoders.EncoderException
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

/**
 * Methods for encrypting/decrypting data in a manner compliant with OpenSSL such that
 * they can be used interchangeably.
 *
 * OpenSSL Encryption from command line:
 *
 *   echo "Hello World!" | openssl aes-256-cbc -e -a -p -salt -pbkdf2 -iter 25000 -k password
 *
 * Terminal output (-p shows the following):
 *   salt=F71F01EC4171ACDF
 *   key=AF9344D72520323D210C440BA015526DABA0D22AD6247DFACF7D3F5B0F724A23
 *   iv =1125D64C744EDE615CE3B8AD55C1581C
 *   U2FsdGVkX1/3HwHsQXGs37PixswoJihPWATaxph4OVQ=
 *
 * OpenSSL Decryption from command line:
 *
 *   echo "U2FsdGVkX1/3HwHsQXGs37PixswoJihPWATaxph4OVQ=" | openssl aes-256-cbc -d -a -p -salt -pbkdf2 -iter 25000 -k password
 * */
class KOpenSSL {

    companion object {
        const val SALTED = "Salted__"

        @JvmStatic
        fun isSalted(chars: CharSequence): Boolean {
            return try {
62
                Base64
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
                        .decode(chars.lines().joinToString(""))
                        .copyOfRange(0, 8)
                        .contentEquals(SALTED.toByteArray())
            } catch (e: Exception) {
                false
            }
        }

        @JvmStatic
        fun isValidUTF8(input: ByteArray): Boolean {
            return try {
                Charset.forName("UTF-8").newDecoder().decode(ByteBuffer.wrap(input))
                true
            } catch (e: CharacterCodingException) {
                false
            }
        }
    }

    /**
     * Decrypts a string value.
     *
     * @throws [ArrayIndexOutOfBoundsException] IvParameterSpec argument passed has negative length
     * @throws [BadPaddingException]
87
     * @throws [CancellationException] if coroutine is cancelled
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
     * @throws [CharacterCodingException] if decryption failed and bytes were not valid UTF-8,
     *   most probably due to a bad password or incorrect hash iterations
     * @throws [IllegalArgumentException] if the input is not a valid Base64 encoded string,
     *   there is an error copying byte ranges, parameters for obtaining the KeySpec were not met,
     *   parameters for obtaining the IvParameterSpec were not met, parameters for obtaining the
     *   SecretKeySpec were not met
     * @throws [IllegalBlockSizeException]
     * @throws [IndexOutOfBoundsException] if error when copying byte ranges
     * @throws [InvalidAlgorithmParameterException]
     * @throws [InvalidKeyException] if the SecretKey used in Cipher.init is invalid
     * @throws [InvalidKeySpecException] if the SecretKey could not be generated
     * @throws [NoSuchAlgorithmException] if PBKDF2WithHmacSHA256, or AES/CBC/NoPadding algo could
     *   not be retrieved
     * @throws [NoSuchPaddingException] if AES/CBC/NoPadding could not be retrieved
     * */
    @Throws(
            ArrayIndexOutOfBoundsException::class,
            BadPaddingException::class,
            CharacterCodingException::class,
107
            DecoderException::class,
108 109 110 111 112 113 114 115 116 117 118 119 120 121
            IllegalArgumentException::class,
            IllegalBlockSizeException::class,
            IndexOutOfBoundsException::class,
            InvalidAlgorithmParameterException::class,
            InvalidKeyException::class,
            InvalidKeySpecException::class,
            NoSuchAlgorithmException::class,
            NoSuchPaddingException::class,
    )
    @JvmOverloads
    fun decrypt_AES256CBC_PBKDF2_HMAC_SHA256(
            password: String,
            hashIterations: Int,
            stringToDecrypt: String,
122
            printDetails: Boolean = false,
123
    ): String {
124
        val encryptedBytes = Base64.decode(stringToDecrypt.lines().joinToString(""))
125 126 127

        // Salt is bytes 8 - 15
        val salt = encryptedBytes.copyOfRange(8, 16)
128
        if (printDetails) {
129
            println("Salt: ${salt.joinToString("") { "%02X".format(it) }}")
130
        }
131 132

        // Derive 48 byte key
133 134 135 136
        val components = getSecretKeyComponents(password, salt, hashIterations)
        if (printDetails) {
            println("Key: ${components.key.joinToString("") { "%02X".format(it) }}")
            println("IV: ${components.iv.joinToString("") { "%02X".format(it) }}")
137 138 139 140 141 142 143
        }

        // Cipher Text is bytes 16 - end of the encrypted bytes
        val cipherText = encryptedBytes.copyOfRange(16, encryptedBytes.size)

        // Decrypt the Cipher Text and manually remove padding after
        val cipher = Cipher.getInstance("AES/CBC/NoPadding")
144 145 146 147 148 149
        cipher.init(Cipher.DECRYPT_MODE, components.getSecretKeySpec(), components.getIvParameterSpec())
        val decrypted = try {
            cipher.doFinal(cipherText)
        } finally {
            components.clearValues()
        }
150

151
        if (!isValidUTF8(decrypted)) {
152
            throw CharacterCodingException()
153
        }
154 155 156 157

        // Last byte of the decrypted text is the number of padding bytes needed to remove
        val plaintext = decrypted.copyOfRange(0, decrypted.size - decrypted.last().toInt())

158 159 160 161 162 163
        return plaintext.toString(Charsets.UTF_8).trim()
                .also {
                    if (printDetails) {
                        println(it)
                    }
                }
164 165 166 167 168 169 170 171
    }

    /**
     * Encrypts a string value.
     *
     * @throws [ArrayIndexOutOfBoundsException] IvParameterSpec argument passed has negative length
     * @throws [AssertionError] there is an error encoding to Base64
     * @throws [BadPaddingException]
172
     * @throws [CancellationException] if coroutine is cancelled
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
     * @throws [IllegalArgumentException] there is an error encoding to Base64, there is an error
     *   copying byte ranges, parameters for obtaining the KeySpec were not met, parameters for
     *   obtaining the IvParameterSpec were not met, parameters for obtaining the SecretKeySpec
     *   were not met
     * @throws [IllegalBlockSizeException]
     * @throws [IndexOutOfBoundsException] if error when copying byte ranges
     * @throws [InvalidAlgorithmParameterException]
     * @throws [InvalidKeyException] if the SecretKey used in Cipher.init is invalid
     * @throws [InvalidKeySpecException] if the SecretKey could not be generated
     * @throws [NoSuchAlgorithmException] if PBKDF2WithHmacSHA256, or AES/CBC/PKCS5Padding algo
     *   could not be retrieved
     * @throws [NoSuchPaddingException] if AES/CBC/NoPadding could not be retrieved
     * */
    @Throws(
            ArrayIndexOutOfBoundsException::class,
            AssertionError::class,
            BadPaddingException::class,
190
            EncoderException::class,
191 192 193 194 195 196 197 198 199 200 201 202 203 204
            IllegalArgumentException::class,
            IllegalBlockSizeException::class,
            IndexOutOfBoundsException::class,
            InvalidAlgorithmParameterException::class,
            InvalidKeyException::class,
            InvalidKeySpecException::class,
            NoSuchAlgorithmException::class,
            NoSuchPaddingException::class
    )
    @JvmOverloads
    fun encrypt_AES256CBC_PBKDF2_HMAC_SHA256(
            password: String,
            hashIterations: Int,
            stringToEncrypt: String,
205
            printDetails: Boolean = false,
206 207
    ): String {
        val salt = SecureRandom().generateSeed(8)
208
        if (printDetails) {
209
            println("Salt: ${salt.joinToString("") { "%02X".format(it) }}")
210
        }
211 212

        // Derive 48 byte key
213 214 215 216
        val components = getSecretKeyComponents(password, salt, hashIterations)
        if (printDetails) {
            println("Key: ${components.key.joinToString("") { "%02X".format(it) }}")
            println("IV: ${components.iv.joinToString("") { "%02X".format(it) }}")
217 218 219
        }

        val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
220 221 222 223 224 225
        cipher.init(Cipher.ENCRYPT_MODE, components.getSecretKeySpec(), components.getIvParameterSpec())
        val cipherText = try {
            cipher.doFinal(stringToEncrypt.toByteArray())
        } finally {
            components.clearValues()
        }
226

227 228 229 230 231
        return Base64.encode(SALTED.toByteArray() + salt + cipherText)
                .decodeToString()
                .replace("(.{64})".toRegex(), "$1\n")
                .also {
                    if (printDetails) {
232
                        println(it)
233
                    }
234 235
                }
    }
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

    private class SecretKeyComponents(val key: ByteArray, val iv: ByteArray) {

        fun getSecretKeySpec(): SecretKeySpec =
                SecretKeySpec(key, "AES")

        fun getIvParameterSpec(): IvParameterSpec =
                IvParameterSpec(iv)

        fun clearValues() {
            key.fill('*'.toByte())
            iv.fill('*'.toByte())
        }
    }

    private fun getSecretKeyComponents(
            password: String,
            salt: ByteArray,
            hashIterations: Int
    ): SecretKeyComponents =
            PKCS5S2ParametersGeneratorKtx(SHA256Digest()).let { generator ->
                generator.init(password.toByteArray(), salt, hashIterations)
                (generator.generateDerivedMacParametersKtx(48 * 8) as KeyParameter).key.let { secretKey ->
                    SecretKeyComponents(
                            // Decryption Key is bytes 0 - 31 of the derived secret key
                            key = secretKey.copyOfRange(0, 32),

                            // Input Vector is bytes 32 - 47 of the derived secret key
                            iv = secretKey.copyOfRange(32, secretKey.size)
                    ).also {
                        generator.password.fill('*'.toByte())
                        secretKey.fill('*'.toByte())
                    }
                }
            }

272 273 274
}