bcgit / bc-java

Bouncy Castle Java Distribution (Mirror)
https://www.bouncycastle.org/java.html
MIT License
2.33k stars 1.14k forks source link

How to parse PKCS1 encrypted privatekey by EC and sm4-cbc #1066

Open flymoondust opened 3 years ago

flymoondust commented 3 years ago

Private key like this: -----BEGIN EC PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: SM4-CBC,xxxxxxx xxxx -----END EC PRIVATE KEY-----

I find out that the PEMUtilities.crypt don't support algorithm like sm4-cbc

my code like this:

 PEMParser pemParser = new PEMParser(new StringReader(keyStr));
            Object object = pemParser.readObject();
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
            KeyPair kp;
            if (object instanceof PEMEncryptedKeyPair) {
                // Encrypted key - we will use provided password
                PEMEncryptedKeyPair ckp = (PEMEncryptedKeyPair) object;
                // uses the password to decrypt the key
                PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().setProvider("BC").build(keyPass);
                kp = converter.getKeyPair(ckp.decryptKeyPair(decProv));
                privateKey = kp.getPrivate();
            }

i encounter error like this:

org.bouncycastle.openssl.EncryptionException: unknown encryption with private key
    at org.bouncycastle.openssl.jcajce.PEMUtilities.crypt(Unknown Source) ~[bcpkix-jdk15on-1.68.jar:1.68.00.0]
    at org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder$1$1.decrypt(Unknown Source) ~[bcpkix-jdk15on-1.68.jar:1.68.00.0]
    at org.bouncycastle.openssl.PEMEncryptedKeyPair.decryptKeyPair(Unknown Source) ~[bcpkix-jdk15on-1.68.jar:1.68.00.0]
mmdet commented 2 years ago

bc库已经实现了sm4算法,估计需要你自己重写某些方法来扩展了