Merge branch 'release/0.9-rc1'
[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  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
15  */
16 public class Key {
17
18         private final byte[] routingKey;
19         private final byte[] cryptoKey;
20         private final byte[] extra;
21
22         private Key(byte[] routingKey, byte[] cryptoKey, byte[] extra) {
23                 this.routingKey = routingKey;
24                 this.cryptoKey = cryptoKey;
25                 this.extra = extra;
26         }
27
28         @VisibleForTesting
29         public String getRoutingKey() {
30                 return encode(routingKey);
31         }
32
33         @VisibleForTesting
34         public String getCryptoKey() {
35                 return encode(cryptoKey);
36         }
37
38         @VisibleForTesting
39         public String getExtra() {
40                 return encode(extra);
41         }
42
43         public FreenetURI toUsk(String docName, long edition, String... paths) {
44                 return new FreenetURI("USK", docName, paths, routingKey, cryptoKey,
45                                 extra, edition);
46         }
47
48         public FreenetURI toSsk(String docName, String... paths) {
49                 return new FreenetURI("SSK", docName, paths, routingKey, cryptoKey,
50                                 extra);
51         }
52
53         public FreenetURI toSsk(String docName, long edition, String... paths) {
54                 return new FreenetURI("SSK", format("%s-%d", docName, edition), paths,
55                                 routingKey, cryptoKey, extra, edition);
56         }
57
58         public static Key from(FreenetURI freenetURI) {
59                 return new Key(freenetURI.getRoutingKey(), freenetURI.getCryptoKey(),
60                                 freenetURI.getExtra());
61         }
62
63         public static String routingKey(FreenetURI freenetURI) {
64                 return from(freenetURI).getRoutingKey();
65         }
66
67 }