我有一个使用 AES 加密来加密字符串的 Dart 应用程序,并且我正在尝试在 Kotlin 应用程序中解密该字符串。但是,当我尝试解密时,遇到 javax.crypto.BadPaddingException。我无法修改Dart代码,所以我需要调整Kotlin代码才能正确解密数据。
以下是Dart加密代码的相关部分:
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';
class CryptoService {
static String encryptString(String input) {
const keyString = "ABCdefg1234!!";
final keyBytes = sha256.convert(utf8.encode(keyString)).bytes;
final key = Key(Uint8List.fromList(keyBytes));
final iv = IV.fromSecureRandom(16);
final encrypter = Encrypter(AES(key));
final encrypted = encrypter.encrypt(input, iv: iv);
final combined = iv.bytes + encrypted.bytes;
return base64Url.encode(combined);
}
static String decryptString(String encoded) {
const keyString = "ABCdefg1234!!";
final keyBytes = sha256.convert(utf8.encode(keyString)).bytes;
final key = Key(Uint8List.fromList(keyBytes));
final encrypter = Encrypter(AES(key));
final combinedBytes = base64Url.decode(encoded);
final ivBytes = combinedBytes.sublist(0, 16);
final encryptedBytes = combinedBytes.sublist(16);
final iv = IV(Uint8List.fromList(ivBytes));
final encrypted = Encrypted(encryptedBytes);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
return decrypted;
}
}
void main() {
print(CryptoService.encryptString("abcdef"));
}
这是应该解密它的 Kotlin 代码:
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.*
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.security.SecureRandom
object CryptoService {
private const val keyString = "ABCdefg1234!!"
private fun generateKey(): SecretKey {
val keyBytes = MessageDigest.getInstance("SHA-256").digest(keyString.toByteArray(StandardCharsets.UTF_8))
return SecretKeySpec(keyBytes, "AES")
}
fun encryptString(input: String): String {
val key = generateKey()
val iv = ByteArray(16).apply { SecureRandom().nextBytes(this) }
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding").apply {
init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(iv))
}
val encryptedBytes = cipher.doFinal(input.toByteArray(StandardCharsets.UTF_8))
val combined = iv + encryptedBytes
return Base64.getUrlEncoder().encodeToString(combined)
}
fun decryptString(encoded: String): String {
val key = generateKey()
val combinedBytes = Base64.getUrlDecoder().decode(encoded)
val iv = combinedBytes.sliceArray(0 until 16)
val encryptedBytes = combinedBytes.sliceArray(16 until combinedBytes.size)
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding").apply {
init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
}
val decryptedBytes = cipher.doFinal(encryptedBytes)
return String(decryptedBytes, StandardCharsets.UTF_8)
}
}
fun main() {
println(CryptoService.decryptString("FzaO3XI3ZVtUDAdM1So357dhQwg37fh0vzVr6jkPDaY="))
println("end")
}
我收到的错误消息是:
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad (:-1)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer (:-1)
at com.sun.crypto.provider.CipherCore.doFinal (:-1)
如何调整 Kotlin 代码以正确解密 Dart 应用程序加密的数据?
我通过切换到 AES/CTR 模式并使用 Bouncy Castle 在 Kotlin 中进行加密和解密,成功解决了 Kotlin 和 Dart 加密之间的兼容性问题。以下是工作解决方案:
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.*
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec
import java.security.SecureRandom
import org.bouncycastle.jce.provider.BouncyCastleProvider
import javax.crypto.SecretKey
object CryptoService {
private const val keyString = "ABCdefg1234!!"
init {
Security.addProvider(BouncyCastleProvider())
}
private fun generateKey(): SecretKey {
val keyBytes = MessageDigest.getInstance("SHA-256").digest(keyString.toByteArray(StandardCharsets.UTF_8))
return SecretKeySpec(keyBytes, "AES")
}
fun encryptString(input: String): String {
val key = generateKey()
val iv = ByteArray(16).apply { SecureRandom().nextBytes(this) }
val cipher = Cipher.getInstance("AES/CTR/PKCS5Padding", "BC").apply {
init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(iv))
}
val encryptedBytes = cipher.doFinal(input.toByteArray(StandardCharsets.UTF_8))
val combined = iv + encryptedBytes
return Base64.getUrlEncoder().encodeToString(combined)
}
fun decryptString(encoded: String): String {
val key = generateKey()
val combinedBytes = Base64.getUrlDecoder().decode(encoded)
val iv = combinedBytes.sliceArray(0 until 16)
val encryptedBytes = combinedBytes.sliceArray(16 until combinedBytes.size)
val cipher = Cipher.getInstance("AES/CTR/PKCS5Padding", "BC").apply {
init(Cipher.DECRYPT_MODE, key, IvParameterSpec(iv))
}
val decryptedBytes = cipher.doFinal(encryptedBytes)
return String(decryptedBytes, StandardCharsets.UTF_8)
}
}
fun main() {
println(CryptoService.decryptString("FzaO3XI3ZVtUDAdM1So357dhQwg37fh0vzVr6jkPDaY="))
println("end")
}
该解决方案使用 AES/CTR 模式(Counter Mode),这似乎更符合 Dart 的默认加密行为。正如评论者 dave_thompson_085 所指出的,Dart 似乎默认使用计数器模式。通过在 Kotlin 中使用 AES/CTR/PKCS5Padding 和 Bouncy Castle 提供程序 (BC),结果与 Dart 的加密/解密过程兼容。