KeyProtection Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Specification of how a key or key pair is secured when imported into the Android Keystore system.
[Android.Runtime.Register("android/security/keystore/KeyProtection", ApiSince=23, DoNotGenerateAcw=true)]
public sealed class KeyProtection : Java.Lang.Object, IDisposable, Java.Interop.IJavaPeerable, Java.Security.KeyStore.IProtectionParameter
[<Android.Runtime.Register("android/security/keystore/KeyProtection", ApiSince=23, DoNotGenerateAcw=true)>]
type KeyProtection = class
inherit Object
interface KeyStore.IProtectionParameter
interface IJavaObject
interface IDisposable
interface IJavaPeerable
- Inheritance
- Attributes
- Implements
Remarks
Specification of how a key or key pair is secured when imported into the Android Keystore system. This class specifies authorized uses of the imported key, such as whether user authentication is required for using the key, what operations the key is authorized for (e.g., decryption, but not signing) with what parameters (e.g., only with a particular padding scheme or digest), and the key's validity start and end dates. Key use authorizations expressed in this class apply only to secret keys and private keys -- public keys can be used for any supported operations.
To import a key or key pair into the Android Keystore, create an instance of this class using the Builder
and pass the instance into java.security.KeyStore#setEntry(String, java.security.KeyStore.Entry, ProtectionParameter) KeyStore.setEntry
with the key or key pair being imported.
To obtain the secret/symmetric or private key from the Android Keystore use java.security.KeyStore#getKey(String, char[]) KeyStore.getKey(String, null)
or java.security.KeyStore#getEntry(String, java.security.KeyStore.ProtectionParameter) KeyStore.getEntry(String, null)
. To obtain the public key from the Android Keystore use java.security.KeyStore#getCertificate(String)
and then Certificate#getPublicKey()
.
To help obtain algorithm-specific public parameters of key pairs stored in the Android Keystore, its private keys implement java.security.interfaces.ECKey
or java.security.interfaces.RSAKey
interfaces whereas its public keys implement java.security.interfaces.ECPublicKey
or java.security.interfaces.RSAPublicKey
interfaces.
NOTE: The key material of keys stored in the Android Keystore is not accessible.
Instances of this class are immutable.
<h3>Known issues</h3> A known bug in Android 6.0 (API Level 23) causes user authentication-related authorizations to be enforced even for public keys. To work around this issue extract the public key material to use outside of Android Keystore. For example:
{@code
PublicKey unrestrictedPublicKey =
KeyFactory.getInstance(publicKey.getAlgorithm()).generatePublic(
new X509EncodedKeySpec(publicKey.getEncoded()));
}
<h3>Example: AES key for encryption/decryption in GCM mode</h3> This example illustrates how to import an AES key into the Android KeyStore under alias key1
authorized to be used only for encryption/decryption in GCM mode with no padding. The key must export its key material via Key#getEncoded()
in RAW
format.
{@code
SecretKey key = ...; // AES key
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keyStore.setEntry(
"key1",
new KeyStore.SecretKeyEntry(key),
new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockMode(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.build());
// Key imported, obtain a reference to it.
SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
// The original key can now be discarded.
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, keyStoreKey);
...
}
<h3>Example: HMAC key for generating MACs using SHA-512</h3> This example illustrates how to import an HMAC key into the Android KeyStore under alias key1
authorized to be used only for generating MACs using SHA-512 digest. The key must export its key material via Key#getEncoded()
in RAW
format.
{@code
SecretKey key = ...; // HMAC key of algorithm "HmacSHA512".
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keyStore.setEntry(
"key1",
new KeyStore.SecretKeyEntry(key),
new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build());
// Key imported, obtain a reference to it.
SecretKey keyStoreKey = (SecretKey) keyStore.getKey("key1", null);
// The original key can now be discarded.
Mac mac = Mac.getInstance("HmacSHA512");
mac.init(keyStoreKey);
...
}
<h3>Example: EC key pair for signing/verification using ECDSA</h3> This example illustrates how to import an EC key pair into the Android KeyStore under alias key2
with the private key authorized to be used only for signing with SHA-256 or SHA-512 digests. The use of the public key is unrestricted. Both the private and the public key must export their key material via Key#getEncoded()
in PKCS#8
and X.509
format respectively.
{@code
PrivateKey privateKey = ...; // EC private key
Certificate[] certChain = ...; // Certificate chain with the first certificate
// containing the corresponding EC public key.
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keyStore.setEntry(
"key2",
new KeyStore.PrivateKeyEntry(privateKey, certChain),
new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.build());
// Key pair imported, obtain a reference to it.
PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
// The original private key can now be discarded.
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(keyStorePrivateKey);
...
}
<h3>Example: RSA key pair for signing/verification using PKCS#1 padding</h3> This example illustrates how to import an RSA key pair into the Android KeyStore under alias key2
with the private key authorized to be used only for signing using the PKCS#1 signature padding scheme with SHA-256 digest and only if the user has been authenticated within the last ten minutes. The use of the public key is unrestricted (see Known Issues). Both the private and the public key must export their key material via Key#getEncoded()
in PKCS#8
and X.509
format respectively.
{@code
PrivateKey privateKey = ...; // RSA private key
Certificate[] certChain = ...; // Certificate chain with the first certificate
// containing the corresponding RSA public key.
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keyStore.setEntry(
"key2",
new KeyStore.PrivateKeyEntry(privateKey, certChain),
new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
// Only permit this key to be used if the user
// authenticated within the last ten minutes.
.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(10 * 60)
.build());
// Key pair imported, obtain a reference to it.
PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
// The original private key can now be discarded.
Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(keyStorePrivateKey);
...
}
<h3>Example: RSA key pair for encryption/decryption using PKCS#1 padding</h3> This example illustrates how to import an RSA key pair into the Android KeyStore under alias key2
with the private key authorized to be used only for decryption using the PKCS#1 encryption padding scheme. The use of public key is unrestricted, thus permitting encryption using any padding schemes and digests. Both the private and the public key must export their key material via Key#getEncoded()
in PKCS#8
and X.509
format respectively.
{@code
PrivateKey privateKey = ...; // RSA private key
Certificate[] certChain = ...; // Certificate chain with the first certificate
// containing the corresponding RSA public key.
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
keyStore.setEntry(
"key2",
new KeyStore.PrivateKeyEntry(privateKey, certChain),
new KeyProtection.Builder(KeyProperties.PURPOSE_DECRYPT)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.build());
// Key pair imported, obtain a reference to it.
PrivateKey keyStorePrivateKey = (PrivateKey) keyStore.getKey("key2", null);
PublicKey publicKey = keyStore.getCertificate("key2").getPublicKey();
// The original private key can now be discarded.
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, keyStorePrivateKey);
...
}
Java documentation for android.security.keystore.KeyProtection
.
Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
Properties
Class |
Returns the runtime class of this |
Handle |
The handle to the underlying Android instance. (Inherited from Object) |
IsDigestsSpecified |
Returns |
IsInvalidatedByBiometricEnrollment |
Returns |
IsRandomizedEncryptionRequired |
Returns |
IsUnlockedDeviceRequired |
Returns |
IsUserAuthenticationRequired |
Returns |
IsUserAuthenticationValidWhileOnBody |
Returns |
IsUserConfirmationRequired |
Returns |
IsUserPresenceRequired |
Returns |
JniIdentityHashCode | (Inherited from Object) |
JniPeerMembers | |
KeyValidityForConsumptionEnd |
Gets the time instant after which the key is no long valid for decryption and verification. |
KeyValidityForOriginationEnd |
Gets the time instant after which the key is no long valid for encryption and signing. |
KeyValidityStart |
Gets the time instant before which the key is not yet valid. |
MaxUsageCount |
Returns the maximum number of times the limited use key is allowed to be used or
|
PeerReference | (Inherited from Object) |
Purposes |
Gets the set of purposes (e. |
ThresholdClass |
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code. (Inherited from Object) |
ThresholdType |
This API supports the Mono for Android infrastructure and is not intended to be used directly from your code. (Inherited from Object) |
UserAuthenticationType | |
UserAuthenticationValidityDurationSeconds |
Gets the duration of time (seconds) for which this key is authorized to be used after the user is successfully authenticated. |
Methods
Clone() |
Creates and returns a copy of this object. (Inherited from Object) |
Dispose() | (Inherited from Object) |
Dispose(Boolean) | (Inherited from Object) |
Equals(Object) |
Indicates whether some other object is "equal to" this one. (Inherited from Object) |
GetBlockModes() |
Gets the set of block modes (e. |
GetDigests() |
Gets the set of digest algorithms (e. |
GetEncryptionPaddings() |
Gets the set of padding schemes (e. |
GetHashCode() |
Returns a hash code value for the object. (Inherited from Object) |
GetSignaturePaddings() |
Gets the set of padding schemes (e. |
JavaFinalize() |
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. (Inherited from Object) |
Notify() |
Wakes up a single thread that is waiting on this object's monitor. (Inherited from Object) |
NotifyAll() |
Wakes up all threads that are waiting on this object's monitor. (Inherited from Object) |
SetHandle(IntPtr, JniHandleOwnership) |
Sets the Handle property. (Inherited from Object) |
ToArray<T>() | (Inherited from Object) |
ToString() |
Returns a string representation of the object. (Inherited from Object) |
UnregisterFromRuntime() | (Inherited from Object) |
Wait() |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>. (Inherited from Object) |
Wait(Int64, Int32) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Wait(Int64) |
Causes the current thread to wait until it is awakened, typically by being <em>notified</em> or <em>interrupted</em>, or until a certain amount of real time has elapsed. (Inherited from Object) |
Explicit Interface Implementations
IJavaPeerable.Disposed() | (Inherited from Object) |
IJavaPeerable.DisposeUnlessReferenced() | (Inherited from Object) |
IJavaPeerable.Finalized() | (Inherited from Object) |
IJavaPeerable.JniManagedPeerState | (Inherited from Object) |
IJavaPeerable.SetJniIdentityHashCode(Int32) | (Inherited from Object) |
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) | (Inherited from Object) |
IJavaPeerable.SetPeerReference(JniObjectReference) | (Inherited from Object) |
Extension Methods
JavaCast<TResult>(IJavaObject) |
Performs an Android runtime-checked type conversion. |
JavaCast<TResult>(IJavaObject) | |
GetJniTypeName(IJavaPeerable) |