当前位置:网站首页>Quickly understand the commonly used asymmetric encryption algorithm, and no longer have to worry about the interviewer's thorough inquiry

Quickly understand the commonly used asymmetric encryption algorithm, and no longer have to worry about the interviewer's thorough inquiry

2022-06-23 13:17:00 51CTO

interviewer : Tell me about your common encryption algorithms ?

Encryption algorithms are usually divided into two types : Symmetric encryption algorithm and Asymmetric encryption algorithm . among , Symmetric encryption algorithm uses the same key for encryption and decryption ; Asymmetric encryption algorithm uses different keys for encryption and decryption , It is divided into public key and private key . Besides , There is also a class called Message digest algorithm , It is an irreversible algorithm for summarizing data .

This time we will learn about asymmetric encryption algorithm .

Asymmetric encryption algorithm

Asymmetric encryption algorithm uses two different keys for encryption and decryption , One of the keys that can be made public is called Public key , Another fully secret key is called Private key . Only the same public key and private key pair can be encrypted and decrypted normally .

For the same public and private key pair , If you use the public key to encrypt the data , Only the corresponding private key can be used for decryption ; If you use a private key to encrypt data , Only the corresponding public key can be used for decryption .

The common asymmetric encryption algorithms are :RSA Algorithm 、DSA.

RSA Algorithm

RSA The algorithm is the most influential public key encryption algorithm at present , It consists of Ron Rivest、Adi Shamir and Leonard Adleman Three big men are 1977 It was put forward together when working at the Massachusetts Institute of technology in ,RSA It's a combination of the three of them .

 Quickly understand common asymmetric encryption algorithms , No longer have to worry about the interviewer's thorough inquiry _ encryption algorithm

in addition ,1973 year , A mathematician working at the British government communications headquarters Clifford Cocks An equivalent algorithm is proposed in an internal file , But the algorithm is classified , until 1997 It was only in .

RSA The algorithm utilizes two number theoretic properties :

  1. p1、p2 For two prime numbers , n=p1 * p2. It is known that p1、p2 seek n Simple , It is known that n seek p1、p2 It is difficult to .
  2. (m^e) mod n=c, It is known that m、e、n seek c Simple , It is known that e、n、c seek m It is difficult to .

Public and private key generation process : Randomly select two prime numbers p1、p2,n=p1 * p2, And then randomly select one and φ(n) Coprime and less than φ(n) The integer of e, And then calculate e about φ(n) The modulo inverse elements of d, Finally get n and e For public key ,n and d For private key .

The encryption process :(m^e) mod n = c, among m In plain text ,c For the cipher ,n and e For public key .

The decryption process :(c^d) mod n = m, among m In plain text ,c For the cipher ,n and d For private key .

We use it Java Write an example :

import javax.crypto.Cipher;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaUtil {

    private static final String RSA = "RSA";
    private static final Charset CHARSET = StandardCharsets.UTF_8;

    /** *  encryption  * * @param input  Plaintext  * @param publicKey  Public key  * @return  Ciphertext  * @throws GeneralSecurityException */
    public static String encrypt(String input, String publicKey) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(RSA);
        PublicKey pubKey = KeyFactory.getInstance(RSA)
                .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey)));
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] data = cipher.doFinal(input.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(data);
    }

    /** *  Decrypt  * * @param input  Ciphertext  * @param privateKey  Private key  * @return  Plaintext  * @throws GeneralSecurityException */
    public static String decrypt(String input, String privateKey) throws GeneralSecurityException {
        Cipher cipher = Cipher.getInstance(RSA);
        PrivateKey priKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] data = cipher.doFinal(Base64.getDecoder().decode(input));
        return new String(data, CHARSET);
    }

    public static void main(String[] args) throws GeneralSecurityException {
        //  Generate public key / Private key pair :
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance(RSA);
        kpGen.initialize(1024);
        KeyPair keyPair = kpGen.generateKeyPair();
        String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
        System.out.println(" Public key :" + publicKey);
        System.out.println(" Private key :" + privateKey);

        String msg = " I like you , Can you be my girl friend? ?";
        System.out.println(" Before encryption :" + msg);
        String pwd = RsaUtil.encrypt(msg, publicKey);
        System.out.println(" After encryption :" + pwd);
        System.out.println(" After decryption :" + RsaUtil.decrypt(pwd, privateKey));
    }
}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.

The operation results are as follows :

 Public key :MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDd4brSm8gdJqFi04m3aW8kjVYbd/T4ymyc7l3c2WmwOhVPlZO1eaZJpTvas61rW0HPf267CRIhc52Zp2+e1hoknApvT0gKeRkfSwC5aws/yoT2vZ9J627QbCFkFc8mmfP8LJ5V/rCpmUE12dIW4xVlEYtWPzmNK2iTMzuR99Jq9wIDAQAB
 Private key :MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAN3hutKbyB0moWLTibdpbySNVht39PjKbJzuXdzZabA6FU+Vk7V5pkmlO9qzrWtbQc9/brsJEiFznZmnb57WGiScCm9PSAp5GR9LALlrCz/KhPa9n0nrbtBsIWQVzyaZ8/wsnlX+sKmZQTXZ0hbjFWURi1Y/OY0raJMzO5H30mr3AgMBAAECgYEAuxPtKlAwzOtaXXIQhrV+AWqttGFTCkXaiAKu31vssap3d2+daACWxTdtHPwr9v2tol9GpKqEP/I0am5zPZA13x+tv068x2TxGf8ZEbp579CKE3NrzTrnhtJN31TT82HIJoJ0TsNUhHbwZPWVAsq98afSCP1rn5RY/kwJ6bzsjhECQQD8Ev044KaUdWd0WZoomMP+5tATUL0HTMmUiBEvrXjOWG2mjuD4M5n/9C11FZWFg+o75riAUiNYE5dfGyK1uDP5AkEA4VZdUOTPt0DclMESX3lOddS3o+TL/OkowErP0mAl3NzbJ1PnDUifQ0q1IZUoCi1nG9eVZScS8xZ7oa7ICgdybwJBAIY/OrsK8cyJBlLx0WcjjOZ5WIGg8zsrCwRevwBsW7VRZPxahbfKC49EJN2BZENaMOo8AzDcDdS/glN1aTPsaUkCQAVLhj3UYp0nxQcp0ki0DQfvy7DqO3Dh+bcrCt8iq0EZX3z5F8DUKAnow4DahGpYzsd0tWn/FQ7pRFZ0SPcTXbkCQQCp7ay9nEo2hEH08E5LekFsuipDjCEpeCgKojZUmFCh7BdawG6XzCLzNMMIIIjqRHlrJaxS41WhedPZR4nTNxGF
 Before encryption : I like you , Can you be my girl friend? ?
 After encryption :tRt5hdF0XB8V2wk6BWC2i8UWVQj/jOCRZn3wIfGYqVaYJ9OjC/+VRUI3c5WgpZlKCZd5zrHo3g1LuQ02G934Gcb51cKH4uhWxRY8oxUgs/fibkvc9+w1X7FQarFwAGCs5SddHIL/vYUxHIvQslelyP9l9/EFpgSs0WWSfOfKcUc=
 After decryption : I like you , Can you be my girl friend? ?

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

RSA The algorithm solves the problem that the security of symmetric algorithm depends on the same key . however ,RSA The algorithm is computationally quite complex , Poor performance 、 Far less than symmetric encryption algorithm . therefore , In general practice , Asymmetric encryption algorithms are often used to randomly create temporary symmetric keys , Then a large number of... Are transmitted through symmetric encryption 、 Subject data .

DSA

DSA(Digital Signature Algorithm, Digital signature algorithm ) yes Schnorr and ElGamal A variety of signature algorithms , Complexity based on modulo arithmetic and discrete logarithm .

National institute of standards and technology (NIST) On 1991 Proposed in DSA For its DSS(DigitalSignature Standard, Digital signature standard ), And in 1994 It was regarded as FIPS 186 use .

and RSA The algorithm uses public key encryption and private key decryption in different ways ,DSA Use the private key to encrypt the data to generate a digital signature , Then the decrypted data is compared with the original data using the public key , To verify the digital signature .

Digital signatures provide information authentication ( The recipient can verify the source of the message ), integrity ( The receiver can verify that the message has not been modified since it was signed ) And non repudiation ( Senders cannot falsely claim that they have not signed the message ).

We use it Java Write an example :

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class DsaUtil {

    private static final String DSA = "DSA";
    private static final String SHA1withDSA = "SHA1withDSA";
    private static final Charset CHARSET = StandardCharsets.UTF_8;

    /** *  Signature  * * @param data  data  * @param privateKey  Private key  * @return  Signature  * @throws GeneralSecurityException */
    public static String sign(String data, String privateKey) throws GeneralSecurityException {
        PrivateKey priKey = KeyFactory.getInstance(DSA)
                .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
        Signature signature = Signature.getInstance(SHA1withDSA);
        signature.initSign(priKey);
        signature.update(data.getBytes(CHARSET));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    /** *  verification  * * @param data  data  * @param publicKey  Public key  * @param sign  Signature  * @return  Whether the verification is passed  */
    public static boolean verify(String data, String publicKey, String sign) throws GeneralSecurityException {
        try {
            PublicKey pubKey = KeyFactory.getInstance(DSA)
                    .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey)));
            Signature signature = Signature.getInstance(SHA1withDSA);
            signature.initVerify(pubKey);
            signature.update(data.getBytes(CHARSET));
            return signature.verify(Base64.getDecoder().decode(sign));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws GeneralSecurityException {
        //  Generate public key / Private key pair :
        KeyPairGenerator kpGen = KeyPairGenerator.getInstance(DSA);
        kpGen.initialize(1024);
        KeyPair keyPair = kpGen.generateKeyPair();
        String publicKey = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        String privateKey = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
        System.out.println(" Public key :" + publicKey);
        System.out.println(" Private key :" + privateKey);

        String msg = " I like you , Can you be my girl friend? ?";
        System.out.println(" data :" + msg);
        String sign = DsaUtil.sign(msg, privateKey);
        System.out.println(" Signature :" + sign);
        System.out.println(" Verify pass :" + DsaUtil.verify(msg, publicKey, sign));
    }

}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.

The operation results are as follows :

 Public key :MIIBtzCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoDgYQAAoGABDM1s78NZ4C0Bh9V86Z1lylEyCjCg2oAj6Kxd3/2IXhSlplnSpJPLlomet9yWJpagLQieIWHAIyq6JLmdcVxOxUvnLIsrvWKIPr4lz7pIqO1xi4AYunP48gPECHlMgOKPyik3ZkQQ3iHl9MiaWOaeisqsw/gzTUtE1xi8CVscks=
 Private key :MIIBSwIBADCCASwGByqGSM44BAEwggEfAoGBAP1/U4EddRIpUt9KnC7s5Of2EbdSPO9EAMMeP4C2USZpRV1AIlH7WT2NWPq/xfW6MPbLm1Vs14E7gB00b/JmYLdrmVClpJ+f6AR7ECLCT7up1/63xhv4O1fnxqimFQ8E+4P208UewwI1VBNaFpEy9nXzrith1yrv8iIDGZ3RSAHHAhUAl2BQjxUjC8yykrmCouuEC/BYHPUCgYEA9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFnEj6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTxvqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSoEFgIUA1HUKjMiSvazMzpKczR6w6DDbeM=
 data : I like you , Can you be my girl friend? ?
 Signature :MCwCFHhnd/3yRCIygyD1GPa1K9ZVQ+4rAhR8zAtlrBim9KKEkv+Fxz47opvSuA==
 Verify pass :true

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

adopt Java You can see the example of , The private key will not be directly encrypted to the data , Instead, the data is summarized through the information summarization algorithm , Then encrypt the private key of the summary information .

summary

Asymmetric encryption algorithm uses two different keys for encryption and decryption , They are called public key and private key respectively , Only the same public key and private key pair can be encrypted and decrypted normally .

The common asymmetric encryption algorithms are :RSA Algorithm 、DSA.RSA The algorithm mainly encrypts the data with public key ,DSA Mainly for signature verification of data .

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231232078906.html

随机推荐