RSA Encryption Algorithm

RSA is an asymmetric encryption algorithm. Asymmetric encryption algorithms use different keys for encryption and decryption. In addition to encryption and decryption, RSA also performs signature functions. Asymmetric encryption usually takes more time than symmetric encryption.

  • Encryption and decryption with public key encryption, decryption with private key; After the public key is encrypted, only the private key can be decrypted. Therefore, data cannot be decrypted. ;
  • Signature generates the signature with the private key and verifies the signature with the public key. This can determine whether the sender is the target identity.

Generating a key pair

Both encryption, decryption and signature require a key pair.

public static KeyPair genKeyPair(a) throws NoSuchAlgorithmException {
   The KeyPairGenerator class is used to generate public and private key pairs based on the RSA algorithm to generate objects
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
    // Initialize the key pair generator, the key size is 96-1024 bits
    keyPairGen.initialize(1024.new SecureRandom());
    // generate a keyPair, stored in keyPair
    KeyPair keyPair = keyPairGen.generateKeyPair();
    return keyPair;
}
Copy the code

Encryption and decryption examples

The code in this example is largely based on RSA encryption and decryption (Java implementation)

encryption

Encrypt with public key

public static String encrypt( String str, Key publicKey ) throws Exception{
        / / RSA encryption
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        String outStr = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }
Copy the code

Decrypt with a private key

 public static String decrypt(String str, Key privateKey) throws Exception{
        // 64-bit decoded encrypted string
        byte[] inputByte = Base64.getDecoder().decode(str.getBytes("UTF-8"));
        / / RSA decryption
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }
Copy the code
public static void main(String[] args) throws Exception {
     // Encrypt the character string
     String message = "df723820";
     KeyPair keyPair = genKeyPair();
     PrivateKey privateKey = keyPair.getPrivate();   // get the private key
     PublicKey publicKey =  keyPair.getPublic();  // Get the public key
     String messageEn = encrypt(message,publicKey);
     log.info("Before encryption :{}",message);
     log.info("Encrypted :{}",messageEn);
     String messageDe = decrypt(messageEn,privateKey);
     log.info("Restored string :{}" , messageDe);
}
Copy the code

Signature example

This example mainly refers to implementing RSA signature and encryption in Java

The private key generates a signature

public static String sign(String plainText, PrivateKey privateKey) throws Exception {
    Signature privateSignature = Signature.getInstance("SHA256withRSA");
    privateSignature.initSign(privateKey);
    privateSignature.update(plainText.getBytes(StandardCharsets.UTF_8));

    byte[] signature = privateSignature.sign();

    return Base64.getEncoder().encodeToString(signature);
}
Copy the code

Public key authentication signature

public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
     Signature publicSignature = Signature.getInstance("SHA256withRSA");
     publicSignature.initVerify(publicKey);
     publicSignature.update(plainText.getBytes(StandardCharsets.UTF_8));

     byte[] signatureBytes = Base64.getDecoder().decode(signature);

     return publicSignature.verify(signatureBytes);
 }
Copy the code

The complete code

public static void main(String[] args) throws Exception {
   String sign = sign(message, keyPair.getPrivate());
   boolean verify = verify(message,sign, keyPair.getPublic());
   log.info("Check pass :{}",verify);
}
Copy the code

As you can see, the signing step is very similar to the encryption and decryption step. But the algorithm used here is SHA256 Withrsa, which contains SHA256 and RSA. Because it is too much to perform signature calculation on the data directly, the abstract of information is usually generated according to the data first, and then the abstract of information is signed to reduce the amount of calculation. SHA stands for Secure Hash Algorithm. SHA256 is a Hash function that summarizes the information on the data. RSA then signs the digest.

HMAC, MD5

What is the difference between RSA and HMAC, MD5, and SHA

  • HMAC
    • HMAC abstracts data based on key and hash function, and the two parties usually share the key. You can select the specified hash functions, such as MD5 and SHA256, which are called hMAC-MD5, HmacSHA256, and HmacSHA256 respectively. HMAC verifies data integrity check and identity authentication.
  • MD5, SHA
    • MD5 and SHA are hash functions that digest information. They can be used to verify data integrity but cannot prove identity.

Q&A

  • Generally, public key encryption, private key decryption; Encrypt the private key and decrypt the public key, okay?
    • Yes, according to the RSA derivation formula, public and private keys can be encrypted and decrypted each other. This code up here, just swap keys and try it out, and it works.
  • Can I make the private key public and the public key private?
    • Can’t. This is easy to crack, because the private key is long and the public key is short (see online generator), so hacker thinks a “private key” is really a “public key,” which has a short value and is easy to extract; Which RSA public key is used for encryption and which is used for decryption?

With practice

If you understand all the above, then you will understand the wechat payment documentThis picture

When the merchant requests wechat, the merchant private key is used to generate the signature, and the wechat credit merchant public key verifies the signature; In response information, the platform private key is used to generate the signature, and the merchant uses the platform public key to verify the signature. When wechat requests merchants, wechat private key is used to generate signatures, and merchants use wechat public key to verify signatures. In response information, the merchant private key is used to generate the signature, and the platform uses the merchant public key to verify the signature. The preceding private key and public key are the RSA private key and public key. Merchant public key and platform public key are stored in merchant certificate and platform certificate respectively. Note That the certificate in this section is different from the certificate in HTTPS, but similar. The certificate is the carrier of the public key. The certificate has the signature of the certificate issuing authority to prevent man-in-the-middle attacks and verify the validity of the public key.

APIV3 key is the key of AES algorithm, which is shared by wechat and merchants.