Encryption and decryption of RSA in java

1. Introduction

  • Background: RSA was proposed in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman. All three were working at MIT at the time. RSA is composed of the initial letters of their three surnames[1].
  • Features: The password and account number entered each time are different after being encrypted, but md5 encryption is the same.
  • Note: The public key and private key must be paired!

2. Generate key pairs

public void generateKeyPair() throws NoSuchAlgorithmException{
    
    
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
        //生成的公钥
        String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
        //生成的私钥
        String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
    }

3. Public key encryption

/**
     * 公钥加密
     *
     * @param publicKeyString 公钥
     * @param text 待加密的文本
     * @return 加密后的文本
     */
    public static String encryptByPublicKey(String publicKeyString, String text) throws Exception
    {
    
    
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encodeBase64String(result);
    }

4. Private key decryption

/**
     * 私钥解密
     *
     * @param privateKeyString 私钥
     * @param text 待解密的文本
     * @return 解密后的文本
     */
    public static String decryptByPrivateKey(String privateKeyString, String text) throws Exception
    {
    
    
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decodeBase64(text));
        return new String(result);
    }

Five, the required jar package dependencies

<!--常用工具类 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

or directly

<dependency>
     <groupId>commons-codec</groupId>
     <artifactId>commons-codec</artifactId>
</dependency>

Guess you like

Origin blog.csdn.net/weixin_43684214/article/details/128183025