|
8 | 8 | import net.snowflake.client.jdbc.internal.org.bouncycastle.jce.provider.BouncyCastleProvider; |
9 | 9 | import net.snowflake.client.jdbc.internal.org.bouncycastle.openssl.PEMParser; |
10 | 10 | import net.snowflake.client.jdbc.internal.org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; |
| 11 | +import net.snowflake.client.jdbc.internal.org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder; |
| 12 | +import net.snowflake.client.jdbc.internal.org.bouncycastle.operator.InputDecryptorProvider; |
| 13 | +import net.snowflake.client.jdbc.internal.org.bouncycastle.operator.OperatorCreationException; |
| 14 | +import net.snowflake.client.jdbc.internal.org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo; |
| 15 | +import net.snowflake.client.jdbc.internal.org.bouncycastle.pkcs.PKCSException; |
11 | 16 |
|
12 | 17 | // ref: |
13 | 18 | // https://docs.snowflake.com/en/developer-guide/jdbc/jdbc-configure#privatekey-property-in-connection-properties |
14 | 19 | public class PrivateKeyReader { |
15 | | - public static PrivateKey get(String pemString) throws IOException { |
| 20 | + public static PrivateKey get(String pemString, String passphrase) |
| 21 | + throws IOException, OperatorCreationException, PKCSException { |
16 | 22 | Security.addProvider(new BouncyCastleProvider()); |
17 | 23 | PEMParser pemParser = new PEMParser(new StringReader(pemString)); |
18 | 24 | Object pemObject = pemParser.readObject(); |
19 | 25 | pemParser.close(); |
20 | 26 |
|
21 | 27 | PrivateKeyInfo privateKeyInfo; |
22 | | - if (pemObject instanceof PrivateKeyInfo) { |
| 28 | + if (pemObject instanceof PKCS8EncryptedPrivateKeyInfo) { |
| 29 | + // Handle the case where the private key is encrypted. |
| 30 | + PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = |
| 31 | + (PKCS8EncryptedPrivateKeyInfo) pemObject; |
| 32 | + InputDecryptorProvider pkcs8Prov = |
| 33 | + new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase.toCharArray()); |
| 34 | + privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(pkcs8Prov); |
| 35 | + } else if (pemObject instanceof PrivateKeyInfo) { |
23 | 36 | privateKeyInfo = (PrivateKeyInfo) pemObject; |
24 | 37 | } else { |
25 | 38 | throw new IllegalArgumentException("Provided PEM does not contain a valid Private Key"); |
|
0 commit comments