私钥、public 密钥和证书关系以及从密钥库访问特定证书的最佳方式

private key, public key and certificates relationship and best way to access specific certificate from keystore

我使用了以下 keytool 命令:

keytool -genkey -alias <alias name> -keypass <keypassword> -keystore <keystore file name with location> -keyalg "RSA" -sigalg SHA1WITHRSA

然后我使用以下命令查看密钥库内容:

keytool -list -v -keystore <keystore file name with location>

显示如下内容:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: keyalias
Creation date: Nov 23, 2017
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=XXXXX, OU=SDG, O=XXXXX, L=XXXXX, ST=XX, C=IN
Issuer: CN=XXXXX, OU=SDG, O=XXXXX, L=XXXXX, ST=XX, C=IN
Serial number: 6c6ec57a
Valid from: Thu Nov 23 14:30:35 IST 2017 until: Wed Feb 21 14:30:35 IST 2018
Certificate fingerprints:
MD5:  85:08:01:27:BF:CA:88:17:88:11:9D:E4:DF:DC:70:AD
SHA1: 6D:14:08:BD:F6:4E:51:C2:A0:58:46:89:CC:85:06:BC:26:DA:23:4E
SHA256: D6:94:A8:31:2F:5D:29:FA:29:5F:8C:5D:24:D0:8E:47:D4:17:4C:B8:8A:
D8:A2:37:3F:18:24:5A:06:C1:E4:CB
Signature algorithm name: SHA1withRSA
Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
    KeyIdentifier [
        0000: 50 AD ED B0 1D 3D 12 AE   D4 C0 C7 EE 9F EE 43 11  P....=........C.
        0010: F4 71 02 93                                        .q..
    ]
]

*******************************************
*******************************************

我在密钥库中只能看到一个条目。希望获得以下问题的答案:

  1. public 键在哪里?

  2. 我也可以看到一个证书,但我没有创建它。如果我需要在 java 代码中访问此证书,那么我需要使用密钥别名还是可以设置任何单独的别名来访问此证书?

如果有人能解释私钥、public 密钥和证书如何在密钥库中链接以及如何从密钥库访问特定证书(假设密钥库有多个证书),那将会很有帮助).

只是回答自己的问题,可能对其他人也有帮助。

私钥包含一串数字。其中两个数字构成 "public key",其他数字是 "private key" 的一部分。 "public key" 位也嵌入到 Certificate 中。要检查证书中的 public 密钥是否与私钥的 public 部分匹配,您需要查看证书和密钥并比较数字。

要从私钥访问证书,您需要使用私钥别名,在列出密钥库的内容时可以找到 publically。

keytool -genkey -alias

很好,您刚刚创建了一个密钥对。

keytool 命令使用自签名证书创建密钥对。实际上,在同一个别名中,您有一个私钥和 X509 证书(公钥 + 一些属性)

Where is the public key?

在这种情况下,public 密钥包含在证书中。

If I need to access this certificate in java code then do I need to use the key alias or can I set any separate alias to access this certificate?

以下代码从密钥对

返回证书和public密钥
KeyStore.PrivateKeyEntry privKeyEntry = (KeyStore.PrivateKeyEntry)keystore.getEntry(KEYSTORE_ALIAS, new KeyStore.PasswordProtection(KEYSTORE_KEY_PASSWORD.toCharArray()));

PublicKey pubKey = privKeyEntry.getCertificate().getPublicKey();

It will be great help if someone can explain how private key, public key and certificates are linked in a key store

显然你已经发现了:)