RSA Decryption Error: java.security.InvalidKeyException: IOException : algid parse error, not a sequence

To get a private key, you need to decrypt the encrypted data. I can’t figure it out. When I get the privatekey, I report an error algid parse error, not a sequence

KeyFactory.getInstance("RSA").generatePrivate(
                    new PKCS8EncodedKeySpec(Encodes.decodeBase64("priKey")))

The reason is that the private key string is not in PKCs #8’s format and cannot be transferred without using a third-party jar

One solution is to use OpenSSL to convert the private key string into pkcs#8 format

The second is to use the third-party library. I use the third-party library bouncy castle, which is more convenient and fast. I don’t bother to install OpenSSL

pom:

<dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcprov-jdk15on</artifactId>
                <version>1.59</version>
            </dependency>
            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcmail-jdk15on</artifactId>
                <version>1.59</version>
            </dependency>
            <dependency>
                <groupId>org.bouncycastle</groupId>
                <artifactId>bcpkix-jdk15on</artifactId>
                <version>1.59</version>
            </dependency>

Restore private/public key to PEM file

public static PrivateKey get10027504355PrivateKey() throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("config/10027504355ssl.pem")));
        PEMParser pemParser = new PEMParser(br);
        PEMKeyPair pemKeyPair = (PEMKeyPair)pemParser.readObject();
        pemParser.close();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        KeyPair keyPair = converter.getKeyPair(pemKeyPair);
        PublicKey publicKey=keyPair.getPublic();
        return keyPair.getPrivate();
    }

Add bouncycastleprovider when the application starts and initialize it once

package com.mktpay.admin.init;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.security.Security;

/**
 * @ClassName Runner
 * @Author yupanpan
 * @Date 2021/10/11 15:03
 */
@Component
public class EDncryptRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        //Customize other ways to initialize encryption and decryption algorithms
        Security.addProvider(new BouncyCastleProvider());
    }
}

Read More: