-
-
Notifications
You must be signed in to change notification settings - Fork 787
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
75 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
package com.pedro.srt.utils | ||
|
||
import android.util.Log | ||
import com.pedro.srt.srt.packets.control.handshake.EncryptionType | ||
import java.security.SecureRandom | ||
import javax.crypto.Cipher | ||
import javax.crypto.SecretKeyFactory | ||
import javax.crypto.spec.PBEKeySpec | ||
|
||
/** | ||
* Created by pedro on 12/11/23. | ||
* Need API 26+ | ||
* | ||
*/ | ||
class EncryptionUtil(val type: EncryptionType, passphrase: String) { | ||
|
||
private val cipher: Cipher | ||
private val iterations = 10_000 //reduce the number for performance but this make it less secure | ||
|
||
init { | ||
val keyLength = when (type) { | ||
EncryptionType.NONE -> 0 | ||
EncryptionType.AES128 -> 128 | ||
EncryptionType.AES192 -> 192 | ||
EncryptionType.AES256 -> 256 | ||
} | ||
cipher = Cipher.getInstance("AES_$keyLength/CBC/PKCS5PADDING") | ||
val salt = ByteArray(128) | ||
val secureRandom = SecureRandom() | ||
secureRandom.nextBytes(salt) | ||
|
||
val spec = PBEKeySpec(passphrase.toCharArray(), salt, iterations, keyLength) | ||
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") | ||
val key = factory.generateSecret(spec) | ||
cipher.init(Cipher.ENCRYPT_MODE, key) | ||
} | ||
|
||
fun encrypt(bytes: ByteArray): ByteArray { | ||
return cipher.doFinal(bytes) | ||
} | ||
|
||
fun encrypt(bytes: ByteArray, offset: Int, length: Int): ByteArray { | ||
return cipher.doFinal(bytes, offset, length) | ||
} | ||
} |