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

Commit

Permalink
Add v1 AES key generator
Browse files Browse the repository at this point in the history
  • Loading branch information
Cach30verfl0w committed Jun 12, 2024
1 parent e006e77 commit aa0dc47
Show file tree
Hide file tree
Showing 14 changed files with 141 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ data class CipherContext<C>(val spec: CipherSpec, val key: Key, val internalCont
* - [CipherDelegate.initializer] (required): The initializer of the cipher context
* - [CipherDelegate.encrypt] (required): The method to encrypt specific data with the context
* - [CipherDelegate.decrypt] (required): The method to decrypt specific data with the context
* - [CipherDelegate.close] (optional): The method called when the cipher is being closed
*
* @author Cedric Hammes
* @since 11/06/2024
Expand All @@ -37,6 +38,7 @@ class CipherDelegate<C: Any> {
private lateinit var initializer: (CipherSpec, Key) -> CipherContext<C>
private lateinit var encrypt: ((CipherContext<C>, ByteArray) -> ByteArray)
private lateinit var decrypt: ((CipherContext<C>, ByteArray) -> ByteArray)
private var close: (CipherContext<C>) -> Unit = {}

/**
* This method creates a new cipher object as a wrapper around the delegate functions with the
Expand Down Expand Up @@ -67,6 +69,7 @@ class CipherDelegate<C: Any> {
return decrypt.invoke(this.context!!, data)
}

override fun close() { close() }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ import io.karma.advcrypto.wrapper.Hasher
class HasherDelegate<C> {
private lateinit var initialize: () -> C
private lateinit var hash: (C, ByteArray) -> String
private var close: (CipherContext<C>) -> Unit = {}

fun createHasher(): Hasher {
return object: Hasher {
val context = initialize()
override fun hash(data: ByteArray): String = hash(context, data)
override fun close() { close() }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ class KeyGeneratorDelegate<C: Any>(
override fun generateKeyPair(): KeyPair {
return keyPairGenerator!!.invoke(context!!)
}

}
}

Expand All @@ -96,14 +95,15 @@ class KeyGeneratorDelegate<C: Any>(
return object: KeyGenerator {
private var context: KeyGenContext<C>? = null

override fun initialize(spec: KeyGeneratorSpec) {
override fun initialize(spec: KeyGeneratorSpec): KeyGenerator {
context = initializer(spec)
return this
}

override fun generateKey(): Key {
return keyGenerator!!.invoke(context!!)
}

override fun close() {}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import io.karma.advcrypto.wrapper.Signature
* - [SignatureDelegate.initVerify] (required): Initialize the context for signature verification
* - [SignatureDelegate.sign] (required): Sign the specified content with the context created before
* - [SignatureDelegate.verify] (required): Verify the specified signature with the original content
* - [SignatureDelegate.close] (optional): Called when the signature is being closed
* and the context created before.
*
* @author Cedric Hammes
Expand All @@ -39,6 +40,7 @@ class SignatureDelegate<C: Any> {
private lateinit var initSign: (C, Key) -> Unit
private lateinit var sign: (C, ByteArray) -> ByteArray
private lateinit var verify: (C, ByteArray, ByteArray) -> Boolean
private var close: (CipherContext<C>) -> Unit = {}

/**
* This method creates a new signature that delegates through this functions to the original
Expand All @@ -60,7 +62,7 @@ class SignatureDelegate<C: Any> {

override fun verify(signature: ByteArray, original: ByteArray): Boolean =
this@SignatureDelegate.verify(context, signature, original)

override fun close() { close() }
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ import io.karma.advcrypto.algorithm.specs.CipherSpec
* @author Cedric Hammes
* @since 11/06/2024
*/
interface Cipher {
@OptIn(ExperimentalStdlibApi::class)
interface Cipher: AutoCloseable {

/**
* This method initializes the cipher with the specified specification. This specification is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ package io.karma.advcrypto.wrapper

import io.karma.advcrypto.Providers

interface Hasher {
@OptIn(ExperimentalStdlibApi::class)
interface Hasher: AutoCloseable {

fun hash(data: ByteArray): String

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import io.karma.advcrypto.keys.Key
* @author Cedric Hammes
* @since 11/06/2024
*/
interface KeyGenerator {
@OptIn(ExperimentalStdlibApi::class)
interface KeyGenerator: AutoCloseable {

/**
* This method initializes the key generator with the specified specification. This
Expand All @@ -37,7 +38,7 @@ interface KeyGenerator {
* @author Cedric Hammes
* @since 11/06/2024
*/
fun initialize(spec: KeyGeneratorSpec)
fun initialize(spec: KeyGeneratorSpec): KeyGenerator

/**
* This method generates a key with the specification defined before. This method will throw an
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import io.karma.advcrypto.Providers
import io.karma.advcrypto.algorithm.delegates.SignatureDelegate
import io.karma.advcrypto.keys.Key

interface Signature {
@OptIn(ExperimentalStdlibApi::class)
interface Signature: AutoCloseable {

fun initVerify(key: Key)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2024 Cach30verfl0w
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.karma.advcrypto.linux.keys

import io.karma.advcrypto.keys.Key
import io.karma.advcrypto.linux.utils.SecureHeap
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.UByteVar
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.toKString
import libssl.ERR_func_error_string
import libssl.ERR_get_error
import libssl.RAND_bytes

@OptIn(ExperimentalForeignApi::class, ExperimentalStdlibApi::class)
class OpenSSLKey(private val secureHeap: SecureHeap, val keySize: Int,
override val purposes: UByte, override val algorithm: String): AutoCloseable, Key {
private val rawDataPtr = secureHeap.allocate((keySize / 8).toULong()).reinterpret<UByteVar>()

override fun close() {
secureHeap.free((keySize / 8).toULong(), rawDataPtr)
}

companion object {
fun generateRandom(secureHeap: SecureHeap, keySize: Int, purposes: UByte,
algorithm: String): OpenSSLKey =
OpenSSLKey(secureHeap, keySize, purposes, algorithm).apply {
if (RAND_bytes(rawDataPtr, 1) != 1) {
throw Exception(ERR_func_error_string(ERR_get_error())?.toKString())
}
}
}


}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2024 Cach30verfl0w
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package io.karma.advcrypto.linux.providers

import io.karma.advcrypto.AbstractProvider
import io.karma.advcrypto.algorithm.delegates.KeyGenContext
import io.karma.advcrypto.keys.Key
import io.karma.advcrypto.linux.keys.OpenSSLKey
import io.karma.advcrypto.linux.utils.SecureHeap

class OpenSSLCryptoProvider: AbstractProvider(
"Default",
"This class provides access to the default asymmetric and symmetric algorithms",
"1.0.0-Dev"
) {
private val secureHeap = SecureHeap(UShort.MAX_VALUE.toULong() + 1u, 0u) // TODO: How to free with good API design

init {
algorithm("AES") {
keyGenerator<Unit>(Key.PURPOSES_SYMMETRIC, arrayOf(128, 196, 256), 256) {
initializer { spec -> KeyGenContext(spec, Unit) }
generateKey { context ->
OpenSSLKey.generateRandom(
secureHeap,
context.generatorSpec.keySize?: defaultKeySize,
context.generatorSpec.purposes,
"AES"
)
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.karma.advcrypto.linux.tests

import io.karma.advcrypto.Providers
import io.karma.advcrypto.algorithm.specs.KeyGeneratorSpec
import io.karma.advcrypto.keys.Key
import io.karma.advcrypto.linux.keys.OpenSSLKey
import io.karma.advcrypto.linux.providers.OpenSSLCryptoProvider
import io.karma.advcrypto.wrapper.KeyGenerator
import kotlin.test.Test

class KeyGeneratorTests {

@Test
fun testAES() {
if (Providers.getProviderByName("Default") == null) {
Providers.addProvider(OpenSSLCryptoProvider())
}

(KeyGenerator.getInstance("AES")
.initialize(KeyGeneratorSpec.Builder(Key.PURPOSES_SYMMETRIC).setKeySize(256).build())
.generateKey() as OpenSSLKey).close()
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import kotlinx.cinterop.ULongVar
import kotlinx.cinterop.pointed
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.value
import libssl.free
import kotlin.experimental.ExperimentalNativeApi
import kotlin.test.Test

Expand Down
2 changes: 1 addition & 1 deletion kmp-advcrypto/src/nativeInterop/cinterop/libssl.def
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
headers = openssl/crypto.h openssl/err.h
headers = openssl/crypto.h openssl/err.h openssl/aes.h openssl/rand.h openssl/evp.h
linkerOpts = -L/usr/lib/x86_64-linux-gnu -L/usr/lib -ldl -lpthread -lc -lm -lssl -lcrypto
compilerOpts = -I/usr/include -I/usr/include/x86_64-linux-gnu

0 comments on commit aa0dc47

Please sign in to comment.