1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2025-12-20 13:15:43 +00:00

complete tools for handling of encrypted data

This commit is contained in:
2021-01-23 20:50:40 +06:00
parent d34deade0d
commit 4d63e3a17d
7 changed files with 22 additions and 104 deletions

View File

@@ -1,7 +1,6 @@
package dev.inmo.tgbotapi.utils.passport
import dev.inmo.micro_utils.crypto.decodeBase64
import sun.security.rsa.RSAPublicKeyImpl
import java.security.KeyFactory
import java.security.interfaces.RSAPrivateKey
import java.security.spec.PKCS8EncodedKeySpec
@@ -9,21 +8,16 @@ import javax.crypto.Cipher
private val regexToRemoveFromKey = Regex("(-----(BEGIN|END) ((?:.*? KEY)|CERTIFICATE)-----|[\\s])")
private fun String.adaptKey() {
val replaced = replace(regexToRemoveFromKey, "")
}
/**
* @param key PKCS8
*/
actual class DecryptionContext actual constructor(key: String) {
class PKCS8Decryptor (key: String): Decryptor {
private val privateKey: RSAPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(
PKCS8EncodedKeySpec(key.replace(regexToRemoveFromKey, "").decodeBase64())
) as RSAPrivateKey
private val chunkSize: Int = privateKey.modulus.bitLength() / 8
actual fun ByteArray.decrypt(): ByteArray {
override fun ByteArray.decrypt(): ByteArray {
return Cipher.getInstance("RSA/ECB/PKCS1Padding").run {
init(Cipher.DECRYPT_MODE, privateKey)
(0 until size step chunkSize).flatMap {
@@ -37,4 +31,9 @@ actual class DecryptionContext actual constructor(key: String) {
}.toByteArray()
}
}
}
}
fun Decryptor(key: String) = PKCS8Decryptor(key)
inline fun <T> doWithDecryptor(decryptor: Decryptor, crossinline block: Decryptor.() -> T) = decryptor.run(block)
inline fun <T> doWithDecryptor(key: String, crossinline block: Decryptor.() -> T) = doWithDecryptor(Decryptor(key), block)