I need to use NIST P-256 elliptic curves to encrypt and decrypt data. Now that I have generated the key pair, but how do I use them to encrypt and decrypt?
The official website only says how to use this ec key pair to sign/verify, but I want to know how to use this ec key pair to encrypt/decrypt.
website: https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec#example:-nist-p-256-ec-key-pair-for-signingverification-using-ecdsa
generate NIST P-256 key pair code:
val kpg: KeyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
val parameterSpec =
KeyGenParameterSpec.Builder("container", KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512)
.build()
kpg.initialize(parameterSpec)
val keyPair = kpg.generateKeyPair()
val ecPublicKey = keyPair.public as ECPublicKey
val ecPrivateKey = keyPair.private as ECPrivateKey
Elliptic Curve Cryptography (ECC) is a key-based technique for encrypting data. ECC focuses on pairs of public and private keys for decryption and encryption of web traffic. ECC is frequently discussed in the context of the Rivest–Shamir–Adleman (RSA) cryptographic algorithm.
An ECC key pair includes a private and public key. The ECC private key is used to generate digital signatures, and the ECC public key is used to verify digital signatures. ICSF generates ECC key pairs using the Elliptic Curve Digital Signature Algorithm (ECDSA).
The encryption uses AES in CBC mode with random IV. Note that the data stored in the class EncryptedData ( salt , iv , and encryptedData ) can be concatenated to a single byte array. You can then save the data or transmit it to the recipient.
AndroidKeyStore does not currently support encryption or decryption with EC keys, only with RSA keys.
To use EC keys for encryption, you need to either use ECDH plus a key derivation function (KDF) to compute a shared symmetric key which you can use for your data, or to use ECIES which does that internally. But AndroidKeyStore doesn't support either mode of operation as of Android 10. Maybe in Android 11.
For now, you can either use RSA with an appropriate padding mode (OAEP recommended) to encrypt your symmetric key, or you can use the native Java cryto provider. This, unfortunately, will not use secure hardware to generate, store or use the key, and will instead do all of these things in your app's process space. There's an example here.
(For what it's worth, I'm the Google engineer who owns AndroidKeyStore. I've been planning to add ECDH support for a few years now, but it's always been pre-empted by other features that were considered higher priority. I will get to it, though.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With