java RSA asymmetric encryption decryption (concise)

Keywords: Java Apache

Last article: Generation of RSA asymmetric encryption certificate (concise and clear)

See my last article for the generation of Java asymmetric encryption certificate. The lower part is mainly the Java decryption part. Use the certificate pkcs8 ﹣ private ﹣ key.der (that is: Generation of RSA asymmetric encryption certificate (concise and clear) Generate a Java supported PKCS8 binary type private key) obtain the private key and decrypt the ciphertext.

Here is the main code:

package home;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.*;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAUtil {

    private static PrivateKey privateKey;

    static {
        try {
            InputStream in = (RSAUtil.class.getResourceAsStream("pkcs8_private_key.der"));
            //System.out.println("der:"+in);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            int count = 0;
            while ((count = in.read(temp)) != -1) {
                bout.write(temp, 0, count);
                temp = new byte[1024];
            }
            in.close();
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bout.toByteArray());
            privateKey = keyFactory.generatePrivate(privateKeySpec);
            //System.out.println("privateKey:"+privateKey);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("RSA encoder Exception");
        }
    }

    public static byte[] decodeBase64(String input) throws Exception{  
        Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");  
        Method mainMethod= clazz.getMethod("decode", String.class);  
        mainMethod.setAccessible(true);  
         Object retObj=mainMethod.invoke(null, input);  
         return (byte[])retObj;  
    } 

    public static String decodeText(String sec) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchProviderException, UnsupportedEncodingException,Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        //byte[] base64 = Base64.decodeBase64(sec.getBytes());
        byte[] base64 = decodeBase64(sec);
        byte[] deBytes = cipher.doFinal(base64);
        return new String(deBytes, "UTF-8");

    }

    public static void main(String[] args) throws Exception {
            //The previous encrypted text is: "I am the inscription, please encrypt me asymmetrically";
            //The corresponding ciphertext is: "f71xcg6r6whhc / Su / w84kfc9whsrr / ivqk + 6z3d5x78noscaplxqtih6hb3hlaqiqm347wdyqdjitfam / 99qmd8i9imii7rmbvxej7mljtay + pg4mkyusvqe4c8txa60wcalw62jscv4eiamhzdw2txjncummf + m5rrix0 ="
        System.out.println(RSAUtil.decodeText("f71XCg6R6wHC/SU/W84kFC9whsRr/ivQK+6Z3d5X78NOSCAplxqtIH6Hb3hHLAQiQm347WdYQdJItFAM/99QMD8I9ImiI7rMBvxEij7mLJtaY+pg4mkyuSvQe4C8tXA6ZEE0AWcaLw62JScV4EIaMHzdw2TxjNcUMmf+M5rRix0="));
    }
}

The following figure shows the results:

Posted by dwu on Fri, 03 Apr 2020 13:45:11 -0700