From 9012ef92ed810f4a08b5f01cd2c18430a277eacf Mon Sep 17 00:00:00 2001 From: pacien Date: Sun, 5 Aug 2018 22:12:46 +0200 Subject: Code style --- .../org/pacien/tincapp/activities/BaseActivity.kt | 10 +-- .../pacien/tincapp/activities/ConfigureActivity.kt | 6 +- .../org/pacien/tincapp/activities/StartActivity.kt | 4 +- .../pacien/tincapp/activities/StatusActivity.kt | 2 +- .../java/org/pacien/tincapp/commands/Executor.kt | 2 +- .../main/java/org/pacien/tincapp/commands/Tincd.kt | 2 +- .../main/java/org/pacien/tincapp/context/App.kt | 2 +- .../java/org/pacien/tincapp/context/AppInfo.kt | 6 +- .../java/org/pacien/tincapp/context/AppPaths.kt | 8 +-- .../java/org/pacien/tincapp/data/CidrAddress.kt | 2 +- .../org/pacien/tincapp/data/TincConfiguration.kt | 6 +- .../tincapp/data/VpnInterfaceConfiguration.kt | 38 ++++++------ .../java/org/pacien/tincapp/extensions/Android.kt | 4 +- .../pacien/tincapp/extensions/VpnServiceBuilder.kt | 18 +++--- .../org/pacien/tincapp/intent/BroadcastMapper.kt | 2 +- .../main/java/org/pacien/tincapp/utils/PemUtils.kt | 72 +++++++++++++--------- 16 files changed, 100 insertions(+), 84 deletions(-) (limited to 'app/src/main/java') diff --git a/app/src/main/java/org/pacien/tincapp/activities/BaseActivity.kt b/app/src/main/java/org/pacien/tincapp/activities/BaseActivity.kt index 3e2bebd..4b1cb91 100644 --- a/app/src/main/java/org/pacien/tincapp/activities/BaseActivity.kt +++ b/app/src/main/java/org/pacien/tincapp/activities/BaseActivity.kt @@ -78,7 +78,7 @@ abstract class BaseActivity : AppCompatActivity() { resources.getString(R.string.app_license) + "\n\n" + AppInfo.all()) .setNeutralButton(R.string.action_open_project_website) { _, _ -> App.openURL(resources.getString(R.string.app_website_url)) } - .setPositiveButton(R.string.action_close, { _, _ -> Unit }) + .setPositiveButton(R.string.action_close) { _, _ -> Unit } .show() } @@ -96,13 +96,13 @@ abstract class BaseActivity : AppCompatActivity() { resources.getString(R.string.message_app_crash), resources.getString(R.string.message_crash_logged, AppPaths.appLogFile().absolutePath) ).joinToString("\n\n")) - .setNeutralButton(R.string.action_send_report, { _, _ -> + .setNeutralButton(R.string.action_send_report) { _, _ -> App.sendMail( resources.getString(R.string.app_dev_email), listOf(R.string.app_name, R.string.title_app_crash).joinToString(" / ", transform = resources::getString), AppPaths.appLogFile().let { if (it.exists()) it.readText() else "" }) - }) - .setPositiveButton(R.string.action_close, { _, _ -> Unit }) + } + .setPositiveButton(R.string.action_close) { _, _ -> Unit } .show() } @@ -111,5 +111,5 @@ abstract class BaseActivity : AppCompatActivity() { protected fun showProgressDialog(@StringRes msg: Int): AlertDialog = ProgressModal.show(this, getString(msg)) protected fun showErrorDialog(msg: String): AlertDialog = AlertDialog.Builder(this) .setTitle(R.string.title_error).setMessage(msg) - .setPositiveButton(R.string.action_close, { _, _ -> Unit }).show() + .setPositiveButton(R.string.action_close) { _, _ -> Unit }.show() } diff --git a/app/src/main/java/org/pacien/tincapp/activities/ConfigureActivity.kt b/app/src/main/java/org/pacien/tincapp/activities/ConfigureActivity.kt index 45a29bf..f823691 100644 --- a/app/src/main/java/org/pacien/tincapp/activities/ConfigureActivity.kt +++ b/app/src/main/java/org/pacien/tincapp/activities/ConfigureActivity.kt @@ -76,7 +76,7 @@ class ConfigureActivity : BaseActivity() { genDialog.new_net_name.text.toString(), genDialog.new_node_name.text.toString(), genDialog.new_passphrase.text.toString()) - }.setNegativeButton(R.string.action_cancel, { _, _ -> Unit }).show() + }.setNegativeButton(R.string.action_cancel) { _, _ -> Unit }.show() } fun openJoinNetworkDialog(@Suppress("UNUSED_PARAMETER") v: View) { @@ -87,7 +87,7 @@ class ConfigureActivity : BaseActivity() { joinDialog!!.net_name.text.toString(), joinDialog!!.invitation_url.text.toString(), joinDialog!!.join_passphrase.text.toString()) - }.setNegativeButton(R.string.action_cancel, { _, _ -> Unit }).show() + }.setNegativeButton(R.string.action_cancel) { _, _ -> Unit }.show() } fun openEncryptDecryptPrivateKeyDialog(@Suppress("UNUSED_PARAMETER") v: View) { @@ -98,7 +98,7 @@ class ConfigureActivity : BaseActivity() { encryptDecryptDialog!!.enc_dec_net_name.text.toString(), encryptDecryptDialog.enc_dec_current_passphrase.text.toString(), encryptDecryptDialog.enc_dec_new_passphrase.text.toString()) - }.setNegativeButton(R.string.action_cancel, { _, _ -> Unit }).show() + }.setNegativeButton(R.string.action_cancel) { _, _ -> Unit }.show() } private fun writeContent() { diff --git a/app/src/main/java/org/pacien/tincapp/activities/StartActivity.kt b/app/src/main/java/org/pacien/tincapp/activities/StartActivity.kt index fbcde81..4be1609 100644 --- a/app/src/main/java/org/pacien/tincapp/activities/StartActivity.kt +++ b/app/src/main/java/org/pacien/tincapp/activities/StartActivity.kt @@ -68,7 +68,7 @@ class StartActivity : BaseActivity() { } override fun onRefresh() { - val networks = AppPaths.confDir()?.list()?.toList() ?: emptyList() + val networks = AppPaths.confDir().list()?.toList() ?: emptyList() runOnUiThread { networkListAdapter?.setElements(networks) setPlaceholderVisibility() @@ -121,7 +121,7 @@ class StartActivity : BaseActivity() { AlertDialog.Builder(this@StartActivity) .setTitle(R.string.title_unlock_private_keys).setView(dialog) .setPositiveButton(R.string.action_unlock) { _, _ -> tryStart(passphrase = dialog.passphrase.text.toString()) } - .setNegativeButton(R.string.action_cancel, { _, _ -> Unit }) + .setNegativeButton(R.string.action_cancel) { _, _ -> Unit } .show() } } diff --git a/app/src/main/java/org/pacien/tincapp/activities/StatusActivity.kt b/app/src/main/java/org/pacien/tincapp/activities/StatusActivity.kt index cd64355..d5c3278 100644 --- a/app/src/main/java/org/pacien/tincapp/activities/StatusActivity.kt +++ b/app/src/main/java/org/pacien/tincapp/activities/StatusActivity.kt @@ -189,7 +189,7 @@ class StatusActivity : BaseActivity(), AdapterView.OnItemClickListener, SwipeRef private const val NOW = 0L fun getNodeNames(): CompletableFuture> = TincVpnService.getCurrentNetName()?.let { netName -> - Tinc.dumpNodes(netName).thenApply> { it.map { it.substringBefore(' ') } } + Tinc.dumpNodes(netName).thenApply> { list -> list.map { it.substringBefore(' ') } } } ?: Executor.supplyAsyncTask> { emptyList() } } } diff --git a/app/src/main/java/org/pacien/tincapp/commands/Executor.kt b/app/src/main/java/org/pacien/tincapp/commands/Executor.kt index 7630b61..9558b15 100644 --- a/app/src/main/java/org/pacien/tincapp/commands/Executor.kt +++ b/app/src/main/java/org/pacien/tincapp/commands/Executor.kt @@ -42,7 +42,7 @@ internal object Executor { /** * @return FAILED (-1) on error, forked child PID otherwise */ - private external fun forkExec(argcv: Array): Int + private external fun forkExec(args: Array): Int /** * @return FAILED (-1) on error, the exit status of the process otherwise diff --git a/app/src/main/java/org/pacien/tincapp/commands/Tincd.kt b/app/src/main/java/org/pacien/tincapp/commands/Tincd.kt index 86d2583..b55e9a1 100644 --- a/app/src/main/java/org/pacien/tincapp/commands/Tincd.kt +++ b/app/src/main/java/org/pacien/tincapp/commands/Tincd.kt @@ -31,7 +31,7 @@ object Tincd { .withOption("pidfile", AppPaths.pidFile(netName).absolutePath) .withOption("logfile", AppPaths.logFile(netName).absolutePath) .withOption("option", "DeviceType=fd") - .withOption("option", "Device=" + deviceFd) + .withOption("option", "Device=$deviceFd") .apply { if (ed25519PrivateKeyFd != null) withOption("option", "Ed25519PrivateKeyFile=/proc/self/fd/$ed25519PrivateKeyFd") } .apply { if (rsaPrivateKeyFd != null) withOption("option", "PrivateKeyFile=/proc/self/fd/$rsaPrivateKeyFd") }) } diff --git a/app/src/main/java/org/pacien/tincapp/context/App.kt b/app/src/main/java/org/pacien/tincapp/context/App.kt index 89d1c73..2d9151e 100644 --- a/app/src/main/java/org/pacien/tincapp/context/App.kt +++ b/app/src/main/java/org/pacien/tincapp/context/App.kt @@ -66,7 +66,7 @@ class App : Application() { AlertDialog.Builder(getContext(), R.style.Theme_AppCompat_Dialog) .setTitle(title).setMessage(msg) .apply { if (manualLink != null) setNeutralButton(R.string.action_open_manual) { _, _ -> openURL(manualLink) } } - .setPositiveButton(R.string.action_close, { _, _ -> Unit }) + .setPositiveButton(R.string.action_close) { _, _ -> Unit } .create().apply { window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR) }.show() } diff --git a/app/src/main/java/org/pacien/tincapp/context/AppInfo.kt b/app/src/main/java/org/pacien/tincapp/context/AppInfo.kt index a7f5439..76da98f 100644 --- a/app/src/main/java/org/pacien/tincapp/context/AppInfo.kt +++ b/app/src/main/java/org/pacien/tincapp/context/AppInfo.kt @@ -26,17 +26,17 @@ import org.pacien.tincapp.R * @author pacien */ object AppInfo { - fun appVersion(): String = App.getResources().getString( + private fun appVersion(): String = App.getResources().getString( R.string.info_version_format, BuildConfig.VERSION_NAME, BuildConfig.BUILD_TYPE) - fun androidVersion(): String = App.getResources().getString( + private fun androidVersion(): String = App.getResources().getString( R.string.info_running_on_format, Build.VERSION.CODENAME, Build.VERSION.RELEASE) - fun supportedABIs(): String = App.getResources().getString( + private fun supportedABIs(): String = App.getResources().getString( R.string.info_supported_abis_format, Build.SUPPORTED_ABIS.joinToString(",")) diff --git a/app/src/main/java/org/pacien/tincapp/context/AppPaths.kt b/app/src/main/java/org/pacien/tincapp/context/AppPaths.kt index ca9e03b..9ec4b69 100644 --- a/app/src/main/java/org/pacien/tincapp/context/AppPaths.kt +++ b/app/src/main/java/org/pacien/tincapp/context/AppPaths.kt @@ -46,10 +46,10 @@ object AppPaths { fun storageAvailable() = Environment.getExternalStorageState().let { it == Environment.MEDIA_MOUNTED && it != Environment.MEDIA_MOUNTED_READ_ONLY } - fun internalCacheDir() = App.getContext().cacheDir - fun cacheDir() = App.getContext().externalCacheDir - fun confDir() = App.getContext().getExternalFilesDir(null) - fun binDir() = File(App.getContext().applicationInfo.nativeLibraryDir) + private fun internalCacheDir() = App.getContext().cacheDir!! + fun cacheDir() = App.getContext().externalCacheDir!! + fun confDir() = App.getContext().getExternalFilesDir(null)!! + private fun binDir() = File(App.getContext().applicationInfo.nativeLibraryDir) fun confDir(netName: String) = File(confDir(), netName) fun hostsDir(netName: String) = File(confDir(netName), NET_HOSTS_DIR) diff --git a/app/src/main/java/org/pacien/tincapp/data/CidrAddress.kt b/app/src/main/java/org/pacien/tincapp/data/CidrAddress.kt index c6a9b1f..2d0577f 100644 --- a/app/src/main/java/org/pacien/tincapp/data/CidrAddress.kt +++ b/app/src/main/java/org/pacien/tincapp/data/CidrAddress.kt @@ -25,7 +25,7 @@ import org.apache.commons.configuration2.ex.ConversionException */ data class CidrAddress(val address: String, val prefix: Int) { companion object { - private val SEPARATOR = "/" + private const val SEPARATOR = "/" fun fromSlashSeparated(s: String) = try { CidrAddress(s.substringBefore(SEPARATOR), Integer.parseInt(s.substringAfter(SEPARATOR))) diff --git a/app/src/main/java/org/pacien/tincapp/data/TincConfiguration.kt b/app/src/main/java/org/pacien/tincapp/data/TincConfiguration.kt index 0eee2eb..c9339e0 100644 --- a/app/src/main/java/org/pacien/tincapp/data/TincConfiguration.kt +++ b/app/src/main/java/org/pacien/tincapp/data/TincConfiguration.kt @@ -30,11 +30,11 @@ data class TincConfiguration(val ed25519PrivateKeyFile: File? = null, val privateKeyFile: File? = null) { companion object { - private val KEY_ED25519_PRIVATE_KEY_FILE = "Ed25519PrivateKeyFile" - private val KEY_PRIVATE_KEY_FILE = "PrivateKeyFile" + private const val KEY_ED25519_PRIVATE_KEY_FILE = "Ed25519PrivateKeyFile" + private const val KEY_PRIVATE_KEY_FILE = "PrivateKeyFile" fun fromTincConfiguration(f: File) = fromTincConfiguration(Configurations().properties(f)) - fun fromTincConfiguration(c: Configuration) = TincConfiguration( + private fun fromTincConfiguration(c: Configuration) = TincConfiguration( c.getFile(KEY_ED25519_PRIVATE_KEY_FILE), c.getFile(KEY_PRIVATE_KEY_FILE)) } diff --git a/app/src/main/java/org/pacien/tincapp/data/VpnInterfaceConfiguration.kt b/app/src/main/java/org/pacien/tincapp/data/VpnInterfaceConfiguration.kt index d903769..daf04c8 100644 --- a/app/src/main/java/org/pacien/tincapp/data/VpnInterfaceConfiguration.kt +++ b/app/src/main/java/org/pacien/tincapp/data/VpnInterfaceConfiguration.kt @@ -44,22 +44,22 @@ data class VpnInterfaceConfiguration(val addresses: List = emptyLis val blocking: Boolean = false, val mtu: Int? = null) { companion object { - private val KEY_ADDRESSES = "Address" - private val KEY_ROUTES = "Route" - private val KEY_DNS_SERVERS = "DNSServer" - private val KEY_SEARCH_DOMAINS = "SearchDomain" - private val KEY_ALLOWED_APPLICATIONS = "AllowApplication" - private val KEY_DISALLOWED_APPLICATIONS = "DisallowApplication" - private val KEY_ALLOWED_FAMILIES = "AllowFamily" - private val KEY_ALLOW_BYPASS = "AllowBypass" - private val KEY_BLOCKING = "Blocking" - private val KEY_MTU = "MTU" + private const val KEY_ADDRESSES = "Address" + private const val KEY_ROUTES = "Route" + private const val KEY_DNS_SERVERS = "DNSServer" + private const val KEY_SEARCH_DOMAINS = "SearchDomain" + private const val KEY_ALLOWED_APPLICATIONS = "AllowApplication" + private const val KEY_DISALLOWED_APPLICATIONS = "DisallowApplication" + private const val KEY_ALLOWED_FAMILIES = "AllowFamily" + private const val KEY_ALLOW_BYPASS = "AllowBypass" + private const val KEY_BLOCKING = "Blocking" + private const val KEY_MTU = "MTU" - private val INVITATION_KEY_ADDRESSES = "Ifconfig" - private val INVITATION_KEY_ROUTES = "Route" + private const val INVITATION_KEY_ADDRESSES = "Ifconfig" + private const val INVITATION_KEY_ROUTES = "Route" fun fromIfaceConfiguration(f: File) = fromIfaceConfiguration(Configurations().properties(f)) - fun fromIfaceConfiguration(c: Configuration) = VpnInterfaceConfiguration( + private fun fromIfaceConfiguration(c: Configuration) = VpnInterfaceConfiguration( c.getCidrList(KEY_ADDRESSES), c.getCidrList(KEY_ROUTES), c.getStringList(KEY_DNS_SERVERS), @@ -72,7 +72,7 @@ data class VpnInterfaceConfiguration(val addresses: List = emptyLis c.getInteger(KEY_MTU, null)) fun fromInvitation(f: File) = fromInvitation(Configurations().properties(f)) - fun fromInvitation(c: Configuration) = VpnInterfaceConfiguration( + private fun fromInvitation(c: Configuration) = VpnInterfaceConfiguration( c.getStringList(INVITATION_KEY_ADDRESSES) .map { applyIgnoringException(CidrAddress.Companion::fromSlashSeparated, it) } .filterNotNull(), @@ -83,10 +83,10 @@ data class VpnInterfaceConfiguration(val addresses: List = emptyLis fun write(f: File) = FileBasedConfigurationBuilder(PropertiesConfiguration::class.java) .configure(Parameters().properties().setFile(f.apply { createNewFile() })).let { builder -> - builder.configuration.let { cfg -> - addresses.forEach { cfg.addProperty(KEY_ADDRESSES, it.toSlashSeparated()) } - routes.forEach { cfg.addProperty(KEY_ROUTES, it.toSlashSeparated()) } + builder.configuration.let { cfg -> + addresses.forEach { cfg.addProperty(KEY_ADDRESSES, it.toSlashSeparated()) } + routes.forEach { cfg.addProperty(KEY_ROUTES, it.toSlashSeparated()) } + } + builder.save() } - builder.save() - } } diff --git a/app/src/main/java/org/pacien/tincapp/extensions/Android.kt b/app/src/main/java/org/pacien/tincapp/extensions/Android.kt index 6563e40..d703c45 100644 --- a/app/src/main/java/org/pacien/tincapp/extensions/Android.kt +++ b/app/src/main/java/org/pacien/tincapp/extensions/Android.kt @@ -27,10 +27,10 @@ import org.pacien.tincapp.context.App * @author pacien */ object Android { - fun ArrayAdapter.setElements(elems: Collection) { + fun ArrayAdapter.setElements(elements: Collection) { setNotifyOnChange(false) clear() - addAll(elems) + addAll(elements) notifyDataSetChanged() setNotifyOnChange(true) } diff --git a/app/src/main/java/org/pacien/tincapp/extensions/VpnServiceBuilder.kt b/app/src/main/java/org/pacien/tincapp/extensions/VpnServiceBuilder.kt index 94e47d6..2bf5661 100644 --- a/app/src/main/java/org/pacien/tincapp/extensions/VpnServiceBuilder.kt +++ b/app/src/main/java/org/pacien/tincapp/extensions/VpnServiceBuilder.kt @@ -34,10 +34,10 @@ object VpnServiceBuilder { } private fun VpnService.Builder.addAddress(cidr: CidrAddress): VpnService.Builder = - exceptWithCidr(cidr, { addAddress(cidr.address, cidr.prefix) }) + exceptWithCidr(cidr) { addAddress(cidr.address, cidr.prefix) } private fun VpnService.Builder.addRoute(cidr: CidrAddress): VpnService.Builder = - exceptWithCidr(cidr, { addRoute(cidr.address, cidr.prefix) }) + exceptWithCidr(cidr) { addRoute(cidr.address, cidr.prefix) } private fun VpnService.Builder.allowBypass(allow: Boolean): VpnService.Builder = if (allow) allowBypass() else this @@ -46,25 +46,25 @@ object VpnServiceBuilder { if (mtu != null) setMtu(mtu) else this private fun VpnService.Builder.addAddresses(cidrList: List): VpnService.Builder = - cidrList.fold(this, { net, cidr -> net.addAddress(cidr) }) + cidrList.fold(this) { net, cidr -> net.addAddress(cidr) } private fun VpnService.Builder.addRoutes(cidrList: List): VpnService.Builder = - cidrList.fold(this, { net, cidr -> net.addRoute(cidr) }) + cidrList.fold(this) { net, cidr -> net.addRoute(cidr) } private fun VpnService.Builder.addDnsServers(dnsList: List): VpnService.Builder = - dnsList.fold(this, { net, dns -> net.addDnsServer(dns) }) + dnsList.fold(this) { net, dns -> net.addDnsServer(dns) } private fun VpnService.Builder.addSearchDomains(domainList: List): VpnService.Builder = - domainList.fold(this, { net, domain -> net.addSearchDomain(domain) }) + domainList.fold(this) { net, domain -> net.addSearchDomain(domain) } private fun VpnService.Builder.allowFamilies(familyList: List): VpnService.Builder = - familyList.fold(this, { net, family -> net.allowFamily(family) }) + familyList.fold(this) { net, family -> net.allowFamily(family) } private fun VpnService.Builder.addAllowedApplications(apps: List): VpnService.Builder = - apps.fold(this, { net, app -> applyIgnoringException(net::addAllowedApplication, app, net)!! }) + apps.fold(this) { net, app -> applyIgnoringException(net::addAllowedApplication, app, net)!! } private fun VpnService.Builder.addDisallowedApplications(apps: List): VpnService.Builder = - apps.fold(this, { net, app -> applyIgnoringException(net::addDisallowedApplication, app, net)!! }) + apps.fold(this) { net, app -> applyIgnoringException(net::addDisallowedApplication, app, net)!! } fun VpnService.Builder.applyCfg(cfg: VpnInterfaceConfiguration): VpnService.Builder = this .addAddresses(cfg.addresses) diff --git a/app/src/main/java/org/pacien/tincapp/intent/BroadcastMapper.kt b/app/src/main/java/org/pacien/tincapp/intent/BroadcastMapper.kt index 54cfc56..0343ff3 100644 --- a/app/src/main/java/org/pacien/tincapp/intent/BroadcastMapper.kt +++ b/app/src/main/java/org/pacien/tincapp/intent/BroadcastMapper.kt @@ -30,7 +30,7 @@ import org.pacien.tincapp.context.App */ class BroadcastMapper(private val actionHandlers: Map Unit>) : BroadcastReceiver() { private val broadcastManager = LocalBroadcastManager.getInstance(App.getContext()) - private val intentFilter = actionHandlers.keys.fold(IntentFilter(), { filter, action -> filter.apply { addAction(action) } }) + private val intentFilter = actionHandlers.keys.fold(IntentFilter()) { filter, action -> filter.apply { addAction(action) } } fun register() = broadcastManager.registerReceiver(this, intentFilter) fun unregister() = broadcastManager.unregisterReceiver(this) diff --git a/app/src/main/java/org/pacien/tincapp/utils/PemUtils.kt b/app/src/main/java/org/pacien/tincapp/utils/PemUtils.kt index f71a5d7..2cec35c 100644 --- a/app/src/main/java/org/pacien/tincapp/utils/PemUtils.kt +++ b/app/src/main/java/org/pacien/tincapp/utils/PemUtils.kt @@ -34,44 +34,60 @@ import java.io.Writer * @author pacien */ object PemUtils { + private const val DEK_INFO_HEADER_KEY = "DEK-Info" + private const val ALGORITHM = "AES-256-CBC" private val PROVIDER = org.bouncycastle.jce.provider.BouncyCastleProvider() private val ENCRYPTED_PROC_TYPE_HEADER = PemHeader("Proc-Type", "4,ENCRYPTED") - private val DEK_INFO_HEADER_KEY = "DEK-Info" - private val ALGO = "AES-256-CBC" private class DekInfo(val algName: String, val iv: ByteArray) - private fun dekInfoHeader(iv: ByteArray) = PemHeader(DEK_INFO_HEADER_KEY, "$ALGO,${Hex.toHexString(iv)}") - private fun PemObject.getPemHeaders() = headers.map { it as PemHeader } + private fun dekInfoHeader(iv: ByteArray) = PemHeader(DEK_INFO_HEADER_KEY, "$ALGORITHM,${Hex.toHexString(iv)}") - fun read(f: File): PemObject = PEMParser(FileReader(f)).readPemObject() - fun write(obj: PemObject, out: Writer) = JcaPEMWriter(out).apply { writeObject(obj) }.apply { close() } - fun isEncrypted(obj: PemObject) = obj.headers.contains(ENCRYPTED_PROC_TYPE_HEADER) + private fun PemObject.getPemHeaders() = headers.map { headerObj -> headerObj as PemHeader } + + private fun PemObject.dekInfo() = try { + getPemHeaders() + .find { header -> header.name == DEK_INFO_HEADER_KEY }!! + .value!! + .split(',') + .let { headerParts -> DekInfo(headerParts[0], Hex.decode(headerParts[1])) } + } catch (e: Exception) { + throw PEMException("Malformed DEK-Info header.", e) + } - fun encrypt(obj: PemObject, passPhrase: String) = - JcePEMEncryptorBuilder(ALGO) + private fun encryptor(passPhrase: String) = + JcePEMEncryptorBuilder(ALGORITHM) .setProvider(PROVIDER) - .build(passPhrase.toCharArray()) - .let { PemObject(obj.type, listOf(ENCRYPTED_PROC_TYPE_HEADER, dekInfoHeader(it.iv)), it.encrypt(obj.content)) } + .build(passPhrase.toCharArray())!! - fun decrypt(obj: PemObject, passPhrase: String?) = - if (isEncrypted(obj)) { - val dekInfo = try { - obj.getPemHeaders() - .find { it.name == DEK_INFO_HEADER_KEY }!! - .value!! - .split(',') - .let { DekInfo(it[0], Hex.decode(it[1])) } - } catch (e: Exception) { - throw PEMException("Malformed DEK-Info header.", e) - } + private fun decryptor(algName: String, passPhrase: String?) = + JcePEMDecryptorProviderBuilder() + .setProvider(PROVIDER) + .build(passPhrase?.toCharArray()) + .get(algName)!! + + fun read(f: File) = PEMParser(FileReader(f)).readPemObject()!! - JcePEMDecryptorProviderBuilder() - .setProvider(PROVIDER) - .build(passPhrase?.toCharArray()) - .get(dekInfo.algName) - .decrypt(obj.content, dekInfo.iv) - .let { PemObject(obj.type, it) } + fun write(obj: PemObject, out: Writer) = + JcaPEMWriter(out) + .apply { writeObject(obj) } + .apply { close() } + + fun isEncrypted(obj: PemObject) = obj.headers.contains(ENCRYPTED_PROC_TYPE_HEADER) + + fun encrypt(obj: PemObject, passPhrase: String): PemObject { + val encryptor = encryptor(passPhrase) + val headers = listOf(ENCRYPTED_PROC_TYPE_HEADER, dekInfoHeader(encryptor.iv)) + val body = encryptor.encrypt(obj.content) + return PemObject(obj.type, headers, body) + } + + fun decrypt(obj: PemObject, passPhrase: String?): PemObject = + if (isEncrypted(obj)) { + val dekInfo = obj.dekInfo() + val decryptor = decryptor(dekInfo.algName, passPhrase) + val body = decryptor.decrypt(obj.content, dekInfo.iv) + PemObject(obj.type, body) } else { obj } -- cgit v1.2.3