[JAVA] RSA asymmetric encryption practice and stepping on the pit

1. First upload the public key encryption code

public String encryptByPublicKey(String publicKeyString, String text) throws Exception
        {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] result = cipher.doFinal(text.getBytes());
            return Base64.encodeBase64String(result);
        }

2. Errors may occur during operation, the errors are as follows

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException :

3. Reason

Because the public key is in PKCS1 format (applicable to non-java), after converting to PKCS8 format (applicable to java), there is no problem

4. Online tool for converting PKCS1 format to PKCS8 format

SSL online tool-online RSA public-private key format conversion|public key PKCS1 and PKCS8 conversion|private key PKCS1 and PKCS8 conversion-SSLeye official website

Guess you like

Origin blog.csdn.net/songyun333/article/details/129693070