Skip to content
This repository has been archived by the owner on Aug 12, 2024. It is now read-only.

Commit

Permalink
Finish tryParseAsPEM method
Browse files Browse the repository at this point in the history
  • Loading branch information
Cach30verfl0w committed Jun 14, 2024
1 parent de284ad commit e90a1d8
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,9 @@ import libssl.OBJ_nid2sn

@OptIn(ExperimentalForeignApi::class)
class OpenSSLPKey(private val rawKey: CPointer<EVP_PKEY>, override val purposes: UByte,
override val type: KeyType): Key {
override val type: KeyType, override val format: KeyFormat = KeyFormat.PEM): Key { // TODO: Derive from encoded from default
@InsecureCryptoApi
override val encoded: ByteArray? = null
override val format: KeyFormat = KeyFormat.PEM // TODO: Derive from encoded content

override val algorithm: String = when(val baseId = EVP_PKEY_get_base_id(rawKey)) {
EVP_PKEY_RSA -> "RSA"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
package io.karma.advcrypto.linux.utils

import io.karma.advcrypto.keys.Key
import io.karma.advcrypto.keys.enum.KeyFormat
import io.karma.advcrypto.keys.enum.KeyType
import io.karma.advcrypto.linux.keys.OpenSSLPKey
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.ExperimentalForeignApi
Expand All @@ -39,27 +42,27 @@ object KeyDetectionUtil {
BIO_write(this, pointer, size.toInt())
}?: throw RuntimeException("Error while writing key into secure memory BIO")

private fun tryParseAsPEM(pointer: CPointer<ByteVar>, size: ULong): Key? {
fun getPEMKey(pointer: CPointer<ByteVar>, size: ULong): Pair<CPointer<EVP_PKEY>, Boolean>? {
private fun tryParseAsPEM(pointer: CPointer<ByteVar>, size: ULong, purposes: UByte): Key? {
fun getPEMKey(pointer: CPointer<ByteVar>, size: ULong): Pair<CPointer<EVP_PKEY>, KeyType>? {
val privateKeyBuffer = createSecureMemoryBuffer(pointer, size)
val privateKey = PEM_read_bio_PrivateKey(privateKeyBuffer, null, null, null)
BIO_free(privateKeyBuffer)
if (privateKey != null) {
return Pair(privateKey, true)
return Pair(privateKey, KeyType.PRIVATE)
}

val publicKeyBuffer = createSecureMemoryBuffer(pointer, size)
val publicKey = PEM_read_bio_PUBKEY(publicKeyBuffer, null, null, null)
BIO_free(publicKeyBuffer)
if (publicKey != null) {
return Pair(publicKey, false)
return Pair(publicKey, KeyType.PUBLIC)
}
return null
}

val pemParsedKey = getPEMKey(pointer, size)
if (pemParsedKey != null) {

return OpenSSLPKey(pemParsedKey.first, purposes, pemParsedKey.second, KeyFormat.PEM)
}
return null
}
Expand Down

0 comments on commit e90a1d8

Please sign in to comment.