package util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMDecryptorProvider;
import org.bouncycastle.openssl.PEMEncryptedKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.PKCS8Generator;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;

import java.io.StringReader;
import java.security.PrivateKey;
import java.security.Security;

public class KeyUtils {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static PrivateKey loadEncryptedPrivateKey(String encryptedKeyPem, String password) throws Exception {
        PEMParser pemParser = new PEMParser(new StringReader(encryptedKeyPem));
        Object object = pemParser.readObject();
        pemParser.close();

        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            // PKCS#8 加密格式
            PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object;
            InputDecryptorProvider decryptorProvider = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .setProvider("BC")
                    .build(password.toCharArray());
            return converter.getPrivateKey(encryptedInfo.decryptPrivateKeyInfo(decryptorProvider));
        }

        throw new IllegalArgumentException("Unsupported key format");
    }
}