Https generates a certificate (keytool) and configures it in Springboot

keytoolIs a Java data certificate management tool that keytoolstores the key (key) and certificate ( certificates) in keystorea .

Related concepts: One article to understand HTTPS, certificate authority (CA), certificate, digital signature, private key, public key

In the keystore, there are two kinds of data:

  1. Key entity: secret key or private key and paired public key (using asymmetric encryption)
  2. Trusted certificate entries: contain only the public key
  3. ailas(alias): keystoreeach associated with this one is unique alias, this aliasis usually case insensitive

1. Keytool generates keystore

Common options in keytool:

-genkey: Creates a default file " " in the user's home directory .keystore, and also generates mykeyan alias mykeycontaining the user's public key, private key and certificate (if the generation location is not specified, keystorethe user's system default directory exists, such as: For the window xpsystem, it will be generated in the system's C:\Documents and Settings\UserName\ file named .keystore)
-alias: generate an alias
-keystore: specify the name of the keystore (all kinds of information generated will be in the .keystorefile )
-keyalg: specify the algorithm of the key (such as RSA, DSA (if not specified, DSA is used by default))
-validity: Specify how many days the created certificate is valid
-keysize: Specify the key length
-storepass: Specify the password of the keystore (password required to obtain keystoreinformation )
-keypass: Specify the password of the alias entry (private key password)
-dname: Specify the certificate owner information. For example: "CN=First and Last Name, OU=Organizational Unit Name, O=Organization Name, L=City or Region Name, ST=State or Province Name, C=Unit's Two-Letter Country Code"
-list: Displays the Certificate information. (keytool -list -v -keystore specifies keystore -storepass password)
-v: Displays certificate details in keystore.
-export: Export the certificate specified by the alias to a file. (keytool -export -alias needs to export the alias -keystore specifies the keystore -file specifies the exported certificate location and certificate name -storepass password)
-file: The parameter specifies the file name to be exported to the file
-delete: Delete an entry in the keystore. (keytool -delete -alias specifies the alias to be deleted -keystore specifies the keystore -storepass password)
-printcert: View the exported certificate information. (keytool -printcert -file yushan.crt)
-keypasswd: Modify the password of the specified entry in the keystore. (keytool -keypasswd -alias alias to be modified -keypass old password -new new password -storepass keystore password -keystore sage)
-storepasswd: Modify the keystore password. (keytool -storepasswd -keystore e:\yushan.keystore (keystore whose password needs to be modified) -storepass 123456 (original password) -new yushan (new password))
-import: Import the signed digital certificate into the keystore. (keytool -import -alias specifies the alias of the imported entry -keystore specifies the certificate to be imported in keystore -file)

1. Generate keystore file

# keytool -genkeypair -alias 别名 -keypass 私钥密码 -keyalg 密钥算法 -keysize 密钥长度 -validity 证书有效期 -keystore 密钥库的生成路径、名称 -storepass 密钥库密码
> keytool -genkeypair -alias test -keypass 123456 -keyalg RSA -keysize 1024 -validity 365 -keystore /Users/mac/Desktop/test.keystore -storepass 123456
您的名字与姓氏是什么?
  [Unknown]:  zyx
您的组织单位名称是什么?
  [Unknown]:  zyx
您的组织名称是什么?
  [Unknown]:  zyx
您所在的城市或区域名称是什么?
  [Unknown]:  bj
您所在的省/市/自治区名称是什么?
  [Unknown]:  bj
该单位的双字母国家/地区代码是什么?
  [Unknown]:  CN
CN=zyx, OU=zyx, O=zyx, L=bj, ST=bj, C=CN是否正确?
  []:  Y

2. View keystore file details

# keytool -list -v -keystore keystore文件 -storepass 密码
keytool -list -v -keystore test.keystore -storepass 123456

3. Export the certificate (public key) from the keystore

# keytool -export -alias 别名 -keystore keystore文件 -rfc -file 生成的证书名
keytool -export -alias test -keystore test.keystore -rfc -file test.cer

# .cer 转换成 .crt
openssl x509 -inform PEM -in test.cer -out test.crt

4. View certificate details

# keytool -printcert -file 证书名
keytool -printcert -file test.cer

5. Export the private key from the keystore

It is important to note that the private key cannot be exported from the certificate store, as that would be very insecure. If you specifically need the private key or private key string, you can only consider getting it from the keystore file programmatically.

Since the jdk command cannot generate the key, you need to use the keystorecode to read the private key base64encoded data from the file, and then format it as a line of 64 characters

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import sun.misc.BASE64Encoder;

class SllKeyStore {
    
    
    private File keystoreFile;
    private String keyStoreType;
    private char[] password;
    private String alias;
    private File exportedFile;

    public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
    
    
        try {
    
    
            Key key = keystore.getKey(alias, password);
            if (key instanceof PrivateKey) {
    
    
                Certificate cert = keystore.getCertificate(alias);
                PublicKey publicKey = cert.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        } catch (UnrecoverableKeyException e) {
    
    
        } catch (NoSuchAlgorithmException e) {
    
    
        } catch (KeyStoreException e) {
    
    
        }
        return null;
    }

	public void export() throws Exception {
    
    
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        BASE64Encoder encoder = new BASE64Encoder();
        keystore.load(new FileInputStream(keystoreFile), password);
        KeyPair keyPair = getPrivateKey(keystore, alias, password);
        PrivateKey privateKey = keyPair.getPrivate();
        String encoded = encoder.encode(privateKey.getEncoded());
        encoded = encoded.replaceAll("\n", "");
        
        //将密钥格式化为一行64个字符
        StringBuilder sb = new StringBuilder(encoded);
        int len = 64;
        while (len < sb.length()) {
    
    
            sb.insert(len, "\n");
            len += 65;
        }
        FileWriter fw = new FileWriter(exportedFile);
        fw.write("-----BEGIN RSA PRIVATE KEY-----\r\n");//私钥库文件必须以此开头,否则使用时会出错
        System.out.println(sb + "\n");

        fw.write(sb.toString());
        fw.write("\r\n-----END RSA PRIVATE KEY-----");//私钥库文件必须以此结尾
        fw.close();
    }


    public static void main(String args[]) throws Exception {
    
    
        SllKeyStore export = new SllKeyStore();
		
		// 指定自己的密钥库keystore文件
        export.keystoreFile = new File("/Users/mac/Desktop/test.keystore");//读取官钥库keystore文件
        export.keyStoreType = KeyStore.getDefaultType();

		// 指定密钥库密码
        String passwordString = "123456"; //密钥库口令
        export.password = passwordString.toCharArray();

		// 指定密钥库别名
        export.alias = "test";//密钥库别名

		// 指定要生成的私钥目录及文件名
        export.exportedFile = new File("/Users/mac/Desktop/test.key");//生成的私钥文件
        export.export();
    }
}

Second, the certificate format conversion

# .key 转换成 .pem:
openssl rsa -in test.key -out test.pem

# .crt 转换成 .pem:
openssl x509 -in test.crt -out test.pem

# .cer 转换成 .crt
openssl x509 -inform PEM -in test.cer -out test.crt

3. Springboot uses https

Put the generated keystorefile in the project's classpathdirectory and configure it in the application.yamlconfiguration file:

server:
  port: 8080

  #开启https,配置跟证书一一对应
  ssl:
  	#true表示开启HTTPS访问
    enabled: true
    #指定证书
    key-store: classpath:test.keystore
    #使用上面方法生成的格式为JKS
    key-store-type: JKS
    #默认为TLS,
    protocol: TLS
    #别名
    key-alias: test
    #私钥密码
    key-password: 123456
    #store文件密码
    key-store-password: 123456

Some SSL configurations in springboot:

configuration item illustrate
server.ssl.ciphers= Supported SSL ciphers.
server.ssl.client-auth= Whether client authentication is required ("want") or required ("need"). A trust store is required.
server.ssl.enabled=true Enable SSL support.
server.ssl.enabled-protocols= SSL protocol is enabled.
server.ssl.key-alias= An alias that identifies the key in the key store.
server.ssl.key-password= The password used to access keys in the key store.
server.ssl.key-store= Path to the key store (usually a jks file) that holds the SSL certificate.
server.ssl.key-store-password= The password used to access the key store.
server.ssl.key-store-provider= Provider for key storage.
server.ssl.key-store-type= Type of key store. (usually a jks file)
server.ssl.protocol=TLS The SSL protocol to use.
server.ssl.trust-store= A trust store that holds SSL certificates.
server.ssl.trust-store-password= Password to access the trust store.
server.ssl.trust-store-provider= The provider of the trust store.
server.ssl.trust-store-type= Type of trust store

Both HTTP and HTTPS protocols are supported: Spring Boot supports HTTPS

4. Postman sends https requests

Postman can access https requests without configuring certificates, but for custom certificates, you need to turn off SSL verification:

insert image description here

Postman sets ssl certificate: Postman requests https interface

Guess you like

Origin blog.csdn.net/zyx1260168395/article/details/112802464