class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
// Although you can define your own key generation parameter specification, it's
// recommended that you use the value specified here.
// val keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC
// val masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var secretKey : SecretKey? = null
var alias = "1223"
var ks : KeyStore = KeyStore.getInstance("AndroidKeyStore").apply {
load(null)
}
if (ks.containsAlias(alias)) {
//키가 존재할경우
val secretKeyEntry = ks.getEntry(alias, null) as KeyStore.SecretKeyEntry
secretKey = secretKeyEntry.secretKey
Log.e("키가 있음", secretKey.toString())
// 이 시크릿키를 가지고 뭔가 암호화 / 복호화?
}
else {
//키가 없을경우
val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
val parameterSpec = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).run {
setBlockModes(KeyProperties.BLOCK_MODE_CBC)
setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
setDigests(KeyProperties.DIGEST_SHA256)
setUserAuthenticationRequired(false)
build()
}
keyGenerator.init(parameterSpec)
secretKey = keyGenerator.generateKey()
Log.e("키가 없어서 생성", secretKey.toString())
}
var iv: ByteArray
var text = "우리나라 만세"
//암호화 하는 부분
val cipher_enc = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher_enc.init(Cipher.ENCRYPT_MODE, secretKey)
iv = cipher_enc.iv
val byteEncryptedText = cipher_enc.doFinal(text.toByteArray())
//복호화 하는 부분
val cipher_dec = Cipher.getInstance("AES/CBC/PKCS7Padding")
cipher_dec.init(Cipher.DECRYPT_MODE, secretKey, IvParameterSpec(iv))
val byteDecryptedText = cipher_dec.doFinal(byteEncryptedText)
Log.e("result","원본 : " + text)
Log.e("result", "암호화 : "+ String(Base64.encode(byteEncryptedText, Base64.DEFAULT)))
Log.e("result", "복호화 : "+ String(byteDecryptedText))
}
}
- 참조
https://stackoverflow.com/questions/51469481/android-keystore-encrypt-and-decrypt-data
https://linsoo.pe.kr/archives/28119
https://developer.android.com/training/articles/keystore?hl=ko
'Android(Kotlin)' 카테고리의 다른 글
bumblebee 이상 firebase import (0) | 2022.08.12 |
---|---|
Android BindingAdapter (0) | 2022.07.31 |
Android 디컴파일 (0) | 2022.07.29 |
SharedPreferences / EncryptedSharedPreferences (0) | 2022.07.26 |
Android Lottie (0) | 2022.05.16 |