summaryrefslogtreecommitdiff
path: root/common/src/main/kotlin/crypto/utils.kt
blob: 2f98e0646ff97af2a5a2b48322bea78c8bcceeca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2024 Taler Systems S.A.

 * LibEuFin is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation; either version 3, or
 * (at your option) any later version.

 * LibEuFin is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General
 * Public License for more details.

 * You should have received a copy of the GNU Affero General Public
 * License along with LibEuFin; see the file COPYING.  If not, see
 * <http://www.gnu.org/licenses/>
 */

package tech.libeufin.common.crypto

import org.bouncycastle.jce.provider.BouncyCastleProvider
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.math.BigInteger
import java.security.*
import java.security.interfaces.RSAPrivateCrtKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.*
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.PBEParameterSpec
import javax.crypto.spec.SecretKeySpec
import tech.libeufin.common.*

/**
 * Helpers for dealing with cryptographic operations in EBICS / LibEuFin.
 */
object CryptoUtil {
    // TODO split common and ebics crypto

    /**
     * RSA key pair.
     */
    data class RsaCrtKeyPair(val private: RSAPrivateCrtKey, val public: RSAPublicKey)

    // FIXME(dold): This abstraction needs to be improved.
    class EncryptionResult(
        val encryptedTransactionKey: ByteArray,
        val pubKeyDigest: ByteArray,
        val encryptedData: ByteArray,
        val plainTransactionKey: SecretKey
    )

    private val bouncyCastleProvider = BouncyCastleProvider()

    /**
     * Load an RSA private key from its binary PKCS#8 encoding.
     */
    fun loadRsaPrivateKey(encodedPrivateKey: ByteArray): RSAPrivateCrtKey {
        val spec = PKCS8EncodedKeySpec(encodedPrivateKey)
        val priv = KeyFactory.getInstance("RSA").generatePrivate(spec)
        if (priv !is RSAPrivateCrtKey)
            throw Exception("wrong encoding")
        return priv
    }

    /**
     * Load an RSA public key from its binary X509 encoding.
     */
    fun loadRsaPublicKey(encodedPublicKey: ByteArray): RSAPublicKey {
        val spec = X509EncodedKeySpec(encodedPublicKey)
        val pub = KeyFactory.getInstance("RSA").generatePublic(spec)
        if (pub !is RSAPublicKey)
            throw Exception("wrong encoding")
        return pub
    }

    /**
     * Load an RSA public key from its components.
     *
     * @param exponent
     * @param modulus
     * @return key
     */
    fun loadRsaPublicKeyFromComponents(modulus: ByteArray, exponent: ByteArray): RSAPublicKey {
        val modulusBigInt = BigInteger(1, modulus)
        val exponentBigInt = BigInteger(1, exponent)

        val keyFactory = KeyFactory.getInstance("RSA")
        val tmp = RSAPublicKeySpec(modulusBigInt, exponentBigInt)
        return keyFactory.generatePublic(tmp) as RSAPublicKey
    }

    /**
     * Load an RSA public key from its binary X509 encoding.
     */
    fun getRsaPublicFromPrivate(rsaPrivateCrtKey: RSAPrivateCrtKey): RSAPublicKey {
        val spec = RSAPublicKeySpec(rsaPrivateCrtKey.modulus, rsaPrivateCrtKey.publicExponent)
        val pub = KeyFactory.getInstance("RSA").generatePublic(spec)
        if (pub !is RSAPublicKey)
            throw Exception("wrong encoding")
        return pub
    }

    /**
     * Generate a fresh RSA key pair.
     *
     * @param nbits size of the modulus in bits
     */
    fun generateRsaKeyPair(nbits: Int): RsaCrtKeyPair {
        val gen = KeyPairGenerator.getInstance("RSA")
        gen.initialize(nbits)
        val pair = gen.genKeyPair()
        val priv = pair.private
        val pub = pair.public
        if (priv !is RSAPrivateCrtKey)
            throw Exception("key generation failed")
        if (pub !is RSAPublicKey)
            throw Exception("key generation failed")
        return RsaCrtKeyPair(priv, pub)
    }

    /**
     * Hash an RSA public key according to the EBICS standard (EBICS 2.5: 4.4.1.2.3).
     */
    fun getEbicsPublicKeyHash(publicKey: RSAPublicKey): ByteArray {
        val keyBytes = ByteArrayOutputStream()
        keyBytes.writeBytes(publicKey.publicExponent.encodeHex().trimStart('0').toByteArray())
        keyBytes.write(' '.code)
        keyBytes.writeBytes(publicKey.modulus.encodeHex().trimStart('0').toByteArray())
        val digest = MessageDigest.getInstance("SHA-256")
        return digest.digest(keyBytes.toByteArray())
    }

    fun encryptEbicsE002(data: InputStream, encryptionPublicKey: RSAPublicKey): EncryptionResult {
        val keygen = KeyGenerator.getInstance("AES", bouncyCastleProvider)
        keygen.init(128)
        val transactionKey = keygen.generateKey()
        return encryptEbicsE002withTransactionKey(
            data,
            encryptionPublicKey,
            transactionKey
        )
    }
    /**
     * Encrypt data according to the EBICS E002 encryption process.
     */
    fun encryptEbicsE002withTransactionKey(
        data: InputStream,
        encryptionPublicKey: RSAPublicKey,
        transactionKey: SecretKey
    ): EncryptionResult {
        val symmetricCipher = Cipher.getInstance(
            "AES/CBC/X9.23Padding",
            bouncyCastleProvider
        )
        val ivParameterSpec = IvParameterSpec(ByteArray(16))
        symmetricCipher.init(Cipher.ENCRYPT_MODE, transactionKey, ivParameterSpec)
        val encryptedData = CipherInputStream(data, symmetricCipher).readAllBytes()
        val asymmetricCipher = Cipher.getInstance(
            "RSA/None/PKCS1Padding",
            bouncyCastleProvider
        )
        asymmetricCipher.init(Cipher.ENCRYPT_MODE, encryptionPublicKey)
        val encryptedTransactionKey = asymmetricCipher.doFinal(transactionKey.encoded)
        val pubKeyDigest = getEbicsPublicKeyHash(encryptionPublicKey)
        return EncryptionResult(
            encryptedTransactionKey,
            pubKeyDigest,
            encryptedData,
            transactionKey
        )
    }

    fun decryptEbicsE002(enc: EncryptionResult, privateKey: RSAPrivateCrtKey): ByteArray {
        return decryptEbicsE002(
            enc.encryptedTransactionKey,
            enc.encryptedData.inputStream(),
            privateKey
        ).readBytes()
    }

    fun decryptEbicsE002(
        encryptedTransactionKey: ByteArray,
        encryptedData: InputStream,
        privateKey: RSAPrivateCrtKey
    ): CipherInputStream {
        val asymmetricCipher = Cipher.getInstance(
            "RSA/None/PKCS1Padding",
            bouncyCastleProvider
        )
        asymmetricCipher.init(Cipher.DECRYPT_MODE, privateKey)
        val transactionKeyBytes = asymmetricCipher.doFinal(encryptedTransactionKey)
        val secretKeySpec = SecretKeySpec(transactionKeyBytes, "AES")
        val symmetricCipher = Cipher.getInstance(
            "AES/CBC/X9.23Padding",
            bouncyCastleProvider
        )
        val ivParameterSpec = IvParameterSpec(ByteArray(16))
        symmetricCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec)
        return CipherInputStream(encryptedData, symmetricCipher)
    }

    /**
     * Signing algorithm corresponding to the EBICS A006 signing process.
     *
     * Note that while [data] can be arbitrary-length data, in EBICS, the order
     * data is *always* hashed *before* passing it to the signing algorithm, which again
     * uses a hash internally.
     */
    fun signEbicsA006(data: ByteArray, privateKey: RSAPrivateCrtKey): ByteArray {
        val signature = Signature.getInstance("SHA256withRSA/PSS", bouncyCastleProvider)
        signature.setParameter(PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1))
        signature.initSign(privateKey)
        signature.update(data)
        return signature.sign()
    }

    fun verifyEbicsA006(sig: ByteArray, data: ByteArray, publicKey: RSAPublicKey): Boolean {
        val signature = Signature.getInstance("SHA256withRSA/PSS", bouncyCastleProvider)
        signature.setParameter(PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1))
        signature.initVerify(publicKey)
        signature.update(data)
        return signature.verify(sig)
    }

    fun digestEbicsOrderA006(orderData: ByteArray): ByteArray {
        val digest = MessageDigest.getInstance("SHA-256")
        for (b in orderData) {
            when (b) {
                '\r'.code.toByte(), '\n'.code.toByte(), (26).toByte() -> Unit
                else -> digest.update(b)
            }
        }
        return digest.digest()
    }

    fun decryptKey(data: EncryptedPrivateKeyInfo, passphrase: String): RSAPrivateCrtKey {
        /* make key out of passphrase */
        val pbeKeySpec = PBEKeySpec(passphrase.toCharArray())
        val keyFactory = SecretKeyFactory.getInstance(data.algName)
        val secretKey = keyFactory.generateSecret(pbeKeySpec)
        /* Make a cipher */
        val cipher = Cipher.getInstance(data.algName)
        cipher.init(
            Cipher.DECRYPT_MODE,
            secretKey,
            data.algParameters // has hash count and salt
        )
        /* Ready to decrypt */
        val decryptedKeySpec: PKCS8EncodedKeySpec = data.getKeySpec(cipher)
        val priv = KeyFactory.getInstance("RSA").generatePrivate(decryptedKeySpec)
        if (priv !is RSAPrivateCrtKey)
            throw Exception("wrong encoding")
        return priv
    }

    fun encryptKey(data: ByteArray, passphrase: String): ByteArray {
        /* Cipher parameters: salt and hash count */
        val hashIterations = 30
        val salt = ByteArray(8)
        SecureRandom().nextBytes(salt)
        val pbeParameterSpec = PBEParameterSpec(salt, hashIterations)
        /* *Other* cipher parameters: symmetric key (from password) */
        val pbeAlgorithm = "PBEWithSHA1AndDESede"
        val pbeKeySpec = PBEKeySpec(passphrase.toCharArray())
        val keyFactory = SecretKeyFactory.getInstance(pbeAlgorithm)
        val secretKey = keyFactory.generateSecret(pbeKeySpec)
        /* Make a cipher */
        val cipher = Cipher.getInstance(pbeAlgorithm)
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec)
        /* ready to encrypt now */
        val cipherText = cipher.doFinal(data)
        /* Must now bundle a PKCS#8-compatible object, that contains
         * algorithm, salt and hash count information */
        val bundleAlgorithmParams = AlgorithmParameters.getInstance(pbeAlgorithm)
        bundleAlgorithmParams.init(pbeParameterSpec)
        val bundle = EncryptedPrivateKeyInfo(bundleAlgorithmParams, cipherText)
        return bundle.encoded
    }

    fun hashStringSHA256(input: String): ByteArray {
        return MessageDigest.getInstance("SHA-256").digest(input.toByteArray(Charsets.UTF_8))
    }
}