Introduction and implementation of asymmetric encryption algorithm

1, Introduction and implementation of asymmetric encryption algorithm

(1) Introduction to asymmetric encryption

Asymmetric encryption algorithm, also known as modern encryption algorithm, is the cornerstone of computer communication security, which ensures that the encrypted data will not be cracked. Unlike symmetric encryption algorithms, asymmetric encryption algorithms require two keys: public key and private key.

Features: in asymmetric encryption algorithm, public key and private key are a pair. It is characterized by public key encryption - private key decryption; Private key encryption - public key decryption. Because encryption and decryption use two different keys, this algorithm is called asymmetric encryption algorithm. Of course, things also have two sides. Due to the high security level of asymmetric encryption, the speed of processing data is relatively slow.

[easy to understand asymmetric encryption]
Take A sensitive file from A to B that needs to be encrypted as an example 👇

  • Symmetric encryption is: A locks the file with A lock and sends it to B, then A sends the key to B, and B gets the lock and key to unlock the file.
  • Asymmetric encryption is: A sends A file to B, B sends its own lock to A, and A locks it to B. B's key is always in its own hand, > unlock its own lock (public key) with its own key (private key), so there is no need to worry about the key being stolen in the process of transmission.

Comparison between ECC algorithm and RSA algorithm

RSA algorithm: an international standard algorithm, which has been applied earlier and is the most popular. It has a wider scope of application and better compatibility than ECC algorithm. Generally, the encryption length of 2048 bits is adopted, but it consumes high performance on the server.

ECC algorithm: the Chinese name is elliptic encryption algorithm. The new generation of algorithms tends to be the mainstream. Generally, 256 bit encryption length is adopted, which has fast encryption speed, higher efficiency, low consumption of server resources, and most importantly, it is more secure and more anti attack.

(2) Asymmetric encryption in Java

The following code demonstrates the implementation of asymmetric encryption algorithm using Java, mainly realizing the following methods:

  • Decrypt data with key: public static string decryptrsa (string algorithm, key, string encrypted)
  • Encrypt data with key: public static string encryptrsa (string algorithm, key, string input)
  • Generate a key pair and save it in a local file: private static void generatekeytofile (string algorithm, string pubpath, string private path)
  • Read private key: public static privatekey getprivatekey (string private path, string algorithm)
  • Read public key: public static publickey getpublickey (string pulickath, string algorithm)
/**
 * description: RSAdemo Generate public and private keys
 * @author: gql
 * @date: 2021/10
 */
public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "Anonymous siege lion";
        System.out.println("The original content is = " + input);

        // Indicates that RSA encryption algorithm is used
        String algorithm = "RSA";

        // Generate a key pair and save it in a local file
        generateKeyToFile(algorithm, "a.pub", "a.pri");
        System.out.println("Key pair saved to local successfully!");

        // Read private and public keys
        PrivateKey privateKey = getPrivateKey("a.pri", algorithm);
        PublicKey publicKey = getPublicKey("a.pub", algorithm);

        //encryption
        String s = encryptRSA(algorithm, privateKey, input);
        // decrypt
        decryptRSA(algorithm, publicKey, s);
    }

    /**
     * Decrypt data using key
     *
     * @param algorithm      : algorithm
     * @param encrypted      : ciphertext
     * @param key            : secret key
     * @return : original text
     * @throws Exception
     */
    public static String decryptRSA(String algorithm, Key key, String encrypted) throws Exception {
        // Create encrypted object
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Decrypt the private key
        cipher.init(Cipher.DECRYPT_MODE, key);
        // Since the ciphertext is Base64 encoded, it needs to be decoded here
        byte[] decode = Base64.decode(encrypted);
        // To decrypt the ciphertext, base64 is not required, because the original text will not be garbled
        byte[] bytes1 = cipher.doFinal(decode);
        System.out.println("After public key decryption = " + new String(bytes1));
        return new String(bytes1);

    }

    /**
     * Encrypt data with a key
     *
     * @param algorithm      : algorithm
     * @param input          : original text
     * @param key            : secret key
     * @return : ciphertext
     * @throws Exception
     */
    public static String encryptRSA(String algorithm, Key key, String input) throws Exception {
        // Create encrypted object
        Cipher cipher = Cipher.getInstance(algorithm);
        // Encryption mode, using private key or public key encryption
        cipher.init(Cipher.ENCRYPT_MODE, key);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        // Base64 encoding of ciphertext
        System.out.println("After private key encryption = " + Base64.encode(bytes));
        return Base64.encode(bytes);
    }

    /**
     * Generate a key pair and save it in a local file
     *
     * @param algorithm : Algorithm selection
     * @param pubPath   : Public key saving path
     * @param priPath   : Private key saving path
     * @throws Exception
     */
    private static void generateKeyToFile(String algorithm, String pubPath, String priPath) throws Exception {
        // Create key pair generator object
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Generate key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Generate private and public keys
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

        // Gets the byte array of the private key and public key
        byte[] privateKeyEncoded = privateKey.getEncoded();
        byte[] publicKeyEncoded = publicKey.getEncoded();

        // base64 encoding the private key and public key at the same time
        String privateKeyString = Base64.encode(privateKeyEncoded);
        String publicKeyString = Base64.encode(publicKeyEncoded);

        System.out.println("Generate private key = " + privateKeyString);
        System.out.println("Generate public key = " + publicKeyString);

        // Save file
        FileUtils.writeStringToFile(new File(priPath), privateKeyString, Charset.forName("UTF-8"));
        FileUtils.writeStringToFile(new File(pubPath), publicKeyString, Charset.forName("UTF-8"));
    }

    /**
     * Read private key
     * @param priPath Private key storage path
     * @param algorithm algorithm
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String priPath, String algorithm) throws Exception {
        // Convert file contents to strings
        String privateKeyString = FileUtils.readFileToString(new File(priPath), Charset.defaultCharset());
        // Get key factory
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        // Build key specification for Base64 decoding
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(privateKeyString));
        // Generate private key
        return keyFactory.generatePrivate(spec);
    }

    /**
     * Read public key
     * @param pulickPath Public key storage path
     * @param algorithm algorithm
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String pulickPath, String algorithm) throws Exception {
        // Convert file contents to strings
        String publicKeyString = FileUtils.readFileToString(new File(pulickPath), Charset.defaultCharset());
        // Get key factory
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        // Build key specification for Base64 decoding
        X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decode(publicKeyString));
        // Generate public key
        return keyFactory.generatePublic(spec);
    }
}

After the code runs, the console displays the following contents, and generates two txt files a.pri and a.pub in the project, saving the private key and key.

The original content is = Anon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5tinRe5ct+sSAgu5SRGpdfwKBgATlaSpJrnJi2yP0il8SElpQoFc3MxeHUvUJy/TNcd7xhV0NnkhakBBKn0E/zTiRdj97YVd+xWHeYTwEQCcfYC6rOqcriA2b2z2U+1ZR0T4hYVRQDH9+V7CzxMM1vB77KHC0Hi8ERsd1x6WtaeCMeDfgLHkvxRwWwEcO6devVd8dAoGBAII8b4lq9EKhYeM9l+oNjMJUwcbqD+uD0aSGYJm+ebgm2uIeVZ8wyZbNfo8pM8wwZjbTW7CaXr8PJM6SEoTcR7k2MK9sEGCwoPltt74m6tF3xGEvQiKdiHToU3zrpCSHUGJVwBHQYA1zyOHQqMtSJcwUdEqkLkmRD3vsCuo0VpKnAoGBAIE1HGHbnRtYJiUQx1GShBpnAOldTVNG/zkNXYviB5HqCOcXrvHEo7tZdNKPUIhIvkQ9enL00YxGxcKic1byccrR9JOCfZKpkwASfmZErK+QLt36RkluaJ3/h9EEcdLTJw8Zeb5KDeoOPtnbxlJeQ5hNp9W8OglTDUWEXOiUoXL8
 Generate public key = MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvwLSI1Q/9brpqPK6w5VyGt3lCMsU4WHF4AtlX8u6ZpzOFwOs11XIlXC/fn/YQU+ZQx65eauo9prn5xsejPiTMjnt3Hja4bOt4tFVqWeJVkbAgWWm+rsXT8BqoTGAaXWHAEaN1rTe5JmcVrSVt6ttho+s6TTr+nhwCBkih80JappzXLyxH5a3NC0WwGlw5dGwAKjFZ8oN94SXrIg9XMEjjTxBVygulF6EBptWPm7whhcjLLVgFvKB5NhEQvGQOjgNJPVI3s1vvisYSB/Sf3iyqF6RraNLwH0GMr04mlCI1Faibn91kTpG8JRmIrH9SqHG3TRSZrioDxh9Oe1+OkKgkwIDAQAB
 Key pair saved to local successfully!
After private key encryption = RD10/pSv/tnAWgereonEmobu3vxKgK6GACmUrBnaD8yj05IUvj54IN2DAyvsRdGijQDrEdbSIoIJOQen5g0UYjE6hHDhHTvuJqpNn+coJ3XcNQzQC4/ANij/hTZGFVX6AinhtqbZgpUDKoIhloJi+g9PV+MOuKgYVD7Fv96VDSbgR2bsuqFMDDIXtBCGQdR//KZmt7vKZGQTCjnP8PPcgnu68iayKFS/Ja38IYojl1F/JdrmNMM9zBJDTF/RfcHrGSAty68MZwopm1EQ8iSrpmM9DD/1y4Nr5jJmac14d57EmifqTfQH3oB+3kqvrSiyvDOof78zpcrQylyFs5epYA==
After public key decryption = Anonymous siege lion
 After encryption-The ciphertext is = RD10/pSv/tnAWgereonEmobu3vxKgK6GACmUrBnaD8yj05IUvj54IN2DAyvsRdGijQDrEdbSIoIJOQen5g0UYjE6hHDhHTvuJqpNn+coJ3XcNQzQC4/ANij/hTZGFVX6AinhtqbZgpUDKoIhloJi+g9PV+MOuKgYVD7Fv96VDSbgR2bsuqFMDDIXtBCGQdR//KZmt7vKZGQTCjnP8PPcgnu68iayKFS/Ja38IYojl1F/JdrmNMM9zBJDTF/RfcHrGSAty68MZwopm1EQ8iSrpmM9DD/1y4Nr5jJmac14d57EmifqTfQH3oB+3kqvrSiyvDOof78zpcrQylyFs5epYA==
After decryption-The original content is = Anonymous siege lion

2, Principle and implementation of digital signature

(1) Introduction to digital signature principle

Digital signature, also known as public key digital signature. It is one of the applications of asymmetric encryption technology. Asymmetric encryption technology mainly has two applications:

  • Encrypted communication decrypted using public key encryption private key;
  • Use private key encryption - digital signature decrypted by public key.

The meaning of digital signature: when transmitting data in the network, add a digital signature to the data to indicate who sent the data, and it can also prove that the data has not been tampered with.

The function of digital signature: authentication, anti repudiation and anti tampering.

Schematic diagram of digital signature

Typical application of digital signature: https protocol for web page encryption

① First, the client sends an encryption request to the server.
② After the server encrypts the web page with its own private key, it sends it to the client together with its own digital certificate.
③ The certificate manager of the client (browser) has a list of trusted root certification authorities. Based on this list, the client will check whether the public key to unlock the digital certificate is in the list.
④ If the web address recorded in the digital certificate is inconsistent with the web address you are browsing, it means that the certificate may be used fraudulently, and the browser will issue a warning.

⑤ If this digital certificate is not issued by a trusted authority, the browser will issue another warning.

⑥ If the digital certificate is reliable, the client can use the server public key in the certificate to encrypt the information, and then exchange the encrypted information with the server.

(2) Java implementation of digital signature

The following code demonstrates the implementation of digital signature using Java, mainly implementing the signature algorithm and verification algorithm:

  • Signature algorithm: private static string getsignature (string STR, string algorithm, privatekey, privatekey)
    The signature algorithm uses private key encryption to generate a signature.
    Note: the signature algorithm will not encrypt the file, but only the Hash value of the file
  • Verification algorithm: private static Boolean verifysignature (string STR, string algorithm, publickey, publickey, string signatureddata)
    The verification algorithm uses public key decryption - verification signature.
/**
 * description: SignatureDemo digital signature 
 * @author: gql
 * @date: 2021/10
 */
public class SignatureDemo {
    public static void main(String[] args) throws Exception {
        String str = "Hudie";
        System.out.println("The original text is = " + str);

        // Get the private key and public key from the file
        PrivateKey privateKey = RSAdemo.getPrivateKey("a.pri", "RSA");
        PublicKey publicKey = RSAdemo.getPublicKey("a.pub", "RSA");

        /**
         * Signature algorithm:
         *  Input: file, private key (signature Key)
         *  Output: digital signature
         */
        String signaturedData = getSignature(str, "sha256withrsa", privateKey);
        System.out.println("The generated digital signature is = " + signaturedData);

        /**
         * Validation algorithm:
         *  Input: file, digital signature, public key (verification Key)
         *  Output: YES/NO
         */
        boolean flag = verifySignature(str, "sha256withrsa", publicKey, signaturedData);
        System.out.println("Verify with public key and generated signature: = " + flag);
    }

    /**
     * Signature algorithm:
     *      Private key encryption - generate signature
     * Note: the signature algorithm will not encrypt the file, but only the Hash value of the file
     * @param str      : original text
     * @param algorithm  : algorithm
     * @param privateKey : Private key
     * @return : digital signature 
     * @throws Exception
     */
    private static String getSignature(String str, String algorithm, PrivateKey privateKey) throws Exception {
        // Get signature object
        Signature signature = Signature.getInstance(algorithm);
        // Initialization signature
        signature.initSign(privateKey);
        // Incoming text
        signature.update(str.getBytes());
        // Start signing
        byte[] sign = signature.sign();
        // Base64 encoding of signature data
        return Base64.encode(sign);
    }

    /**
     * Validation algorithm:
     *      Public key decryption - Verification Signature
     * @param str          : original text
     * @param algorithm      : algorithm
     * @param publicKey      : Public key
     * @param signaturedData : digital signature 
     * @return : Is the data tampered with
     * @throws Exception
     */
    private static boolean verifySignature(String str, String algorithm, PublicKey publicKey, String signaturedData) throws Exception {
        // Get signature object
        Signature signature = Signature.getInstance(algorithm);
        // Initialization signature
        signature.initVerify(publicKey);
        // Incoming text
        signature.update(str.getBytes());
        // Check data
        return signature.verify(Base64.decode(signaturedData));
    }
}

Some contents refer to: Digital signature principle of b station

Tags: Java Algorithm

Posted on Wed, 13 Oct 2021 08:58:50 -0400 by heerajee