1
0
Fork 0
mirror of https://github.com/pgpainless/pgpainless.git synced 2025-09-10 18:59:39 +02:00

Kotlin conversion: Cleartext Signature Framework

This commit is contained in:
Paul Schaub 2023-08-30 15:59:25 +02:00
parent 8d67820f50
commit 48af91efbf
Signed by: vanitasvitae
GPG key ID: 62BEE9264BF17311
10 changed files with 297 additions and 337 deletions

View file

@ -0,0 +1,153 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.decryption_verification.cleartext_signatures
import org.bouncycastle.bcpg.ArmoredInputStream
import org.bouncycastle.openpgp.PGPSignatureList
import org.bouncycastle.util.Strings
import org.pgpainless.exception.WrongConsumingMethodException
import org.pgpainless.implementation.ImplementationFactory
import org.pgpainless.util.ArmoredInputStreamFactory
import java.io.*
import kotlin.jvm.Throws
/**
* Utility class to deal with cleartext-signed messages.
* Based on Bouncycastle's [org.bouncycastle.openpgp.examples.ClearSignedFileProcessor].
*/
class ClearsignedMessageUtil {
companion object {
/**
* Dearmor a clearsigned message, detach the inband signatures and write the plaintext message to the provided
* messageOutputStream.
*
* @param clearsignedInputStream input stream containing a clearsigned message
* @param messageOutputStream output stream to which the dearmored message shall be written
* @return signatures
*
* @throws IOException if the message is not clearsigned or some other IO error happens
* @throws WrongConsumingMethodException in case the armored message is not cleartext signed
*/
@JvmStatic
@Throws(WrongConsumingMethodException::class, IOException::class)
fun detachSignaturesFromInbandClearsignedMessage(
clearsignedInputStream: InputStream,
messageOutputStream: OutputStream): PGPSignatureList {
val input: ArmoredInputStream = if (clearsignedInputStream is ArmoredInputStream) {
clearsignedInputStream
} else {
ArmoredInputStreamFactory.get(clearsignedInputStream)
}
if (!input.isClearText) {
throw WrongConsumingMethodException("Message isn't using the Cleartext Signature Framework.")
}
BufferedOutputStream(messageOutputStream).use { output ->
val lineOut = ByteArrayOutputStream()
var lookAhead = readInputLine(lineOut, input)
val lineSep = getLineSeparator()
if (lookAhead != -1 && input.isClearText) {
var line = lineOut.toByteArray()
output.write(line, 0, getLengthWithoutSeparatorOrTrailingWhitespace(line))
while (lookAhead != -1 && input.isClearText) {
lookAhead = readInputLine(lineOut, lookAhead, input)
line = lineOut.toByteArray()
output.write(lineSep)
output.write(line, 0, getLengthWithoutSeparatorOrTrailingWhitespace(line))
}
} else {
if (lookAhead != -1) {
val line = lineOut.toByteArray()
output.write(line, 0, getLengthWithoutSeparatorOrTrailingWhitespace(line))
}
}
}
val objectFactory = ImplementationFactory.getInstance().getPGPObjectFactory(input)
val next = objectFactory.nextObject() ?: PGPSignatureList(arrayOf())
return next as PGPSignatureList
}
@JvmStatic
private fun readInputLine(bOut: ByteArrayOutputStream, fIn: InputStream): Int {
bOut.reset()
var lookAhead = -1
var ch: Int
while (fIn.read().also { ch = it } >= 0) {
bOut.write(ch)
if (ch == '\r'.code || ch == '\n'.code) {
lookAhead = readPassedEOL(bOut, ch, fIn)
break
}
}
return lookAhead
}
@JvmStatic
private fun readInputLine(bOut: ByteArrayOutputStream, lookAhead: Int, fIn: InputStream): Int {
var mLookAhead = lookAhead
bOut.reset()
var ch = mLookAhead
do {
bOut.write(ch)
if (ch == '\r'.code || ch == '\n'.code) {
mLookAhead = readPassedEOL(bOut, ch, fIn)
break
}
} while (fIn.read().also { ch = it } >= 0)
if (ch < 0) {
mLookAhead = -1
}
return mLookAhead
}
@JvmStatic
private fun readPassedEOL(bOut: ByteArrayOutputStream, lastCh: Int, fIn: InputStream): Int {
var lookAhead = fIn.read()
if (lastCh == '\r'.code && lookAhead == '\n'.code) {
bOut.write(lookAhead)
lookAhead = fIn.read()
}
return lookAhead
}
@JvmStatic
private fun getLineSeparator(): ByteArray {
val nl = Strings.lineSeparator()
val nlBytes = ByteArray(nl.length)
for (i in nlBytes.indices) {
nlBytes[i] = nl[i].code.toByte()
}
return nlBytes
}
@JvmStatic
private fun getLengthWithoutSeparatorOrTrailingWhitespace(line: ByteArray): Int {
var end = line.size - 1
while (end >= 0 && isWhiteSpace(line[end])) {
end--
}
return end + 1
}
@JvmStatic
private fun isLineEnding(b: Byte): Boolean {
return b == '\r'.code.toByte() || b == '\n'.code.toByte()
}
@JvmStatic
private fun isWhiteSpace(b: Byte): Boolean {
return isLineEnding(b) || b == '\t'.code.toByte() || b == ' '.code.toByte()
}
}
}

View file

@ -0,0 +1,29 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.decryption_verification.cleartext_signatures
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
/**
* Implementation of the [MultiPassStrategy].
* This class keeps the read data in memory by caching the data inside a [ByteArrayOutputStream].
*
* Note, that this class is suitable and efficient for processing small amounts of data.
* For larger data like encrypted files, use of the [WriteToFileMultiPassStrategy] is recommended to
* prevent [OutOfMemoryError] and other issues.
*/
class InMemoryMultiPassStrategy : MultiPassStrategy {
private val cache = ByteArrayOutputStream()
override val messageOutputStream: ByteArrayOutputStream
get() = cache
override val messageInputStream: ByteArrayInputStream
get() = ByteArrayInputStream(getBytes())
fun getBytes(): ByteArray = messageOutputStream.toByteArray()
}

View file

@ -0,0 +1,71 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.decryption_verification.cleartext_signatures
import java.io.*
/**
* Since for verification of cleartext signed messages, we need to read the whole data twice in order to verify signatures,
* a strategy for how to cache the read data is required.
* Otherwise, large data kept in memory could cause an [OutOfMemoryError] or other issues.
*
* This is an Interface that describes a strategy to deal with the fact that detached signatures require multiple passes
* to do verification.
*
* This interface can be used to write the signed data stream out via [messageOutputStream] and later
* get access to the data again via [messageInputStream].
* Thereby the detail where the data is being stored (memory, file, etc.) can be abstracted away.
*/
interface MultiPassStrategy {
/**
* Provide an [OutputStream] into which the signed data can be read into.
*
* @return output stream
* @throws IOException io error
*/
val messageOutputStream: OutputStream
/**
* Provide an [InputStream] which contains the data that was previously written away in
* [messageOutputStream].
*
* As there may be multiple signatures that need to be processed, each call of this method MUST return
* a new [InputStream].
*
* @return input stream
* @throws IOException io error
*/
val messageInputStream: InputStream
companion object {
/**
* Write the message content out to a file and re-read it to verify signatures.
* This strategy is best suited for larger messages (e.g. plaintext signed files) which might not fit into memory.
* After the message has been processed completely, the messages content are available at the provided file.
*
* @param file target file
* @return strategy
*/
@JvmStatic
fun writeMessageToFile(file: File): MultiPassStrategy {
return WriteToFileMultiPassStrategy(file)
}
/**
* Read the message content into memory.
* This strategy is best suited for small messages which fit into memory.
* After the message has been processed completely, the message content can be accessed by calling
* [ByteArrayOutputStream.toByteArray] on [messageOutputStream].
*
* @return strategy
*/
@JvmStatic
fun keepMessageInMemory(): InMemoryMultiPassStrategy {
return InMemoryMultiPassStrategy()
}
}
}

View file

@ -0,0 +1,43 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.pgpainless.decryption_verification.cleartext_signatures
import java.io.*
/**
* Implementation of the [MultiPassStrategy].
* When processing signed data the first time, the data is being written out into a file.
* For the second pass, that file is being read again.
*
* This strategy is recommended when larger amounts of data need to be processed.
* For smaller files, [InMemoryMultiPassStrategy] yields higher efficiency.
*
* @param file file to write the data to and read from
*/
class WriteToFileMultiPassStrategy(
private val file: File
) : MultiPassStrategy {
override val messageOutputStream: OutputStream
@Throws(IOException::class)
get() {
if (!file.exists()) {
if (!file.createNewFile()) {
throw IOException("New file '${file.absolutePath}' could not be created.")
}
}
return FileOutputStream(file)
}
override val messageInputStream: InputStream
@Throws(IOException::class)
get() {
if (!file.exists()) {
throw IOException("File '${file.absolutePath}' does no longer exist.")
}
return FileInputStream(file)
}
}