🔀 Merge branch “release-80”
[Sone.git] / src / main / java / net / pterodactylus / sone / freenet / Key.java
1 package net.pterodactylus.sone.freenet;
2
3 import static freenet.support.Base64.encode;
4 import static java.lang.String.format;
5
6 import freenet.keys.FreenetURI;
7
8 import com.google.common.annotations.VisibleForTesting;
9
10 /**
11  * Encapsulates the parts of a {@link FreenetURI} that do not change while
12  * being converted from SSK to USK and/or back.
13  */
14 public class Key {
15
16         private final byte[] routingKey;
17         private final byte[] cryptoKey;
18         private final byte[] extra;
19
20         private Key(byte[] routingKey, byte[] cryptoKey, byte[] extra) {
21                 this.routingKey = routingKey;
22                 this.cryptoKey = cryptoKey;
23                 this.extra = extra;
24         }
25
26         @VisibleForTesting
27         public String getRoutingKey() {
28                 return encode(routingKey);
29         }
30
31         @VisibleForTesting
32         public String getCryptoKey() {
33                 return encode(cryptoKey);
34         }
35
36         @VisibleForTesting
37         public String getExtra() {
38                 return encode(extra);
39         }
40
41         public FreenetURI toUsk(String docName, long edition, String... paths) {
42                 return new FreenetURI("USK", docName, paths, routingKey, cryptoKey,
43                                 extra, edition);
44         }
45
46         public FreenetURI toSsk(String docName, String... paths) {
47                 return new FreenetURI("SSK", docName, paths, routingKey, cryptoKey,
48                                 extra);
49         }
50
51         public FreenetURI toSsk(String docName, long edition, String... paths) {
52                 return new FreenetURI("SSK", format("%s-%d", docName, edition), paths,
53                                 routingKey, cryptoKey, extra, edition);
54         }
55
56         public static Key from(FreenetURI freenetURI) {
57                 return new Key(freenetURI.getRoutingKey(), freenetURI.getCryptoKey(),
58                                 freenetURI.getExtra());
59         }
60
61         public static String routingKey(FreenetURI freenetURI) {
62                 return from(freenetURI).getRoutingKey();
63         }
64
65 }