All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.binaryfoo.crypto.SignedDataRecoverer.kt Maven / Gradle / Ivy

There is a newer version: 0.1.8
Show newest version
package io.github.binaryfoo.crypto

import io.github.binaryfoo.tlv.ISOUtil
import java.math.BigInteger
import kotlin.collections.lastIndex

class SignedDataRecoverer {

    fun recover(signed: String, exponent: String, modulus: String): ByteArray {
        return recover(ISOUtil.hex2byte(signed), ISOUtil.hex2byte(exponent), ISOUtil.hex2byte(modulus))
    }

    fun recover(signed: ByteArray, exponent: ByteArray, modulus: ByteArray): ByteArray {
        val biSigned = BigInteger(1, signed)
        val biExponent = BigInteger(exponent)
        val bigModulus = BigInteger(1, modulus)
        val recovered = biSigned.modPow(biExponent, bigModulus).toByteArray()
        verify(recovered)
        return recovered
    }

    private fun verify(recovered: ByteArray) {
        val header = recovered[0].toInt()
        if (header != 0x6A) {
            throw IllegalStateException("Recover failed: bad header byte ${Integer.toHexString(header)}")
        }
        val footer = recovered[recovered.lastIndex].toInt() and 0xFF
        if (footer != 0xBC) {
            throw IllegalStateException("Recover failed: bad footer byte ${Integer.toHexString(footer)}")
        }
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy