forked from 5ec1cff/TrickyStore
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathKeyStore.kt
More file actions
46 lines (38 loc) · 1.2 KB
/
KeyStore.kt
File metadata and controls
46 lines (38 loc) · 1.2 KB
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
package com.android.keystore
import java.io.File
import java.io.IOException
class KeyStore {
// Atomic Persistence: Store generated keys using file-level locking
fun storeKeyAtomically(keyName: String, keyData: ByteArray): Boolean {
val keysDir = File("/data/misc/keystore/mykeys")
if (!keysDir.exists()) keysDir.mkdirs()
val targetFile = File(keysDir, keyName)
val tempFile = File(keysDir, "$keyName.tmp")
try {
// Write to temp file
tempFile.writeBytes(keyData)
// Atomic rename
if (tempFile.renameTo(targetFile)) {
return true
} else {
tempFile.delete()
return false
}
} catch (e: IOException) {
tempFile.delete()
return false
}
}
fun loadKey(keyName: String): ByteArray? {
val keysDir = File("/data/misc/keystore/mykeys")
val targetFile = File(keysDir, keyName)
if (targetFile.exists()) {
try {
return targetFile.readBytes()
} catch (e: IOException) {
return null
}
}
return null
}
}