BadPaddingException:尝试解码时填充块已损坏

时间:2019-03-19 17:09:35

标签: android encoding base64 moshi okio

我在尝试解码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")
}

0 个答案:

没有答案