1 package com.atlassian.refapp.trustedapps.internal;
2
3 import com.atlassian.security.auth.trustedapps.EncryptionProvider;
4 import com.atlassian.user.util.Base64Encoder;
5 import org.apache.log4j.Logger;
6
7 import java.security.Key;
8 import java.security.NoSuchAlgorithmException;
9 import java.security.NoSuchProviderException;
10 import java.security.PrivateKey;
11 import java.security.PublicKey;
12 import java.security.spec.InvalidKeySpecException;
13
14 public class KeyUtils {
15 private static final Logger log = Logger.getLogger(KeyUtils.class);
16
17 public static String encode(Key key) {
18 return new String(Base64Encoder.encode(key.getEncoded()));
19 }
20
21 public static PrivateKey decodePrivateKey(EncryptionProvider encryptionProvider, String keyStr) {
22 final byte[] data = Base64Encoder.decode(keyStr.getBytes());
23 try {
24 return encryptionProvider.toPrivateKey(data);
25 } catch (NoSuchProviderException e) {
26 log.error(e);
27 return new InvalidPrivateKey(e);
28 } catch (NoSuchAlgorithmException e) {
29 log.error(e);
30 return new InvalidPrivateKey(e);
31 } catch (InvalidKeySpecException e) {
32 log.error(e);
33 return new InvalidPrivateKey(e);
34 }
35 }
36
37 public static PublicKey decodePublicKey(EncryptionProvider encryptionProvider, String keyStr) {
38 final byte[] data = Base64Encoder.decode(keyStr.getBytes());
39 try {
40 return encryptionProvider.toPublicKey(data);
41 } catch (NoSuchProviderException e) {
42 log.error(e);
43 return new InvalidPublicKey(e);
44 } catch (NoSuchAlgorithmException e) {
45 log.error(e);
46 return new InvalidPublicKey(e);
47 } catch (InvalidKeySpecException e) {
48 log.error(e);
49 return new InvalidPublicKey(e);
50 }
51 }
52
53
54
55
56
57
58 public static class InvalidPrivateKey extends InvalidKey implements PrivateKey {
59 public InvalidPrivateKey(Exception cause) {
60 super(cause);
61 }
62 }
63
64
65
66
67
68 public static class InvalidPublicKey extends InvalidKey implements PublicKey {
69 public InvalidPublicKey(Exception cause) {
70 super(cause);
71 }
72 }
73
74 static class InvalidKey implements Key {
75 private final Exception cause;
76
77 public InvalidKey(Exception cause) {
78 this.cause = cause;
79 }
80
81 public String getAlgorithm() {
82 return "";
83 }
84
85
86 public String getFormat() {
87 return "";
88 }
89
90
91 public byte[] getEncoded() {
92 return new byte[0];
93 }
94
95 public String toString() {
96 return "Invalid Key: " + cause.toString();
97 }
98
99 public Exception getCause() {
100 return cause;
101 }
102 }
103
104
105 }