Fix bad padding exception

This commit is contained in:
J-Jamet
2021-03-29 12:42:53 +02:00
parent 8cedc313cf
commit 17029ce67c

View File

@@ -7,6 +7,7 @@ import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.Security
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.IvParameterSpec
@@ -39,7 +40,16 @@ object CipherFactory {
@Throws(NoSuchAlgorithmException::class, NoSuchPaddingException::class, InvalidKeyException::class, InvalidAlgorithmParameterException::class)
fun getTwofish(opmode: Int, key: ByteArray, IV: ByteArray): Cipher {
val cipher: Cipher = Cipher.getInstance("Twofish/CBC/PKCS7PADDING")
val cipher: Cipher = try {
Cipher.getInstance("Twofish/CBC/PKCS7PADDING")
} catch (e: BadPaddingException) {
// Retry with other padding if don't work
if (opmode == Cipher.ENCRYPT_MODE) {
Cipher.getInstance("Twofish/CBC/ZeroBytePadding")
} else {
Cipher.getInstance("Twofish/CBC/NoPadding")
}
}
cipher.init(opmode, SecretKeySpec(key, "AES"), IvParameterSpec(IV))
return cipher
}