-
- private KeyPair getKeyPair(final String keyId) {
- // public key retrieval logic taken from DatastoreBackedPublicKeyAuth
- final var dsKeypair = credentialProvider.credentialForId(keyId);
- if (dsKeypair == null) {
- throw new IllegalArgumentException("No keypair found with keyId=" + keyId);
- }
- final var passPhrase = Strings.isNullOrEmpty(dsKeypair.getPassphrase()) ? "" : dsKeypair.getPassphrase();
- try {
- return decodePrivateKey(decryptString(dsKeypair.getPrivateKey()), decryptString(passPhrase));
- } catch (IOException e) {
- throw new IllegalStateException("Could not decode private key with keyId=" + keyId, e);
- }
- }
-
- private String decryptString(final String encrypted) {
- final byte[] cryptobytes = Base64.getDecoder().decode(encrypted);
- final byte[] clearbytes;
- try {
- clearbytes = encryptionService.decrypt(cryptobytes);
- } catch (GeneralSecurityException e) {
- throw new IllegalStateException("Failed to decrypt", e);
- }
- return new String(clearbytes, StandardCharsets.UTF_8);
- }
-
-
- @VisibleForTesting
- static KeyPair decodePrivateKey(final String privateKey, final String passphrase) throws IOException {
- try (var keyReader = new PEMParser(new StringReader(privateKey.replace("\\n", "\n")))) {
- final var obj = keyReader.readObject();
-
- final PEMKeyPair keyPair;
- if (obj instanceof PEMEncryptedKeyPair encrypted) {
- keyPair = encrypted.decryptKeyPair(new JcePEMDecryptorProviderBuilder()
- .setProvider(BCPROV)
- .build(passphrase.toCharArray()));
- } else if (obj instanceof PEMKeyPair plain) {
- keyPair = plain;
- } else {
- throw new IllegalArgumentException("Unhandled private key " + obj.getClass());
- }
-
- return new JcaPEMKeyConverter().getKeyPair(keyPair);
- }
- }