Add methods for reading RSA keys from memory

Signed-off-by: Graham <gpe@openrs2.org>
Graham 4 years ago
parent 1155eb7eb8
commit cf6e7cf8e7
  1. 37
      crypto/src/main/kotlin/org/openrs2/crypto/Rsa.kt

@ -22,6 +22,7 @@ import org.bouncycastle.util.io.pem.PemReader
import org.bouncycastle.util.io.pem.PemWriter import org.bouncycastle.util.io.pem.PemWriter
import org.openrs2.util.io.useAtomicBufferedWriter import org.openrs2.util.io.useAtomicBufferedWriter
import java.io.IOException import java.io.IOException
import java.io.Reader
import java.math.BigInteger import java.math.BigInteger
import java.nio.file.Files import java.nio.file.Files
import java.nio.file.Path import java.nio.file.Path
@ -133,7 +134,13 @@ public object Rsa {
} }
public fun readPublicKey(path: Path): RSAKeyParameters { public fun readPublicKey(path: Path): RSAKeyParameters {
val der = readSinglePemObject(path, PUBLIC_KEY) Files.newBufferedReader(path).use { reader ->
return readPublicKey(reader)
}
}
public fun readPublicKey(reader: Reader): RSAKeyParameters {
val der = readSinglePemObject(reader, PUBLIC_KEY)
val spki = SubjectPublicKeyInfo.getInstance(der) val spki = SubjectPublicKeyInfo.getInstance(der)
validateAlgorithm(spki.algorithm) validateAlgorithm(spki.algorithm)
@ -148,7 +155,13 @@ public object Rsa {
} }
public fun readPrivateKey(path: Path): RSAPrivateCrtKeyParameters { public fun readPrivateKey(path: Path): RSAPrivateCrtKeyParameters {
val der = readSinglePemObject(path, PRIVATE_KEY) Files.newBufferedReader(path).use { reader ->
return readPrivateKey(reader)
}
}
public fun readPrivateKey(reader: Reader): RSAPrivateCrtKeyParameters {
val der = readSinglePemObject(reader, PRIVATE_KEY)
val pki = PrivateKeyInfo.getInstance(der) val pki = PrivateKeyInfo.getInstance(der)
validateAlgorithm(pki.privateKeyAlgorithm) validateAlgorithm(pki.privateKeyAlgorithm)
@ -181,19 +194,19 @@ public object Rsa {
} }
} }
private fun readSinglePemObject(path: Path, type: String): ByteArray { private fun readSinglePemObject(reader: Reader, type: String): ByteArray {
PemReader(Files.newBufferedReader(path)).use { val pemReader = PemReader(reader)
val obj = it.readPemObject()
if (obj == null || obj.type != type || it.readPemObject() != null) {
throw IOException("Expecting single $type PEM object")
}
if (obj.headers.isNotEmpty()) { val obj = pemReader.readPemObject()
throw IOException("PEM headers unsupported") if (obj == null || obj.type != type || pemReader.readPemObject() != null) {
} throw IOException("Expecting single $type PEM object")
}
return obj.content if (obj.headers.isNotEmpty()) {
throw IOException("PEM headers unsupported")
} }
return obj.content
} }
private fun writeSinglePemObject(path: Path, type: String, content: ByteArray) { private fun writeSinglePemObject(path: Path, type: String, content: ByteArray) {

Loading…
Cancel
Save