Java 密钥库 证书 公钥 私钥
Java 密钥库 证书 公钥 私钥
1.密钥库
密钥库keystore
是存储一个或多个密钥条目的文件,每个密钥条目以一个别名标识,它包含密钥和证书相关信息。可以使用java自带工具keytool生成,也可以通过程序编码实现。
- 密钥库文件格式(实际上,扩展名并不重要),比较常用的是jks和pkcs12。
格式 | 扩展名 | 描述 | 特点 |
---|---|---|---|
JKS | .jks/.ks | 密钥库的Java实现版本,provider为SUN | 密钥库和私钥用不同的密码进行保护 |
JCEKS | .jce | 密钥库的JCE实现版本,provider为SUN JCE | 相对于JKS安全级别更高,保护Keystore私钥时采用3DES |
PKCS12 | .p12/.pfx | 个人信息交换语法标准 | 包含私钥、公钥及其证书,密钥库和私钥用相同密码进行保护 |
BKS | .bks | 密钥库的BC实现版本,provider为BC | 基于JCE实现 |
2.使用Java的keytool
工具生成密钥库
keytool -genkeypair -alias fire -storetype PKCS12 -keyalg RSA -keystore fire.pkcs12 -storepass 13987664391 -validity 3650 -keysize 2048
您的名字与姓氏是什么?
[Unknown]: xu.dm
您的组织单位名称是什么?
[Unknown]: com.home
您的组织名称是什么?
[Unknown]: home
您所在的城市或区域名称是什么?
[Unknown]: km
您所在的省/市/自治区名称是什么?
[Unknown]: yn
该单位的双字母国家/地区代码是什么?
[Unknown]: cn
CN=xu.dm, OU=com.home, O=home, L=km, ST=yn, C=cn是否正确?
[否]: y
3.查看密钥库keystore证书BASE64信息
keytool -list -rfc -keystore fire.pkcs12 -storepass 13987664391
密钥库类型: PKCS12
密钥库提供方: SUN
您的密钥库包含 1 个条目
别名: fire
创建日期: 2021-1-25
条目类型: PrivateKeyEntry
证书链长度: 1
证书[1]:
-----BEGIN CERTIFICATE-----
MIIDUTCCAjmgAwIBAgIEKcHXqjANBgkqhkiG9w0BAQsFADBZMQswCQYDVQQGEwJj
bjELMAkGA1UECBMCeW4xCzAJBgNVBAcTAmttMQ0wCwYDVQQKEwRob21lMREwDwYD
VQQLEwhjb20uaG9tZTEOMAwGA1UEAxMFeHUuZG0wHhcNMjEwMTI1MDM0MDM1WhcN
MzEwMTIzMDM0MDM1WjBZMQswCQYDVQQGEwJjbjELMAkGA1UECBMCeW4xCzAJBgNV
BAcTAmttMQ0wCwYDVQQKEwRob21lMREwDwYDVQQLEwhjb20uaG9tZTEOMAwGA1UE
AxMFeHUuZG0wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCSPMos3BDL
SPHyS7dg+X6G1ce2vcEvXCbeGaptl7qs7kE78iHjXJd6lGLPwAn0iwNz+mEyqC94
jHFORypFlVHHExKvCe71u1TAxcEFc3ngGyJCxzPw2+1ET7EW0nQYlqM0ZKgqL+Tr
qCuYs+mJWmdqg4S+hXLi3f8heLTIA5+QAxucWwtVJyH0SF+5A+qWlF/Tk90+b8E5
Iv1d0bNZV7phwztgvJA7YlYrlo/lRUw4DQh+bqNmxjGApCN7rMVmICliYJJsLJZh
hIY98cscZ0A2buMXZIHkIWs9ThpJNpU4RQa6dZx17VaDiVfNa49r8Aj1RTApMz3/
WsiSuaKpkgHhAgMBAAGjITAfMB0GA1UdDgQWBBQdi78WTJWP9dYCc08GSHfdUPLD
xDANBgkqhkiG9w0BAQsFAAOCAQEAItCX9SN7/2rkvPoP51I9sap+TjjIwEQU6oEy
2B6toOCBx3akN0Kme5enLkmp2hU33R+FJhjUgXUrePlLz+yW/frE1Wi0YI+KdWZr
Fs0g7He0eRCZDMjkfnY6Pb2WHIaRJFNWwQ9Wf+7dOE9GfsgS3uVQjtpvfOAmjXlt
IerB4xbGydPsI4JnjXvyN4T6+18VT4PLnoosdSZ0bta0ZXIy3kN5GNlr9Y+Hp42c
Slenle06FQSczfb+1C/87rST20VCy0YmPq4SDdQSsiCZWAj4dWI7mJYkXnhH6AAm
QeXmUIZVmpRkPEvXIBLL3qZt7jv3Xlv65VfDsJmtNMRfC7KhbQ==
-----END CERTIFICATE-----
*******************************************
*******************************************
4.使用java代码生成密钥库
public static void createKeyStoreFile() throws Exception {
String filePath = "e:/myProgram/key/home.keystore";
final int keySize = 2048;
final String commonName = "xu.dm";
final String organizationalUnit = "com.home";
final String organization = "home";
final String city = "km";
final String state = "yn";
final String country = "cn";
final long validity = 3650; // 10 years
final String alias = "home";
final String keyPassword = "13987664391";
// keytool工具
CertAndKeyGen keyGen = new CertAndKeyGen("RSA", "SHA1WithRSA");
// 通用信息
X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);
// 根据密钥长度生成公钥和私钥
keyGen.generate(keySize);
PrivateKey privateKey = keyGen.getPrivateKey();
// 证书
X509Certificate certificate = keyGen.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null,null);
keyStore.setKeyEntry(alias,privateKey,keyPassword.toCharArray(),new Certificate[]{certificate});
FileOutputStream outputStream = new FileOutputStream(filePath);
keyStore.store(outputStream,keyPassword.toCharArray());
outputStream.close();
System.out.println("keyStore file created ...");
}
5.从密钥库keystore里提取私钥和证书
public static PrivateKey getPrivateKey() throws Exception {
String storepass = "13987664391";
String keyAlias = "honor";
BASE64Encoder base64Encoder = new BASE64Encoder();
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(KeyTools.class.getResourceAsStream("/key/home.pkcs12"), storepass.toCharArray());
PrivateKey key = (PrivateKey) keystore.getKey(keyAlias, storepass.toCharArray());
System.out.println(key.toString());
String privateKeyStr = base64Encoder.encode(key.getEncoded());
System.out.println();
System.out.println("-----BEGIN PRIVATE KEY-----");
System.out.println(privateKeyStr);
System.out.println("-----END PRIVATE KEY-----");
Certificate certificate = keystore.getCertificate(keyAlias);
PublicKey publicKey = certificate.getPublicKey();
System.out.println(publicKey);
// 打印certificate的base64编码
String certificateString = base64Encoder.encode(certificate.getEncoded());
System.out.println();
System.out.println("-----BEGIN CERTIFICATE-----");
System.out.println(certificateString);
System.out.println("-----END CERTIFICATE-----");
return key;
}
6.从证书中提取公钥BASE64编码字符串
/**
* 从CERTIFICATE文本中提取public key字符串
* CERTIFICATE本质是文本以"-----BEGIN CERTIFICATE-----"
* 并以"-----END CERTIFICATE-----"结束
*/
public static String getPublicKeyFromCertificate() throws CertificateException {
InputStream inputStream = KeyTools.class.getResourceAsStream("/key/home.PKCS12.cer");
CertificateFactory ft = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate) ft.generateCertificate(inputStream);
PublicKey publicKey = certificate.getPublicKey();
BASE64Encoder b64 = new BASE64Encoder();
String result = b64.encode(publicKey.getEncoded());
System.out.println("-----BEGIN PUBLIC KEY-----");
System.out.println(result);
System.out.println("-----END PUBLIC KEY-----");
return result;
}
7.从公钥BASE64字符串生成PublicKey对象
/**
* 从public key字符串中创建PublicKey对象
*
* @param signingKey 不包括"-----BEGIN PUBLIC KEY-----"和"-----END PUBLIC KEY-----"
*/
public static PublicKey getRsaPublicKey(String signingKey) {
try {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(signingKey));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
8.从密钥库keystore中提取密钥对,密钥对可以提取公钥和私钥对象
/**
* 根据Keystore生成密钥对
*/
public static KeyPair getKeyPair() throws Exception {
String storepass = "13987664391";
String keyAlias = "honor";
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(KeyTools.class.getResourceAsStream("/key/home.pkcs12"), storepass.toCharArray());
RSAPrivateCrtKey key = (RSAPrivateCrtKey) keystore.getKey(keyAlias, storepass.toCharArray());
RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
return new KeyPair(publicKey, key);
}