Skip to content

Commit

Permalink
optimize encrypt method
Browse files Browse the repository at this point in the history
  • Loading branch information
pedroSG94 committed Nov 14, 2023
1 parent 8f9f5ac commit 9d766ef
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions srt/src/main/java/com/pedro/srt/utils/EncryptionUtil.kt
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,29 @@ class EncryptionUtil(val type: EncryptionType, passphrase: String) {
private val keyBasedEncryption = KeyBasedEncryption.PAIR_KEY
private val cipherType = CipherType.CTR
private val salt: ByteArray
private val sek: ByteArray
private val keyLength: Int = when (type) {
EncryptionType.NONE -> 0
EncryptionType.AES128 -> 16
EncryptionType.AES192 -> 24
EncryptionType.AES256 -> 32
}
private var keyData = byteArrayOf()
private val block: SecretKeySpec
private val cipher = Cipher.getInstance("AES/CTR/NoPadding")

init {
salt = generateSecureRandomBytes(16)
sek = generateSecureRandomBytes(keyLength)
val sek = generateSecureRandomBytes(keyLength)
val kek = calculateKEK(passphrase, salt, keyLength)
keyData = wrapKey(kek, sek)
block = SecretKeySpec(sek, "AES")
}

fun encrypt(bytes: ByteArray, sequence: Int): ByteArray {
val ctr = ByteArray(16)
ByteBuffer.wrap(ctr, 10, 4).putInt(sequence)
for (i in 0 until 14) ctr[i] = (ctr[i] xor salt[i])

val block = SecretKeySpec(sek, "AES")
val cipher = Cipher.getInstance("AES/CTR/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, block, IvParameterSpec(ctr))
return cipher.doFinal(bytes)
}
Expand Down

0 comments on commit 9d766ef

Please sign in to comment.