1

我在尝试解码 InputStream 时遇到了 BadPaddingException。当我使用杰克逊时,我能够对 OutputStream/InputStream 进行编码/解码,但是当我尝试使用 Okio 时,它会抛出 BadPaddingException。

getEncodeStream() 和 getDecodeStream() 方法在 Jackson 上运行良好,但似乎与 Okio 不同。

编码文件的输出 = FxGOXOwOWzBGMa7+u+E3TvNTOjFv/vKKsSt+Q1+QsedtluVa6sULFhOImRO+pYQp43h/HsrssNm0 UpxcC2cvbM4+ix9nH5YUfCK0NJjzT2iR9tJG8tXTrLSCz/B/6WEQ

@Test
fun main() {
    val password = "password"
    val file1 = File("src/test/resources/okioTest")
    if(!file1.exists())
        file1.createNewFile()

    //create output stream
    val outputStream = FileOutputStream(file1)
    val encodeStream = getEncodeStream(password, outputStream)
    val sink = Okio.buffer(Okio.sink(encodeStream))
    sink.write("something to test something to test something to test something to test something to test something to test".toByteArray())
    sink.emit()

    val inputStream = FileInputStream(file1)
    val decodeStream = getDecodeStream(password, inputStream)
    val source = Okio.buffer(Okio.source(decodeStream))
    val result = source.readUtf8()
    Timber.d(result)
}

fun getEncodeStream(keyString: String, stream: OutputStream): OutputStream {
    val keySpec = getKey(keyString)
    // IMPORTANT TO GET SAME RESULTS ON iOS and ANDROID
    val iv = ByteArray(16)
    Arrays.fill(iv, 0x00.toByte())
    val ivParameterSpec = IvParameterSpec(iv)

    // Cipher is not thread safe
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec)
    val base64stream = Base64OutputStream(stream, Base64.DEFAULT)

    // Log.d("jacek", "Encrypted: $stringToEncode -> $encrypedValue")
    return CipherOutputStream(base64stream, cipher)
}

fun getDecodeStream(password: String, stream: InputStream): InputStream {

    val key = getKey(password)
    val iv = ByteArray(16)
    Arrays.fill(iv, 0x00.toByte())
    val ivParameterSpec = IvParameterSpec(iv)
    val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
    cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec)
    val base64stream = Base64InputStream(stream, Base64.DEFAULT)
    return CipherInputStream(base64stream, cipher)
}

@Throws(UnsupportedEncodingException::class)
fun getKey(password: String): SecretKeySpec {

    // You can change it to 128 if you wish
    val keyLength = 256
    val keyBytes = ByteArray(keyLength / 8)
    // explicitly fill with zeros
    Arrays.fill(keyBytes, 0x0.toByte())

    // if password is shorter then key length, it will be zero-padded
    // to key length
    val passwordBytes = password.toByteArray(charset("UTF-8"))
    val length = if (passwordBytes.size < keyBytes.size) passwordBytes.size else keyBytes.size
    System.arraycopy(passwordBytes, 0, keyBytes, 0, length)
    return SecretKeySpec(keyBytes, "AES")
}
4

0 回答 0