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
8 import java.io.StringReader;
9 import java.security.PrivateKey;
10 import java.util.Objects;
11 import java.util.Optional;
12
13
14
15
16
17
18
19
20
21
22
23 public class StringPrivateKeyProvider implements KeyProvider<PrivateKey> {
24 private final String keyId;
25 private final Optional<PrivateKey> privateKey;
26
27
28
29
30
31
32
33
34
35 public StringPrivateKeyProvider(KeyReader keyReader, String key, String keyId) {
36 this.keyId = Objects.requireNonNull(keyId);
37 this.privateKey = tryReadPrivateKey(keyReader, key);
38 }
39
40 private static Optional<PrivateKey> tryReadPrivateKey(KeyReader keyReader, String key) {
41 try {
42 return Optional.of(keyReader.readPrivateKey(new StringReader(key)));
43 } catch (CannotRetrieveKeyException e) {
44 return Optional.empty();
45 }
46 }
47
48 @Override
49 public PrivateKey getKey(ValidatedKeyId keyId) throws CannotRetrieveKeyException {
50 if (keyId.getKeyId().equals(this.keyId)) {
51 return privateKey.orElseThrow(() -> new CannotRetrieveKeyException("Cannot parse private key"));
52 } else {
53 throw new CannotRetrieveKeyException("Cannot find private key");
54 }
55 }
56 }