Note: 只支持Android 6.0 以上
dependencies {
def security_version = "1.0.0-alpha02"
implementation "androidx.security:security-crypto:$security_version"
}
文件内容操作
e.g : 文件写入
private fun writeFile(){
val key = MasterKeys.AES256_GCM_SPEC
val masterKeyAlias = MasterKeys.getOrCreate(key)
val fileName = "my.txt"
val encryptedFile = EncryptedFile.Builder(File(this.filesDir, fileName),
this,
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB)
.build()
try {
val outPutStream = encryptedFile.openFileOutput()
outPutStream.apply {
write("这是一个测试输入文本内容".toByteArray(Charset.forName("UTF-8")))
flush()
close()
}
} catch (e: Exception) {
}
}
打开文件看到的内容:
(G�y��2SS��ݬ�FBg6��Wyb��P��4rU��{����$��a��)�(2���@�fɏ�=F�c\)Kx��O���Ŷ�?PC�TIE0ݚ�G����
e.g: 读取
private fun readFile() : String{
val key = MasterKeys.AES256_GCM_SPEC
val masterKeyAlias = MasterKeys.getOrCreate(key)
val readFile = "my.txt"
val readEncrypt = EncryptedFile.Builder(
File(this.filesDir, readFile),
this,
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
)
.build()
lateinit var byteStream: ByteArrayOutputStream
var fileContent: String? = null
try {
val fileInputSteam = readEncrypt.openFileInput()
try {
byteStream = ByteArrayOutputStream()
var nextRead = fileInputSteam.read()
while (nextRead != -1){
byteStream.write(nextRead)
nextRead = fileInputSteam.read()
}
fileContent = byteStream.toString()
} catch (e: java.lang.Exception){
} finally {
fileInputSteam.close()
}
} catch (e: Exception) {
}
return fileContent!!
}
输出:
这是一个测试输入文本内容
SharedPreferences
val sharedPreferences = EncryptedSharedPreferences
.create(
fileName,
masterKeyAlias,
context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
val sharedPrefsEditor = sharedPreferences.edit()