RSA algorithm - using the private signature, public key signature verification

1. symmetric encryption and asymmetric encryption

        Encryption technology is the most common means of security and confidentiality, data encryption technology is the key encryption / decryption algorithm and key management. Data encryption is the basic process of the original plain text file or data processed by an encryption algorithm, making it unreadable piece of code, typically a "ciphertext." After the "ciphertext" can only enter the appropriate key to display the original content, to ensure that the encrypted content through this pathway is not stolen.

        Characterized by symmetric encryption file or data encryption and decryption using the same key , this method become cryptography symmetric encryption algorithm .

        An asymmetric encryption algorithm different from the algorithm symmetric encryption, asymmetric encryption algorithm requires two keys, a public key (PublicKey) and private key (the PrivateKey) . A pair of public and private key, if the data using the public key encryption, the corresponding private key can decrypt; if the data using a private key encryption, the corresponding public key can decrypt.

2. asymmetric cryptography algorithm --RSA

        RSA algorithm is commonly used asymmetric encryption technology, it is the origin of the name of the person making Ron Rivest, the first letter of Adi Shamir, Leonard Adleman three people last name. In general, asymmetric cryptography in two ways, one is the use of public key cryptography, private key to decrypt; the other is the private key signature described herein, signed public inspection.

2.1 generate a certificate file

        First, the RSA algorithm to generate a certificate file the certificate file will contain information of public and private keys.

        Keytool is a certificate management tool provided by Java, here we will use keytool to generate the key certificate. Use keytool to generate a certificate file has the following steps

        1. JDK ensure environment variables are available;

        2. Open the cmd window, and enter the destination folder generated certificate (the certificate will be generated in the current folder);

        3. The code section executed command, a command meaning of each parameter are as follows:

           -alias: alias key, and here I set mountainkey

           -keyalg: hash algorithm used, here I am using the RSA algorithm

           -keypass: access to cryptographic keys, and here I set to mountain

           -keystore: key store file name, where I set mountain.keystore, generated files are saved in the contents of the certificate in mountain.keystore

           -storepass: access password key store, where I set mountainkeystore

keytool -genkeypair -alias mountainkey -keyalg RSA -keypass mountain -keystore mountain.keystore -storepass mountainkeystore

        Command input process as shown below.

        Executed successfully generated certificate file included in the directory in which dos window, as shown in FIG.

2.2 obtain the public key

        Generated certificate file contains a public key and a private key mountain.keystore, and now obtain the public key from the certificate. Here we need to use openssl toolkit for download at http://slproweb.com/products/Win32OpenSSL.html

        After successfully downloaded and installed, the added openssl bin directory path environment variable, as shown in FIG.

        Now, with just a certificate cmd into the directory where the file, enter the following command (the certificate file is mountain.keystore), typing storepass set of keys when prompted for a password library, which is the secret key store password.

keytool -list -rfc --keystore mountain.keystore | openssl x509 -inform pem -pubkey

       Displays the following contents, the content contains the public key information, that is, from the content BEGIN PUBLIC KEY END PUBLIC KEY The string is used to check by the private key encrypted content.

2.3 using the private key signature

        Now we test to obtain a certificate by the private key to encrypt data which is capable of reading the certificate file and obtain the private key has a lot of methods, and here I use the method provided by the Spring Security to carry out this operation.

    /**
     * 读取证书文件中的私钥,并使用私钥对数据加密,得到加密后的字符串
     */    
    @Test
    public void testGenerateToken(){
        String keystore = "mountain.keystore";
        String keystorePassword = "mountainkeystore";
        ClassPathResource classPathResource = new ClassPathResource(keystore);
        String alias  = "mountainkey";
        String keyPassword = "mountain";
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource,keystorePassword.toCharArray());
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias, keyPassword.toCharArray());
        RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
        Map<String,String> contentMap = new HashMap<>();
        contentMap.put("hello","hello world");
        String bodyString = JSON.toJSONString(contentMap);
        Jwt jwt = JwtHelper.encode(bodyString, new RsaSigner(aPrivate));
        String encodedContent = jwt.getEncoded();
        System.out.println(encodedContent);
    }

        After the private key to encrypt the contents of the console printing are as follows.

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJoZWxsbyI6ImhlbGxvIHdvcmxkIn0.LNB7GpiTYl1G4MNYpFDPgay6funMLXeoGUo3TU30IfhIJiSU7zobJ-SpJap6ARbCJoRc5_JURb4ti-6vanf3cpIyOayk2H83gfBOSY8_wACbpfhlt_PGT0RYfStGC7OVwKFUAdEaO6hYYD466vI8d6d9uNb1RfNfGToYlosH05McYAyrM2XLcy0T7glZmuNw_JgMflRAjN09K13MlQZttn6W-lhSlv38CE1_CJ8SzNLHC6U7Dzd1FlcW9Xs-IvDalw1xzgzNRfbNpdvcZTnNhbdNa6_bSlSIfSM9IHngG3EVS_hwQkGOfBeV5gxQZrW4BB9niK8FwvoDB1cVjy4Ktw

2.4 checksum using the public key

        The data using the private key signature verification, here still use Spring Security provides.

    /**
     * 使用公钥校验加密后的字符串
     */
    @Test
    public void testCheckTokenByPublicKey() {
        // 公钥
        String publickey = "-----BEGIN PUBLIC KEY-----" +
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtbuddIbMU5FjqpJR4Ikn" +
                "xktq1k/0C10XfOR2VU79qh4PXGSNn6Vt5BZgK8Ow4cA7SzAMoBUkxev/5I2Mx4p4" +
                "gk+6ImQ+IsTi6tqXOQ7DHjpogfsX/VeXJ93Aeq8v9hOqtKYj5q1jy4skGRvbD+c8" +
                "Z6knxLQb9I6HE39v3BZZL+WTYz6kx8BTZ0rPd7C5uOVqYo/FG+QzY+Ndv2u7gNcy" +
                "V9sRnM+hI2w5e87LuG+V6GhekdKqtS0dsjKskpjX/L2ppykdi1hkCtS/ipZ5aaAj" +
                "/SzVfWfQTxw4Yh+3QVc+KoSW61KlCZ+SSu7YrszAqlg93927/eWWLjYUFsCqP0jw" +
                "5wIDAQAB" +
                "-----END PUBLIC KEY-----";
        // 私钥加密后的内容
        String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJoZWxsbyI6ImhlbGxvIHdvcmxkIn0.LNB7GpiTYl1G4MNYpFDPgay6funMLXeoGUo3TU30IfhIJiSU7zobJ-SpJap6ARbCJoRc5_JURb4ti-6vanf3cpIyOayk2H83gfBOSY8_wACbpfhlt_PGT0RYfStGC7OVwKFUAdEaO6hYYD466vI8d6d9uNb1RfNfGToYlosH05McYAyrM2XLcy0T7glZmuNw_JgMflRAjN09K13MlQZttn6W-lhSlv38CE1_CJ8SzNLHC6U7Dzd1FlcW9Xs-IvDalw1xzgzNRfbNpdvcZTnNhbdNa6_bSlSIfSM9IHngG3EVS_hwQkGOfBeV5gxQZrW4BB9niK8FwvoDB1cVjy4Ktw";
        //校验jwt令牌
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(publickey));
        //拿到jwt令牌中自定义的内容
        String claims = jwt.getClaims();
        System.out.println(claims);
    }

        Print the contents of the console that is using data from previous private key signature.

{"hello":"hello world"}

 

Published 48 original articles · won praise 52 · views 20000 +

Guess you like

Origin blog.csdn.net/y506798278/article/details/104145607