summaryrefslogtreecommitdiff
path: root/util/src/main/kotlin/Ebics.kt
blob: 2d90dd2cdc046e8945506017be1a9691fec33928 (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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
/*
 * This file is part of LibEuFin.
 * Copyright (C) 2019 Stanisci and Dold.

 * 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/>
 */

/**
 * This is the main "EBICS library interface".  Functions here are stateless helpers
 * used to implement both an EBICS server and EBICS client.
 */

package tech.libeufin.util

import io.ktor.http.HttpStatusCode
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import tech.libeufin.util.ebics_h004.*
import tech.libeufin.util.ebics_h005.Ebics3Request
import tech.libeufin.util.ebics_h005.Ebics3Response
import tech.libeufin.util.ebics_hev.HEVRequest
import tech.libeufin.util.ebics_hev.HEVResponse
import tech.libeufin.util.ebics_s001.UserSignatureData
import java.math.BigInteger
import java.security.SecureRandom
import java.security.interfaces.RSAPrivateCrtKey
import java.security.interfaces.RSAPublicKey
import java.time.ZonedDateTime
import java.util.*
import java.util.zip.DeflaterInputStream
import javax.xml.bind.JAXBElement
import javax.xml.datatype.DatatypeFactory
import javax.xml.datatype.XMLGregorianCalendar

private val logger: Logger = LoggerFactory.getLogger("tech.libeufin.util")

data class EbicsProtocolError(
    val httpStatusCode: HttpStatusCode,
    val reason: String,
    /**
     * This class is also used when Nexus finds itself
     * in an inconsistent state, without interacting with the
     * bank.  In this case, the EBICS code below can be left
     * null.
     */
    val ebicsTechnicalCode: EbicsReturnCode? = null
) : Exception(reason)

data class EbicsDateRange(val start: ZonedDateTime, val end: ZonedDateTime)

sealed class EbicsOrderParams
data class EbicsStandardOrderParams(
    val dateRange: EbicsDateRange? = null
) : EbicsOrderParams()

data class EbicsGenericOrderParams(
    val params: Map<String, String> = mapOf()
) : EbicsOrderParams()

enum class EbicsInitState {
    SENT, NOT_SENT, UNKNOWN
}

/**
 * This class is a mere container that keeps data found
 * in the database and that is further needed to sign / verify
 * / make messages.  And not all the values are needed all
 * the time.
 */
data class EbicsClientSubscriberDetails(
    val partnerId: String,
    val userId: String,
    var bankAuthPub: RSAPublicKey?,
    var bankEncPub: RSAPublicKey?,
    val ebicsUrl: String,
    val hostId: String,
    val customerEncPriv: RSAPrivateCrtKey,
    val customerAuthPriv: RSAPrivateCrtKey,
    val customerSignPriv: RSAPrivateCrtKey,
    val ebicsIniState: EbicsInitState,
    val ebicsHiaState: EbicsInitState,
    var dialect: String? = null
)

/**
 * @param size in bits
 */
private fun getNonce(size: Int): ByteArray {
    val sr = SecureRandom()
    val ret = ByteArray(size / 8)
    sr.nextBytes(ret)
    return ret
}

private fun getXmlDate(d: ZonedDateTime): XMLGregorianCalendar {
    return DatatypeFactory.newInstance()
        .newXMLGregorianCalendar(d.year, d.monthValue, d.dayOfMonth, 0, 0, 0, 0, d.offset.totalSeconds / 60)
}

private fun makeOrderParams(orderParams: EbicsOrderParams): EbicsRequest.OrderParams {
    return when (orderParams) {
        is EbicsStandardOrderParams -> {
            EbicsRequest.StandardOrderParams().apply {
                val r = orderParams.dateRange
                if (r != null) {
                    this.dateRange = EbicsRequest.DateRange().apply {
                        this.start = getXmlDate(r.start)
                        this.end = getXmlDate(r.end)
                    }
                }
            }
        }
        is EbicsGenericOrderParams -> {
            EbicsRequest.GenericOrderParams().apply {
                this.parameterList = orderParams.params.map { entry ->
                    EbicsTypes.Parameter().apply {
                        this.name = entry.key
                        this.value = entry.value
                        this.type = "string"
                    }
                }
            }
        }
    }
}

fun makeEbics3DateRange(ebicsDateRange: EbicsDateRange?): Ebics3Request.DateRange? {
    return if (ebicsDateRange != null)
        return Ebics3Request.DateRange().apply {
            this.start = getXmlDate(ebicsDateRange.start)
            this.end = getXmlDate(ebicsDateRange.end)
        }
    else null
}

private fun signOrder(
    orderBlob: ByteArray,
    signKey: RSAPrivateCrtKey,
    partnerId: String,
    userId: String
): UserSignatureData {
    val ES_signature = CryptoUtil.signEbicsA006(
        CryptoUtil.digestEbicsOrderA006(orderBlob),
        signKey
    )
    val userSignatureData = UserSignatureData().apply {
        orderSignatureList = listOf(
            UserSignatureData.OrderSignatureData().apply {
                signatureVersion = "A006"
                signatureValue = ES_signature
                partnerID = partnerId
                userID = userId
            }
        )
    }
    return userSignatureData
}

private fun signOrderEbics3(
    orderBlob: ByteArray,
    signKey: RSAPrivateCrtKey,
    partnerId: String,
    userId: String
): tech.libeufin.util.ebics_s002.UserSignatureDataEbics3 {
    val ES_signature = CryptoUtil.signEbicsA006(
        CryptoUtil.digestEbicsOrderA006(orderBlob),
        signKey
    )
    val userSignatureData = tech.libeufin.util.ebics_s002.UserSignatureDataEbics3().apply {
        orderSignatureList = listOf(
            tech.libeufin.util.ebics_s002.UserSignatureDataEbics3.OrderSignatureData().apply {
                signatureVersion = "A006"
                signatureValue = ES_signature
                partnerID = partnerId
                userID = userId
            }
        )
    }
    return userSignatureData
}

fun createEbicsRequestForDownloadReceipt(
    subscriberDetails: EbicsClientSubscriberDetails,
    transactionID: String?,
    withEbics3: Boolean = false
): String {
    val doc = if (withEbics3) {
        val req = Ebics3Request.createForDownloadReceiptPhase(
            transactionID,
            subscriberDetails.hostId
        )
        XMLUtil.convertJaxbToDocument(req)

    } else {
        val req = EbicsRequest.createForDownloadReceiptPhase(
            transactionID,
            subscriberDetails.hostId
        )
        XMLUtil.convertJaxbToDocument(req)
    }
    XMLUtil.signEbicsDocument(doc, subscriberDetails.customerAuthPriv)
    return XMLUtil.convertDomToString(doc)
}

data class PreparedUploadData(
    val transactionKey: ByteArray,
    val userSignatureDataEncrypted: ByteArray,
    val dataDigest: ByteArray,
    val encryptedPayloadChunks: List<String>
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as PreparedUploadData

        if (!transactionKey.contentEquals(other.transactionKey)) return false
        if (!userSignatureDataEncrypted.contentEquals(other.userSignatureDataEncrypted)) return false
        if (encryptedPayloadChunks != other.encryptedPayloadChunks) return false

        return true
    }

    override fun hashCode(): Int {
        var result = transactionKey.contentHashCode()
        result = 31 * result + userSignatureDataEncrypted.contentHashCode()
        result = 31 * result + encryptedPayloadChunks.hashCode()
        return result
    }
}

fun prepareUploadPayload(
    subscriberDetails: EbicsClientSubscriberDetails,
    payload: ByteArray,
    isEbics3: Boolean = false
): PreparedUploadData {
    // First A006-sign the payload, then E002-encrypt with bank's pub.
    val encryptionResult = if (isEbics3) {
        val innerSignedEbicsXml = signOrderEbics3( // A006 signature.
            payload,
            subscriberDetails.customerSignPriv,
            subscriberDetails.partnerId,
            subscriberDetails.userId
        )
        val userSignatureDataEncrypted = CryptoUtil.encryptEbicsE002(
            EbicsOrderUtil.encodeOrderDataXml(innerSignedEbicsXml),
            subscriberDetails.bankEncPub!!
        )
        userSignatureDataEncrypted
    } else {
        val innerSignedEbicsXml = signOrder( // A006 signature.
            payload,
            subscriberDetails.customerSignPriv,
            subscriberDetails.partnerId,
            subscriberDetails.userId
        )
        val userSignatureDataEncrypted = CryptoUtil.encryptEbicsE002(
            EbicsOrderUtil.encodeOrderDataXml(innerSignedEbicsXml),
            subscriberDetails.bankEncPub!!
        )
        userSignatureDataEncrypted
    }
    // Then only E002 symmetric (with ephemeral key) encrypt.
    val compressedInnerPayload = DeflaterInputStream(
        payload.inputStream()
    ).use { it.readAllBytes() }
    val encryptedPayload = CryptoUtil.encryptEbicsE002withTransactionKey(
        compressedInnerPayload,
        subscriberDetails.bankEncPub!!,
        encryptionResult.plainTransactionKey!!
    )
    val encodedEncryptedPayload = Base64.getEncoder().encodeToString(encryptedPayload.encryptedData)

    return PreparedUploadData(
        encryptionResult.encryptedTransactionKey, // ephemeral key
        encryptionResult.encryptedData, // bank-pub-encrypted A006 signature.
        CryptoUtil.digestEbicsOrderA006(payload), // used by EBICS 3
        listOf(encodedEncryptedPayload) // actual payload E002 encrypted.
    )
}

// Creates the EBICS 3 upload init request.
fun createEbicsRequestForUploadInitialization(
    subscriberDetails: EbicsClientSubscriberDetails,
    ebics3OrderService: Ebics3Request.OrderDetails.Service,
    orderParams: EbicsOrderParams? = null,
    preparedUploadData: PreparedUploadData
): String {
    val nonce = getNonce(128)
    val req = Ebics3Request.createForUploadInitializationPhase(
        preparedUploadData.transactionKey,
        preparedUploadData.userSignatureDataEncrypted,
        preparedUploadData.dataDigest,
        subscriberDetails.hostId,
        nonce,
        subscriberDetails.partnerId,
        subscriberDetails.userId,
        DatatypeFactory.newInstance().newXMLGregorianCalendar(GregorianCalendar()),
        subscriberDetails.bankAuthPub!!,
        subscriberDetails.bankEncPub!!,
        BigInteger.ONE,
        ebics3OrderService
    )
    val doc = XMLUtil.convertJaxbToDocument(
        req,
        withSchemaLocation = "urn:org:ebics:H005 ebics_request_H005.xsd"
    )
    logger.debug("Created EBICS 3 document for upload initialization," +
            " nonce: ${nonce.toHexString()}")
    XMLUtil.signEbicsDocument(
        doc,
        subscriberDetails.customerAuthPriv,
        withEbics3 = true
    )
    return XMLUtil.convertDomToString(doc)
}

/**
 * Create an EBICS request for the initialization phase of an upload EBICS transaction.
 *
 * The payload is only passed to generate the signature.
 */
fun createEbicsRequestForUploadInitialization(
    subscriberDetails: EbicsClientSubscriberDetails,
    orderType: String,
    orderParams: EbicsOrderParams,
    preparedUploadData: PreparedUploadData
): String {
    val nonce = getNonce(128)
    val req = EbicsRequest.createForUploadInitializationPhase(
        preparedUploadData.transactionKey,
        preparedUploadData.userSignatureDataEncrypted,
        subscriberDetails.hostId,
        nonce,
        subscriberDetails.partnerId,
        subscriberDetails.userId,
        DatatypeFactory.newInstance().newXMLGregorianCalendar(GregorianCalendar()),
        subscriberDetails.bankAuthPub!!,
        subscriberDetails.bankEncPub!!,
        BigInteger.ONE,
        orderType,
        makeOrderParams(orderParams)
    )
    val doc = XMLUtil.convertJaxbToDocument(req)
    logger.debug("Created EBICS $orderType document for upload initialization," +
            " nonce: ${nonce.toHexString()}")
    XMLUtil.signEbicsDocument(
        doc,
        subscriberDetails.customerAuthPriv
    )
    return XMLUtil.convertDomToString(doc)
}

// Generates a EBICS 2.5 signed document for the download init phase.
fun createEbicsRequestForDownloadInitialization(
    subscriberDetails: EbicsClientSubscriberDetails,
    orderType: String,
    orderParams: EbicsOrderParams
): String {
    val nonce = getNonce(128)
    val req = EbicsRequest.createForDownloadInitializationPhase(
        subscriberDetails.userId,
        subscriberDetails.partnerId,
        subscriberDetails.hostId,
        nonce,
        DatatypeFactory.newInstance().newXMLGregorianCalendar(GregorianCalendar()),
        subscriberDetails.bankEncPub ?: throw EbicsProtocolError(
            HttpStatusCode.BadRequest,
            "Invalid subscriber state 'bankEncPub' missing, please send HPB first"
        ),
        subscriberDetails.bankAuthPub ?: throw EbicsProtocolError(
            HttpStatusCode.BadRequest,
            "Invalid subscriber state 'bankAuthPub' missing, please send HPB first"
        ),
        orderType,
        makeOrderParams(orderParams)
    )
    logger.debug("Created EBICS document for download initialization, nonce: ${nonce.toHexString()}")
    val doc = XMLUtil.convertJaxbToDocument(req)
    XMLUtil.signEbicsDocument(
        doc,
        subscriberDetails.customerAuthPriv,
        withEbics3 = false
    )
    return XMLUtil.convertDomToString(doc)
}

fun createEbicsRequestForDownloadInitialization(
    subscriberDetails: EbicsClientSubscriberDetails,
    ebics3OrderService: Ebics3Request.OrderDetails.Service,
    orderParams: EbicsOrderParams,
): String {
    val nonce = getNonce(128)
    val req = Ebics3Request.createForDownloadInitializationPhase(
        subscriberDetails.userId,
        subscriberDetails.partnerId,
        subscriberDetails.hostId,
        nonce,
        DatatypeFactory.newInstance().newXMLGregorianCalendar(GregorianCalendar()),
        subscriberDetails.bankEncPub ?: throw EbicsProtocolError(
            HttpStatusCode.BadRequest,
            "Invalid subscriber state 'bankEncPub' missing, please send HPB first"
        ),
        subscriberDetails.bankAuthPub ?: throw EbicsProtocolError(
            HttpStatusCode.BadRequest,
            "Invalid subscriber state 'bankAuthPub' missing, please send HPB first"
        ),
        ebics3OrderService
    )
    val doc = XMLUtil.convertJaxbToDocument(req)
    XMLUtil.signEbicsDocument(
        doc,
        subscriberDetails.customerAuthPriv,
        withEbics3 = true
    )
    return XMLUtil.convertDomToString(doc)
}

fun createEbicsRequestForDownloadTransferPhase(
    subscriberDetails: EbicsClientSubscriberDetails,
    transactionID: String?,
    segmentNumber: Int,
    numSegments: Int,
    withEbics3: Boolean = false
): String {
    val doc = if (withEbics3) {
        val req = Ebics3Request.createForDownloadTransferPhase(
            subscriberDetails.hostId,
            transactionID,
            segmentNumber,
            numSegments
        )
        XMLUtil.convertJaxbToDocument(req)
    } else {
        val req = EbicsRequest.createForDownloadTransferPhase(
            subscriberDetails.hostId,
            transactionID,
            segmentNumber,
            numSegments
        )
        XMLUtil.convertJaxbToDocument(req)
    }
    XMLUtil.signEbicsDocument(
        doc,
        subscriberDetails.customerAuthPriv,
        withEbics3 = withEbics3
    )
    return XMLUtil.convertDomToString(doc)
}

fun createEbicsRequestForUploadTransferPhase(
    subscriberDetails: EbicsClientSubscriberDetails,
    transactionID: String?,
    preparedUploadData: PreparedUploadData,
    chunkIndex: Int,
    withEbics3: Boolean = false
): String {
    val doc = if (withEbics3) {
        val req = Ebics3Request.createForUploadTransferPhase(
            subscriberDetails.hostId,
            transactionID,
            // chunks are 1-indexed
            BigInteger.valueOf(chunkIndex.toLong() + 1),
            preparedUploadData.encryptedPayloadChunks[chunkIndex]
        )
        XMLUtil.convertJaxbToDocument(req)
    } else {
        val req = EbicsRequest.createForUploadTransferPhase(
            subscriberDetails.hostId,
            transactionID,
            // chunks are 1-indexed
            BigInteger.valueOf(chunkIndex.toLong() + 1),
            preparedUploadData.encryptedPayloadChunks[chunkIndex]
        )
        XMLUtil.convertJaxbToDocument(req)
    }
    XMLUtil.signEbicsDocument(doc, subscriberDetails.customerAuthPriv, withEbics3)
    return XMLUtil.convertDomToString(doc)
}

data class DataEncryptionInfo(
    val transactionKey: ByteArray,
    val bankPubDigest: ByteArray
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as DataEncryptionInfo

        if (!transactionKey.contentEquals(other.transactionKey)) return false
        if (!bankPubDigest.contentEquals(other.bankPubDigest)) return false

        return true
    }

    override fun hashCode(): Int {
        var result = transactionKey.contentHashCode()
        result = 31 * result + bankPubDigest.contentHashCode()
        return result
    }
}


@Suppress("SpellCheckingInspection")
enum class EbicsReturnCode(val errorCode: String) {
    EBICS_OK("000000"),
    EBICS_DOWNLOAD_POSTPROCESS_DONE("011000"),
    EBICS_DOWNLOAD_POSTPROCESS_SKIPPED("011001"),
    EBICS_TX_SEGMENT_NUMBER_UNDERRUN("011101"),
    EBICS_AUTHENTICATION_FAILED ("061001"),
    EBICS_INVALID_USER_OR_USER_STATE("091002"),
    EBICS_PROCESSING_ERROR("091116"),
    EBICS_ACCOUNT_AUTHORISATION_FAILED("091302"),
    EBICS_AMOUNT_CHECK_FAILED("091303"),
    EBICS_EBICS_AUTHORISATION_ORDER_IDENTIFIER_FAILED("090003"),
    EBICS_INVALID_XML("091010"),
    EBICS_NO_DOWNLOAD_DATA_AVAILABLE("090005");

    companion object {
        fun lookup(errorCode: String): EbicsReturnCode {
            for (x in values()) {
                if (x.errorCode == errorCode) {
                    return x
                }
            }
            throw EbicsProtocolError(HttpStatusCode.InternalServerError, "Unknown EBICS status code: $errorCode")
        }
    }
}

data class EbicsResponseContent(
    val transactionID: String?,
    val dataEncryptionInfo: DataEncryptionInfo?,
    val orderDataEncChunk: String?,
    val technicalReturnCode: EbicsReturnCode,
    val bankReturnCode: EbicsReturnCode,
    val reportText: String,
    val segmentNumber: Int?,
    // Only present in init phase
    val numSegments: Int?
)

data class EbicsKeyManagementResponseContent(
    val technicalReturnCode: EbicsReturnCode,
    val bankReturnCode: EbicsReturnCode?,
    val orderData: ByteArray?
)

fun parseAndDecryptEbicsKeyManagementResponse(
    subscriberDetails: EbicsClientSubscriberDetails,
    responseStr: String
): EbicsKeyManagementResponseContent {
    val resp = try {
        XMLUtil.convertStringToJaxb<EbicsKeyManagementResponse>(responseStr)
    } catch (e: Exception) {
        throw EbicsProtocolError(HttpStatusCode.InternalServerError, "Invalid XML received from bank")
    }
    val retCode = EbicsReturnCode.lookup(resp.value.header.mutable.returnCode)

    val daeXml = resp.value.body.dataTransfer?.dataEncryptionInfo
    val orderData = if (daeXml != null) {
        val dae = DataEncryptionInfo(daeXml.transactionKey, daeXml.encryptionPubKeyDigest.value)
        val encOrderData = resp.value.body.dataTransfer?.orderData?.value ?: throw EbicsProtocolError(
            HttpStatusCode.InternalServerError, "Invalid XML/orderData received from bank"
        )
        decryptAndDecompressResponse(subscriberDetails, dae, listOf(encOrderData))
    } else {
        null
    }

    val bankReturnCodeStr = resp.value.body.returnCode.value
    val bankReturnCode = EbicsReturnCode.lookup(bankReturnCodeStr)

    return EbicsKeyManagementResponseContent(retCode, bankReturnCode, orderData)
}

class HpbResponseData(
    val hostID: String,
    val encryptionPubKey: RSAPublicKey,
    val encryptionVersion: String,
    val authenticationPubKey: RSAPublicKey,
    val authenticationVersion: String
)

fun parseEbicsHpbOrder(orderDataRaw: ByteArray): HpbResponseData {
    val resp = try {
        XMLUtil.convertStringToJaxb<HPBResponseOrderData>(orderDataRaw.toString(Charsets.UTF_8))
    } catch (e: Exception) {
        throw EbicsProtocolError(HttpStatusCode.InternalServerError, "Invalid XML (as HPB response) received from bank")
    }
    val encPubKey = CryptoUtil.loadRsaPublicKeyFromComponents(
        resp.value.encryptionPubKeyInfo.pubKeyValue.rsaKeyValue.modulus,
        resp.value.encryptionPubKeyInfo.pubKeyValue.rsaKeyValue.exponent
    )
    val authPubKey = CryptoUtil.loadRsaPublicKeyFromComponents(
        resp.value.authenticationPubKeyInfo.pubKeyValue.rsaKeyValue.modulus,
        resp.value.authenticationPubKeyInfo.pubKeyValue.rsaKeyValue.exponent
    )
    return HpbResponseData(
        hostID = resp.value.hostID,
        encryptionPubKey = encPubKey,
        encryptionVersion = resp.value.encryptionPubKeyInfo.encryptionVersion,
        authenticationPubKey = authPubKey,
        authenticationVersion = resp.value.authenticationPubKeyInfo.authenticationVersion
    )
}

private fun ebics3toInternalRepr(response: String): EbicsResponseContent {
    val resp: JAXBElement<Ebics3Response> = try {
        XMLUtil.convertStringToJaxb(response)
    } catch (e: Exception) {
        throw EbicsProtocolError(
            HttpStatusCode.InternalServerError,
            "Could not transform string-response from bank into JAXB"
        )
    }
    val bankReturnCodeStr = resp.value.body.returnCode.value
    val bankReturnCode = EbicsReturnCode.lookup(bankReturnCodeStr)

    val techReturnCodeStr = resp.value.header.mutable.returnCode
    val techReturnCode = EbicsReturnCode.lookup(techReturnCodeStr)

    val reportText = resp.value.header.mutable.reportText

    val daeXml = resp.value.body.dataTransfer?.dataEncryptionInfo
    val dataEncryptionInfo = if (daeXml == null) {
        null
    } else {
        DataEncryptionInfo(daeXml.transactionKey, daeXml.encryptionPubKeyDigest.value)
    }

    return EbicsResponseContent(
        transactionID = resp.value.header._static.transactionID,
        bankReturnCode = bankReturnCode,
        technicalReturnCode = techReturnCode,
        reportText = reportText,
        orderDataEncChunk = resp.value.body.dataTransfer?.orderData?.value,
        dataEncryptionInfo = dataEncryptionInfo,
        numSegments = resp.value.header._static.numSegments?.toInt(),
        segmentNumber = resp.value.header.mutable.segmentNumber?.value?.toInt()
    )
}

private fun ebics25toInternalRepr(response: String): EbicsResponseContent {
    val resp: JAXBElement<EbicsResponse> = try {
        XMLUtil.convertStringToJaxb(response)
    } catch (e: Exception) {
        throw EbicsProtocolError(
            HttpStatusCode.InternalServerError,
            "Could not transform string-response from bank into JAXB"
        )
    }
    val bankReturnCodeStr = resp.value.body.returnCode.value
    val bankReturnCode = EbicsReturnCode.lookup(bankReturnCodeStr)

    val techReturnCodeStr = resp.value.header.mutable.returnCode
    val techReturnCode = EbicsReturnCode.lookup(techReturnCodeStr)

    val reportText = resp.value.header.mutable.reportText

    val daeXml = resp.value.body.dataTransfer?.dataEncryptionInfo
    val dataEncryptionInfo = if (daeXml == null) {
        null
    } else {
        DataEncryptionInfo(daeXml.transactionKey, daeXml.encryptionPubKeyDigest.value)
    }

    return EbicsResponseContent(
        transactionID = resp.value.header._static.transactionID,
        bankReturnCode = bankReturnCode,
        technicalReturnCode = techReturnCode,
        reportText = reportText,
        orderDataEncChunk = resp.value.body.dataTransfer?.orderData?.value,
        dataEncryptionInfo = dataEncryptionInfo,
        numSegments = resp.value.header._static.numSegments?.toInt(),
        segmentNumber = resp.value.header.mutable.segmentNumber?.value?.toInt()
    )
}
fun parseAndValidateEbicsResponse(
    subscriberDetails: EbicsClientSubscriberDetails,
    responseStr: String,
    withEbics3: Boolean = false
): EbicsResponseContent {
    val responseDocument = try {
        XMLUtil.parseStringIntoDom(responseStr)
    } catch (e: Exception) {
        throw EbicsProtocolError(
            HttpStatusCode.InternalServerError,
            "Invalid XML (as EbicsResponse) received from bank"
        )
    }
    if (!XMLUtil.verifyEbicsDocument(
            responseDocument,
            subscriberDetails.bankAuthPub ?: throw EbicsProtocolError(
                HttpStatusCode.InternalServerError,
                "Bank's signature verification failed"
            ),
            withEbics3 = withEbics3
        )
    ) {
        throw EbicsProtocolError(
            HttpStatusCode.InternalServerError,
            "Bank's signature verification failed"
        )
    }
    if (withEbics3)
        return ebics3toInternalRepr(responseStr)
    return ebics25toInternalRepr(responseStr)
}

/**
 * Get the private key that matches the given public key digest.
 */
fun getDecryptionKey(subscriberDetails: EbicsClientSubscriberDetails, pubDigest: ByteArray): RSAPrivateCrtKey {
    val authPub = CryptoUtil.getRsaPublicFromPrivate(subscriberDetails.customerAuthPriv)
    val encPub = CryptoUtil.getRsaPublicFromPrivate(subscriberDetails.customerEncPriv)
    val authPubDigest = CryptoUtil.getEbicsPublicKeyHash(authPub)
    val encPubDigest = CryptoUtil.getEbicsPublicKeyHash(encPub)
    if (pubDigest.contentEquals(authPubDigest)) {
        return subscriberDetails.customerAuthPriv
    }
    if (pubDigest.contentEquals(encPubDigest)) {
        return subscriberDetails.customerEncPriv
    }
    throw EbicsProtocolError(HttpStatusCode.NotFound, "Could not find customer's public key")
}

/**
 * Wrapper around the lower decryption routine, that takes a EBICS response
 * object containing a encrypted payload, and return the plain version of it
 * (including decompression).
 */
fun decryptAndDecompressResponse(
    subscriberDetails: EbicsClientSubscriberDetails,
    encryptionInfo: DataEncryptionInfo,
    chunks: List<String>
): ByteArray {
    val privateKey = getDecryptionKey(subscriberDetails, encryptionInfo.bankPubDigest)
    val buf = StringBuilder()
    chunks.forEach { buf.append(it) }
    val decoded = Base64.getDecoder().decode(buf.toString())
    val er = CryptoUtil.EncryptionResult(
        encryptionInfo.transactionKey,
        encryptionInfo.bankPubDigest,
        decoded
    )
    val dataCompr = CryptoUtil.decryptEbicsE002(
        er,
        privateKey
    )
    return EbicsOrderUtil.decodeOrderData(dataCompr)
}

data class EbicsVersionSpec(
    val protocol: String,
    val version: String
)

data class EbicsHevDetails(
    val versions: List<EbicsVersionSpec>
)

fun makeEbicsHEVRequest(subscriberDetails: EbicsClientSubscriberDetails): String {
    val req = HEVRequest().apply {
        hostId = subscriberDetails.hostId
    }
    val doc = XMLUtil.convertJaxbToDocument(req)
    return XMLUtil.convertDomToString(doc)
}

fun makeEbicsHEVRequestRaw(hostID: String): String {
    val h = hostID
    val req = HEVRequest().apply {
        hostId = h
    }
    val doc = XMLUtil.convertJaxbToDocument(req)
    return XMLUtil.convertDomToString(doc)
}

fun parseEbicsHEVResponse(respStr: String): EbicsHevDetails {
    val resp = try {
        XMLUtil.convertStringToJaxb<HEVResponse>(respStr)
    } catch (e: Exception) {
        logger.error("Exception while parsing HEV response", e)
        throw EbicsProtocolError(HttpStatusCode.InternalServerError, "Invalid HEV received from bank")
    }
    val versions = resp.value.versionNumber.map { versionNumber ->
        EbicsVersionSpec(versionNumber.protocolVersion, versionNumber.value)
    }
    return EbicsHevDetails(versions)
}

fun makeEbicsIniRequest(subscriberDetails: EbicsClientSubscriberDetails): String {
    val iniRequest = EbicsUnsecuredRequest.createIni(
        subscriberDetails.hostId,
        subscriberDetails.userId,
        subscriberDetails.partnerId,
        subscriberDetails.customerSignPriv
    )
    val doc = XMLUtil.convertJaxbToDocument(iniRequest)
    return XMLUtil.convertDomToString(doc)
}

fun makeEbicsHiaRequest(subscriberDetails: EbicsClientSubscriberDetails): String {
    val hiaRequest = EbicsUnsecuredRequest.createHia(
        subscriberDetails.hostId,
        subscriberDetails.userId,
        subscriberDetails.partnerId,
        subscriberDetails.customerAuthPriv,
        subscriberDetails.customerEncPriv
    )
    val doc = XMLUtil.convertJaxbToDocument(hiaRequest)
    return XMLUtil.convertDomToString(doc)
}

fun makeEbicsHpbRequest(subscriberDetails: EbicsClientSubscriberDetails): String {
    val hpbRequest = EbicsNpkdRequest.createRequest(
        subscriberDetails.hostId,
        subscriberDetails.partnerId,
        subscriberDetails.userId,
        getNonce(128),
        DatatypeFactory.newInstance().newXMLGregorianCalendar(GregorianCalendar())
    )
    val doc = XMLUtil.convertJaxbToDocument(hpbRequest)
    XMLUtil.signEbicsDocument(doc, subscriberDetails.customerAuthPriv)
    return XMLUtil.convertDomToString(doc)
}

fun dumpEbicsSubscriber(ebicsHeader: EbicsUnsecuredRequest.StaticHeaderType): String {
    return "userID: ${ebicsHeader.userID}, partnerID: ${ebicsHeader.partnerID}, systemID: ${ebicsHeader.systemID}"

}