1 package com.atlassian.asap.core.keys.privatekey;
2
3 import com.atlassian.asap.api.exception.CannotRetrieveKeyException;
4 import com.atlassian.asap.core.keys.KeyProvider;
5 import com.atlassian.asap.core.keys.KeyReader;
6 import com.atlassian.asap.core.validator.ValidatedKeyId;
7 import com.google.common.base.Preconditions;
8 import org.slf4j.Logger;
9 import org.slf4j.LoggerFactory;
10
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.InputStreamReader;
14 import java.nio.charset.StandardCharsets;
15 import java.security.PrivateKey;
16 import java.util.Objects;
17
18 import static com.atlassian.asap.core.keys.ClassPathUri.classPathUri;
19
20
21
22
23 public class ClasspathPrivateKeyProvider implements KeyProvider<PrivateKey> {
24 private static final Logger logger = LoggerFactory.getLogger(ClasspathPrivateKeyProvider.class);
25
26 private final KeyReader keyReader;
27 private final String classpathBase;
28
29
30
31
32 public ClasspathPrivateKeyProvider(String classpathBase, KeyReader keyReader) {
33 this.keyReader = Objects.requireNonNull(keyReader);
34 this.classpathBase = Objects.requireNonNull(classpathBase);
35 Preconditions.checkArgument(classpathBase.endsWith("/"), "Classpath prefix must end with a slash");
36 }
37
38 @Override
39 public PrivateKey getKey(ValidatedKeyId validatedKeyId) throws CannotRetrieveKeyException {
40 String pathToPrivateKey = classpathBase + validatedKeyId.getKeyId();
41
42 logger.debug("Reading private key from classpath: {}", pathToPrivateKey);
43
44 try (InputStream inputStream = ClasspathPrivateKeyProvider.class.getResourceAsStream(pathToPrivateKey)) {
45 if (inputStream == null) {
46 throw new CannotRetrieveKeyException("Private key not found in the classpath", classPathUri(pathToPrivateKey));
47 }
48 try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.US_ASCII)) {
49 return keyReader.readPrivateKey(reader);
50 }
51 } catch (IOException e) {
52 throw new CannotRetrieveKeyException("Error retrieving private key from classpath", e, classPathUri(pathToPrivateKey));
53 }
54 }
55
56 @Override
57 public String toString() {
58 return this.getClass().getSimpleName();
59 }
60 }