summaryrefslogtreecommitdiff
path: root/main/src/ui/java/de/blinkt/openvpn/core/ProfileEncryption.kt
blob: fa61e733269d6e9f769f83ea4150e12eabdc652e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2012-2022 Arne Schwabe
 * Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
 */
package de.blinkt.openvpn.core

import android.content.Context
import android.os.Build
import androidx.security.crypto.EncryptedFile
import androidx.security.crypto.MasterKey
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.security.GeneralSecurityException

internal class ProfileEncryption {

    companion object {
        @JvmStatic
        fun encryptionEnabled(): Boolean {
            return mMasterKey != null
        }

        private var mMasterKey: MasterKey? = null
        @JvmStatic
        fun initMasterCryptAlias(context:Context) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
                return
            try {
                mMasterKey = MasterKey.Builder(context)
                      .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
                      .build()
            } catch (e: GeneralSecurityException) {
                VpnStatus.logException("Could not initialise file encryption key.", e)
            } catch (e: IOException) {
                VpnStatus.logException("Could not initialise file encryption key.", e)
            }
        }

        @JvmStatic
        @Throws(GeneralSecurityException::class, IOException::class)
        fun getEncryptedVpInput(context: Context, file: File): FileInputStream {
            val encryptedFile = EncryptedFile.Builder(
                context,
                file,
                mMasterKey!!,
                EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
            ).build()
            return encryptedFile.openFileInput()
        }

        @JvmStatic
        @Throws(GeneralSecurityException::class, IOException::class)
        fun getEncryptedVpOutput(context: Context, file: File): FileOutputStream {
            val encryptedFile = EncryptedFile.Builder(
                context,
                file,
                mMasterKey!!,
                EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
            ).build()
            return encryptedFile.openFileOutput()
        }
    }
}