Cryptography: asymmetric encryption

catalogue

Asymmetric encryption

Generate public and private keys

Private key encryption

Private key encryption private key decryption

Private key encryption public key decryption

Public key encryption and public key decryption

Save public and private keys

Read private key

Read public key

Asymmetric encryption

Introduction:

① Asymmetric encryption algorithm is also called modern encryption algorithm.

② Asymmetric encryption 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

④ Public and private keys are a pair

⑤ If the data is encrypted with a public key, it can only be decrypted with the corresponding private key.

⑥ If the data is encrypted with a private key, it can only be decrypted with the corresponding public key.

⑦ Because encryption and decryption use two different keys, this algorithm is called asymmetric encryption algorithm.

  • Example
    • First, a key pair is generated. The public key is (5,14) and the private key is (11,14)
    • Now A wants to send original 2 to B
    • A uses the public key to encrypt data 2 to the 5th power mod 14 = 4, send ciphertext 4 to B
    • B decrypts data using the private key 4 to the 11th power mod14 = 2, get the original 2
  • characteristic
    • Encryption and decryption use different keys
    • If you use private key encryption, you can only use public key decryption
    • If you use public key encryption, you can only decrypt using the private key
    • Processing data is slower because of the high level of security
  • Common algorithms
    • RSA
    • ECC

Generate public and private keys

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
public class RSAdemo {
    public static void main(String[] args) throws Exception {
      
        // encryption algorithm 
        String algorithm = "RSA";
        //  Create key pair generator object
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Generate key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Generate private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Generate public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key byte array
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Get public key byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        // base64 encoding of public and private keys
        String privateKeyString = Base64.encode(privateKeyEncoded);
        String publicKeyString = Base64.encode(publicKeyEncoded);
        // Print private key
        System.out.println(privateKeyString);
        // Print public key
        System.out.println(publicKeyString);
    }
}

Run the program: the private key is printed first, and the public key is printed later

Private key encryption

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "silicon valley";
        // encryption algorithm 
        String algorithm = "RSA";
        //  Create key pair generator object
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Generate key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Generate private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Generate public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key byte array
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Get public key byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        // base64 encoding of public and private keys
        String privateKeyString = Base64.encode(privateKeyEncoded);
        String publicKeyString = Base64.encode(publicKeyEncoded);


        // Create encrypted object
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Initialize encryption
        // First parameter: encryption mode
        // Second parameter: use private key for encryption
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        System.out.println(Base64.encode(bytes));
       
    }
}

Run program

Private key encryption private key decryption

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "silicon valley";
        // encryption algorithm 
        String algorithm = "RSA";
        //  Create key pair generator object
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Generate key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Generate private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Generate public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key byte array
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Get public key byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        // base64 encoding of public and private keys
        String privateKeyString = Base64.encode(privateKeyEncoded);
        String publicKeyString = Base64.encode(publicKeyEncoded);


        // Create encrypted object
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Initialize encryption
        // First parameter: encryption mode
        // The second parameter: use the private key for encryption
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        System.out.println(Base64.encode(bytes));
        // Decrypt the private key
        cipher.init(Cipher.DECRYPT_MODE,publicKey);
        // To decrypt the ciphertext, base64 is not required, because the original text will not be garbled
        byte[] bytes1 = cipher.doFinal(bytes);
        System.out.println(new String(bytes1));

    }
}

Run the program because the private key is encrypted and can only be decrypted by the public key

Private key encryption public key decryption

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "silicon valley";
        // encryption algorithm 
        String algorithm = "RSA";
        //  Create key pair generator object
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Generate key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Generate private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Generate public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key byte array
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Get public key byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        // base64 encoding of public and private keys
        String privateKeyString = Base64.encode(privateKeyEncoded);
        String publicKeyString = Base64.encode(publicKeyEncoded);


        // Create encrypted object
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Initialize encryption
        // First parameter: encryption mode
        // Second parameter: use private key for encryption
        cipher.init(Cipher.ENCRYPT_MODE,privateKey);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        System.out.println(Base64.encode(bytes));
        // Decrypt the private key
        cipher.init(Cipher.DECRYPT_MODE,publicKey);
        // To decrypt the ciphertext, base64 is not required, because the original text will not be garbled
        byte[] bytes1 = cipher.doFinal(bytes);
        System.out.println(new String(bytes1));

    }
}

Run program

Public key encryption and public key decryption

It will also report an error

Save public and private keys

The previous code will generate encryption and decryption every time. We need to transfer all the encryption and decryption methods to the local root directory.

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "silicon valley";
        // encryption algorithm 
        String algorithm = "RSA";

        //Generate a key pair and save it in a local file
        generateKeyToFile(algorithm, "a.pub", "a.pri");

          //encryption
//        String s = encryptRSA(algorithm, privateKey, input);
        // decrypt
//        String s1 = decryptRSA(algorithm, publicKey, s);
//        System.out.println(s1);


    }

    /**
     * Generate a key pair and save it in a local file
     *
     * @param algorithm : algorithm
     * @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 {
        // Get key pair generator
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Get key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Get public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Get byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Base64 encoding
        String publicKeyString = Base64.encode(publicKeyEncoded);
        String privateKeyString = Base64.encode(privateKeyEncoded);
        // Save file
        FileUtils.writeStringToFile(new File(pubPath), publicKeyString, Charset.forName("UTF-8"));
        FileUtils.writeStringToFile(new File(priPath), privateKeyString, Charset.forName("UTF-8"));

    }

    /**
     * Decrypt data
     *
     * @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(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
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Initialize encryption
        // First parameter: encryption mode
        // Second parameter: use private key for encryption
        cipher.init(Cipher.ENCRYPT_MODE,key);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        // Base64 encoding of ciphertext
        System.out.println(Base64.encode(bytes));
        return Base64.encode(bytes);
    }
}

Run to generate the private key at the root of the project

Run to generate the public key at the root of the project

Read private key

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "silicon valley";
        // encryption algorithm 
        String algorithm = "RSA";
        PrivateKey privateKey = getPrivateKey("a.pri", algorithm);



    }

    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);
    }

    /**
     * Generate a key pair and save it in a local file
     *
     * @param algorithm : algorithm
     * @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 {
        // Get key pair generator
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Get key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Get public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Get byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Base64 encoding
        String publicKeyString = Base64.encode(publicKeyEncoded);
        String privateKeyString = Base64.encode(privateKeyEncoded);
        // Save file
        FileUtils.writeStringToFile(new File(pubPath), publicKeyString, Charset.forName("UTF-8"));
        FileUtils.writeStringToFile(new File(priPath), privateKeyString, Charset.forName("UTF-8"));

    }

    /**
     * Decrypt data
     *
     * @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(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
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Initialize encryption
        // First parameter: encryption mode
        // Second parameter: use private key for encryption
        cipher.init(Cipher.ENCRYPT_MODE,key);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        // Base64 encoding of ciphertext
        System.out.println(Base64.encode(bytes));
        return Base64.encode(bytes);
    }
}

Read public key

import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.apache.commons.io.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAdemo {
    public static void main(String[] args) throws Exception {
        String input = "silicon valley";
        // encryption algorithm 
        String algorithm = "RSA";
        PrivateKey privateKey = getPrivateKey("a.pri", algorithm);
        PublicKey publicKey = getPublicKey("a.pub", algorithm);

        String s = encryptRSA(algorithm, privateKey, input);
        String s1 = decryptRSA(algorithm, publicKey, s);
        System.out.println(s1);


    }

    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);
    }

    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);
    }

    /**
     * Generate a key pair and save it in a local file
     *
     * @param algorithm : algorithm
     * @param pubPath   : Public key saving path
     * @param priPath   : Private key saving path
     * @throws Exception
     */
    public static void generateKeyToFile(String algorithm, String pubPath, String priPath) throws Exception {
        // Get key pair generator
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
        // Get key pair
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // Get public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key
        PrivateKey privateKey = keyPair.getPrivate();
        // Get byte array
        byte[] publicKeyEncoded = publicKey.getEncoded();
        byte[] privateKeyEncoded = privateKey.getEncoded();
        // Base64 encoding
        String publicKeyString = Base64.encode(publicKeyEncoded);
        String privateKeyString = Base64.encode(privateKeyEncoded);
        // Save file
        FileUtils.writeStringToFile(new File(pubPath), publicKeyString, Charset.forName("UTF-8"));
        FileUtils.writeStringToFile(new File(priPath), privateKeyString, Charset.forName("UTF-8"));

    }

    /**
     * Decrypt data
     *
     * @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);
        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
        // The parameter represents the encryption algorithm
        Cipher cipher = Cipher.getInstance(algorithm);
        // Initialize encryption
        // First parameter: encryption mode
        // Second parameter: use private key for encryption
        cipher.init(Cipher.ENCRYPT_MODE,key);
        // Private key encryption
        byte[] bytes = cipher.doFinal(input.getBytes());
        // Base64 encoding of ciphertext
        return Base64.encode(bytes);
    }
}

Run program

Keywords: Encryption cryptology base64

Added by hamboy on Tue, 18 Jan 2022 06:43:40 +0200