Most visited

Recently visited

Added in API level 1

KeyStore

public class KeyStore
extends Object

java.lang.Object
   ↳ java.security.KeyStore


这个类代表了密码密钥和证书的存储设施。

KeyStore管理不同类型的条目。 每种类型的条目都实现了KeyStore.Entry接口。 提供了三种基本的KeyStore.Entry实现:

密钥库中的每个条目由“别名”字符串标识。 在私钥及其相关证书链的情况下,这些字符串区分实体可以对其自身进行验证的不同方式。 例如,实体可以使用不同的证书颁发机构或使用不同的公钥算法对自身进行身份验证。

别名是否区分大小写取决于实现。 为了避免问题,建议不要在KeyStore中使用仅在大小写不同的别名。

这里没有指定密钥库是否持久,以及密钥库使用的机制是否持久。 这允许使用各种技术来保护敏感(例如私人或秘密)密钥。 智能卡或其他集成密码引擎(SafeKeyper)是一种选择,也可以使用更简单的机制(如各种格式),如文件。

请求KeyStore对象的典型方法包括依靠默认类型并提供特定的密钥库类型。

在可以访问密钥库之前,它必须是 loaded

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

    // get user password and file input stream
    char[] password = getPassword();

    java.io.FileInputStream fis = null;
    try {
        fis = new java.io.FileInputStream("keyStoreName");
        ks.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
 
To create an empty keystore using the above load method, pass null as the InputStream argument.

加载密钥库后,可以从密钥库中读取现有条目,或者将新条目写入密钥库:

    KeyStore.ProtectionParameter protParam =
        new KeyStore.PasswordProtection(password);

    // get my private key
    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
        ks.getEntry("privateKeyAlias", protParam);
    PrivateKey myPrivateKey = pkEntry.getPrivateKey();

    // save my secret key
    javax.crypto.SecretKey mySecretKey;
    KeyStore.SecretKeyEntry skEntry =
        new KeyStore.SecretKeyEntry(mySecretKey);
    ks.setEntry("secretKeyAlias", skEntry, protParam);

    // store away the keystore
    java.io.FileOutputStream fos = null;
    try {
        fos = new java.io.FileOutputStream("newKeyStoreName");
        ks.store(fos, password);
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
 
Note that although the same password may be used to load the keystore, to protect the private key entry, to protect the secret key entry, and to store the keystore (as is shown in the sample code above), different passwords or other protection parameters may also be used.

Android提供了以下 KeyStore类型:

Name Supported (API Levels)
AndroidCAStore 14+
AndroidKeyStore 18+
BCPKCS12 1–8
BKS 1+
BouncyCastle 1+
PKCS12 1+
PKCS12-DEF 1–8
These types are described in the KeyStore section of the Java Cryptography Architecture Standard Algorithm Name Documentation.

也可以看看:

Summary

Nested classes

class KeyStore.Builder

对待实例化的KeyStore对象的描述。

class KeyStore.CallbackHandlerProtection

封装CallbackHandler的ProtectionParameter。

interface KeyStore.Entry

用于KeyStore条目类型的标记界面。

interface KeyStore.LoadStoreParameter

KeyStore loadstore参数的标记接口。

class KeyStore.PasswordProtection

基于密码的实现ProtectionParameter

class KeyStore.PrivateKeyEntry

包含PrivateKey和相应证书链的KeyStore条目。

interface KeyStore.ProtectionParameter

密钥库保护参数的标记界面。

class KeyStore.SecretKeyEntry

包含SecretKey KeyStore条目。

class KeyStore.TrustedCertificateEntry

包含可信Certificate KeyStore条目。

Protected constructors

KeyStore(KeyStoreSpi keyStoreSpi, Provider provider, String type)

创建给定类型的KeyStore对象,并封装给定的提供者实现(SPI对象)。

Public methods

final Enumeration<String> aliases()

列出此密钥库的所有别名。

final boolean containsAlias(String alias)

检查此密钥库中是否存在给定的别名。

final void deleteEntry(String alias)

从此密钥库中删除由给定别名标识的条目。

final boolean entryInstanceOf(String alias, Class<? extends KeyStore.Entry> entryClass)

确定密钥库 Entry为指定 alias是指定的一个实例或亚类 entryClass

final Certificate getCertificate(String alias)

返回与给定别名关联的证书。

final String getCertificateAlias(Certificate cert)

返回证书与给定证书相匹配的第一个密钥库条目的(别名)名称。

final Certificate[] getCertificateChain(String alias)

返回与给定别名关联的证书链。

final Date getCreationDate(String alias)

返回由给定别名标识的条目的创建日期。

static final String getDefaultType()

如果不存在此类属性,则返回Java安全性属性文件中指定的默认密钥库类型或字符串“jks”(“Java密钥库”的首字母缩写)。

final KeyStore.Entry getEntry(String alias, KeyStore.ProtectionParameter protParam)

获取具有指定保护参数的指定别名的密钥库 Entry

static KeyStore getInstance(String type)

返回指定类型的keystore对象。

static KeyStore getInstance(String type, String provider)

返回指定类型的keystore对象。

static KeyStore getInstance(String type, Provider provider)

返回指定类型的keystore对象。

final Key getKey(String alias, char[] password)

返回与给定别名关联的密钥,使用给定的密码来恢复它。

final Provider getProvider()

返回此密钥库的提供者。

final String getType()

返回此密钥库的类型。

final boolean isCertificateEntry(String alias)

如果给定别名标识的条目是通过调用创建返回true setCertificateEntry ,或者创建通过调用 setEntryTrustedCertificateEntry

final boolean isKeyEntry(String alias)

如果由给定别名标识的条目是通过调用 setKeyEntry创建的,或者通过用 PrivateKeyEntrySecretKeyEntry调用 setEntry创建的,则返回true。

final void load(KeyStore.LoadStoreParameter param)

使用给定的 LoadStoreParameter加载此密钥库。

final void load(InputStream stream, char[] password)

从给定的输入流加载此KeyStore。

final void setCertificateEntry(String alias, Certificate cert)

将给定的可信证书分配给给定的别名。

final void setEntry(String alias, KeyStore.Entry entry, KeyStore.ProtectionParameter protParam)

将密钥库 Entry保存在指定的别名下。

final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)

将给定的键分配给给定的别名,用给定的密码保护它。

final void setKeyEntry(String alias, byte[] key, Certificate[] chain)

将给定的键(已被保护)分配给给定的别名。

final int size()

检索此密钥库中的条目数。

final void store(OutputStream stream, char[] password)

将此密钥库存储到给定的输出流,并使用给定的密码保护其完整性。

final void store(KeyStore.LoadStoreParameter param)

使用给定的 LoadStoreParameter存储此密钥库。

Inherited methods

From class java.lang.Object

Protected constructors

KeyStore

Added in API level 1
KeyStore (KeyStoreSpi keyStoreSpi, 
                Provider provider, 
                String type)

创建给定类型的KeyStore对象,并封装给定的提供者实现(SPI对象)。

Parameters
keyStoreSpi KeyStoreSpi: the provider implementation.
provider Provider: the provider.
type String: the keystore type.

Public methods

aliases

Added in API level 1
Enumeration<String> aliases ()

列出此密钥库的所有别名。

Returns
Enumeration<String> enumeration of the alias names
Throws
KeyStoreException if the keystore has not been initialized (loaded).

containsAlias

Added in API level 1
boolean containsAlias (String alias)

检查此密钥库中是否存在给定的别名。

Parameters
alias String: the alias name
Returns
boolean true if the alias exists, false otherwise
Throws
KeyStoreException if the keystore has not been initialized (loaded).

deleteEntry

Added in API level 1
void deleteEntry (String alias)

从此密钥库中删除由给定别名标识的条目。

Parameters
alias String: the alias name
Throws
KeyStoreException if the keystore has not been initialized, or if the entry cannot be removed.

entryInstanceOf

Added in API level 1
boolean entryInstanceOf (String alias, 
                Class<? extends KeyStore.Entry> entryClass)

确定密钥库 Entry为指定 alias是指定的一个实例或亚类 entryClass

Parameters
alias String: the alias name
entryClass Class: the entry class
Returns
boolean true if the keystore Entry for the specified alias is an instance or subclass of the specified entryClass, false otherwise
Throws
NullPointerException if alias or entryClass is null
KeyStoreException if the keystore has not been initialized (loaded)

getCertificate

Added in API level 1
Certificate getCertificate (String alias)

返回与给定别名关联的证书。

如果给定的别名标识通过调用创建一个条目 setCertificateEntry ,或者创建通过调用 setEntryTrustedCertificateEntry ,那么包含在该条目中的可信证书被返回。

如果给定的别名标识通过调用 setKeyEntry创建的条目,或者通过用 PrivateKeyEntrysetEntry的调用创建的条目,则返回该条目中证书链的第一个元素。

Parameters
alias String: the alias name
Returns
Certificate the certificate, or null if the given alias does not exist or does not contain a certificate.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getCertificateAlias

Added in API level 1
String getCertificateAlias (Certificate cert)

返回证书与给定证书相匹配的第一个密钥库条目的(别名)名称。

此方法尝试将给定的证书与每个密钥库条目进行匹配。 如果正在考虑的条目是通过调用setCertificateEntry创建的,或者通过调用setEntryTrustedCertificateEntry ,则将给定的证书与该条目的证书进行比较。

如果正在考虑的条目是通过调用 setKeyEntry创建的,或者通过调用 setEntryPrivateKeyEntry ,则将给定的证书与该条目的证书链的第一个元素进行比较。

Parameters
cert Certificate: the certificate to match with.
Returns
String the alias name of the first entry with a matching certificate, or null if no such entry exists in this keystore.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getCertificateChain

Added in API level 1
Certificate[] getCertificateChain (String alias)

返回与给定别名关联的证书链。 证书链必须已经通过调用别名关联到setKeyEntry ,或者通过将呼叫setEntryPrivateKeyEntry

Parameters
alias String: the alias name
Returns
Certificate[] the certificate chain (ordered with the user's certificate first followed by zero or more certificate authorities), or null if the given alias does not exist or does not contain a certificate chain
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getCreationDate

Added in API level 1
Date getCreationDate (String alias)

返回由给定别名标识的条目的创建日期。

Parameters
alias String: the alias name
Returns
Date the creation date of this entry, or null if the given alias does not exist
Throws
KeyStoreException if the keystore has not been initialized (loaded).

getDefaultType

Added in API level 1
String getDefaultType ()

如果不存在此类属性,则返回Java安全性属性文件中指定的默认密钥库类型或字符串“jks”(“Java密钥库”的首字母缩写)。 Java安全属性文件位于名为<JAVA_HOME> /lib/security/java.security的文件中。 <JAVA_HOME>引用java.home系统属性的值,并指定安装JRE的目录。

当调用其中一个 getInstance方法时,不想使用硬编码密钥库类型的应用程序可以使用默认密钥库类型,并且希望在用户未指定其自己的情况下提供默认密钥库类型。

通过将“keystore.type”安全属性(在Java安全属性文件中)的值设置为所需的密钥库类型,可以更改默认密钥库类型。

Returns
String the default keystore type as specified in the Java security properties file, or the string "jks" if no such property exists.

getEntry

Added in API level 1
KeyStore.Entry getEntry (String alias, 
                KeyStore.ProtectionParameter protParam)

获取具有指定保护参数的指定别名的密钥库 Entry

Parameters
alias String: get the keystore Entry for this alias
protParam KeyStore.ProtectionParameter: the ProtectionParameter used to protect the Entry, which may be null
Returns
KeyStore.Entry the keystore Entry for the specified alias, or null if there is no such entry
Throws
NullPointerException if alias is null
NoSuchAlgorithmException if the algorithm for recovering the entry cannot be found
UnrecoverableEntryException if the specified protParam were insufficient or invalid
UnrecoverableKeyException if the entry is a PrivateKeyEntry or SecretKeyEntry and the specified protParam does not contain the information needed to recover the key (e.g. wrong password)
KeyStoreException if the keystore has not been initialized (loaded).

也可以看看:

getInstance

Added in API level 1
KeyStore getInstance (String type)

返回指定类型的keystore对象。

该方法遍历注册安全提供程序的列表,从最优先的提供程序开始。 返回一个新的KeyStore对象,该对象封装来自支持指定类型的第一个Provider的KeyStoreSpi实现。

请注意,可以通过 Security.getProviders()方法检索注册供应商列表。

Parameters
type String: the type of keystore. See the KeyStore section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard keystore types.
Returns
KeyStore a keystore object of the specified type.
Throws
KeyStoreException if no Provider supports a KeyStoreSpi implementation for the specified type.

也可以看看:

getInstance

Added in API level 1
KeyStore getInstance (String type, 
                String provider)

返回指定类型的keystore对象。

返回封装指定提供程序的KeyStoreSpi实现的新KeyStore对象。 指定的提供者必须在安全提供者列表中注册。

请注意,可以通过 Security.getProviders()方法检索注册供应商列表。

Parameters
type String: the type of keystore. See the KeyStore section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard keystore types.
provider String: the name of the provider.
Returns
KeyStore a keystore object of the specified type.
Throws
KeyStoreException if a KeyStoreSpi implementation for the specified type is not available from the specified provider.
NoSuchProviderException if the specified provider is not registered in the security provider list.
IllegalArgumentException if the provider name is null or empty.

也可以看看:

getInstance

Added in API level 1
KeyStore getInstance (String type, 
                Provider provider)

返回指定类型的keystore对象。

返回封装指定Provider对象的KeyStoreSpi实现的新KeyStore对象。 请注意,指定的Provider对象不必在提供程序列表中注册。

Parameters
type String: the type of keystore. See the KeyStore section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard keystore types.
provider Provider: the provider.
Returns
KeyStore a keystore object of the specified type.
Throws
KeyStoreException if KeyStoreSpi implementation for the specified type is not available from the specified Provider object.
IllegalArgumentException if the specified provider is null.

也可以看看:

getKey

Added in API level 1
Key getKey (String alias, 
                char[] password)

返回与给定别名关联的密钥,使用给定的密码来恢复它。 通过拨打setKeyEntry或通过拨打setEntryPrivateKeyEntrySecretKeyEntry ,密钥必须与别名相关联。

Parameters
alias String: the alias name
password char: the password for recovering the key
Returns
Key the requested key, or null if the given alias does not exist or does not identify a key-related entry.
Throws
KeyStoreException if the keystore has not been initialized (loaded).
NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
UnrecoverableKeyException if the key cannot be recovered (e.g., the given password is wrong).

getProvider

Added in API level 1
Provider getProvider ()

返回此密钥库的提供者。

Returns
Provider the provider of this keystore.

getType

Added in API level 1
String getType ()

返回此密钥库的类型。

Returns
String the type of this keystore.

isCertificateEntry

Added in API level 1
boolean isCertificateEntry (String alias)

如果给定别名标识的条目是通过调用创建返回true setCertificateEntry ,或者创建通过调用 setEntryTrustedCertificateEntry

Parameters
alias String: the alias for the keystore entry to be checked
Returns
boolean true if the entry identified by the given alias contains a trusted certificate, false otherwise.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

isKeyEntry

Added in API level 1
boolean isKeyEntry (String alias)

如果由给定别名标识的条目是通过调用 setKeyEntry创建的,或者通过用 PrivateKeyEntrySecretKeyEntry调用 setEntry创建的,则返回true。

Parameters
alias String: the alias for the keystore entry to be checked
Returns
boolean true if the entry identified by the given alias is a key-related entry, false otherwise.
Throws
KeyStoreException if the keystore has not been initialized (loaded).

load

Added in API level 1
void load (KeyStore.LoadStoreParameter param)

使用给定的 LoadStoreParameter加载此密钥库。

请注意,如果此KeyStore已被加载,则会重新初始化并从给定参数再次加载。

Parameters
param KeyStore.LoadStoreParameter: the LoadStoreParameter that specifies how to load the keystore, which may be null
Throws
IllegalArgumentException if the given LoadStoreParameter input is not recognized
IOException if there is an I/O or format problem with the keystore data. If the error is due to an incorrect ProtectionParameter (e.g. wrong password) the cause of the IOException should be an UnrecoverableKeyException
NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
CertificateException if any of the certificates in the keystore could not be loaded

load

Added in API level 1
void load (InputStream stream, 
                char[] password)

从给定的输入流加载此KeyStore。

可以给密码解锁密钥库(例如,密钥库驻留在硬件令牌设备上),或者检查密钥库数据的完整性。 如果未提供密码进行完整性检查,则不会执行完整性检查。

为了创建一个空的密钥库,或者如果keystore无法从流中初始化, null作为 stream参数传递。

请注意,如果此密钥库已被加载,它将被重新初始化并从给定的输入流再次加载。

Parameters
stream InputStream: the input stream from which the keystore is loaded, or null
password char: the password used to check the integrity of the keystore, the password used to unlock the keystore, or null
Throws
IOException if there is an I/O or format problem with the keystore data, if a password is required but not given, or if the given password was incorrect. If the error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException
NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found
CertificateException if any of the certificates in the keystore could not be loaded

setCertificateEntry

Added in API level 1
void setCertificateEntry (String alias, 
                Certificate cert)

将给定的可信证书分配给给定的别名。

如果给定的别名标识通过对 setCertificateEntry的调用创建的现有条目或通过用 TrustedCertificateEntrysetEntry的调用创建的现有条目,则现有条目中的可信证书将被给定证书覆盖。

Parameters
alias String: the alias name
cert Certificate: the certificate
Throws
KeyStoreException if the keystore has not been initialized, or the given alias already exists and does not identify an entry containing a trusted certificate, or this operation fails for some other reason.

setEntry

Added in API level 1
void setEntry (String alias, 
                KeyStore.Entry entry, 
                KeyStore.ProtectionParameter protParam)

在指定的别名下保存密钥库Entry 保护参数用于保护Entry

如果指定别名的条目已存在,则会覆盖它。

Parameters
alias String: save the keystore Entry under this alias
entry KeyStore.Entry: the Entry to save
protParam KeyStore.ProtectionParameter: the ProtectionParameter used to protect the Entry, which may be null
Throws
NullPointerException if alias or entry is null
KeyStoreException if the keystore has not been initialized (loaded), or if this operation fails for some other reason

也可以看看:

setKeyEntry

Added in API level 1
void setKeyEntry (String alias, 
                Key key, 
                char[] password, 
                Certificate[] chain)

将给定的键分配给给定的别名,用给定的密码保护它。

如果给定密钥的类型为 java.security.PrivateKey ,则必须附带证明相应公钥的证书链。

如果给定的别名已经存在,则与其关联的密钥库信息将被给定密钥(可能还有证书链)覆盖。

Parameters
alias String: the alias name
key Key: the key to be associated with the alias
password char: the password to protect the key
chain Certificate: the certificate chain for the corresponding public key (only required if the given key is of type java.security.PrivateKey).
Throws
KeyStoreException if the keystore has not been initialized (loaded), the given key cannot be protected, or this operation fails for some other reason

setKeyEntry

Added in API level 1
void setKeyEntry (String alias, 
                byte[] key, 
                Certificate[] chain)

将给定的键(已被保护)分配给给定的别名。

如果受保护的密钥类型为java.security.PrivateKey ,则必须附带证明相应公钥的证书链。 如果基础密钥库实现类型为jkskey必须将key编码为PKCS#8标准中定义的EncryptedPrivateKeyInfo

如果给定的别名已经存在,则与其关联的密钥库信息将被给定密钥(可能还有证书链)覆盖。

Parameters
alias String: the alias name
key byte: the key (in protected format) to be associated with the alias
chain Certificate: the certificate chain for the corresponding public key (only useful if the protected key is of type java.security.PrivateKey).
Throws
KeyStoreException if the keystore has not been initialized (loaded), or if this operation fails for some other reason.

size

Added in API level 1
int size ()

检索此密钥库中的条目数。

Returns
int the number of entries in this keystore
Throws
KeyStoreException if the keystore has not been initialized (loaded).

store

Added in API level 1
void store (OutputStream stream, 
                char[] password)

将此密钥库存储到给定的输出流,并使用给定的密码保护其完整性。

Parameters
stream OutputStream: the output stream to which this keystore is written.
password char: the password to generate the keystore integrity check
Throws
KeyStoreException if the keystore has not been initialized (loaded).
IOException if there was an I/O problem with data
NoSuchAlgorithmException if the appropriate data integrity algorithm could not be found
CertificateException if any of the certificates included in the keystore data could not be stored

store

Added in API level 1
void store (KeyStore.LoadStoreParameter param)

使用给定的 LoadStoreParameter存储此密钥库。

Parameters
param KeyStore.LoadStoreParameter: the LoadStoreParameter that specifies how to store the keystore, which may be null
Throws
IllegalArgumentException if the given LoadStoreParameter input is not recognized
KeyStoreException if the keystore has not been initialized (loaded)
IOException if there was an I/O problem with data
NoSuchAlgorithmException if the appropriate data integrity algorithm could not be found
CertificateException if any of the certificates included in the keystore data could not be stored

Hooray!