source: trunk/src/org/expeditee/encryption/Actions.java@ 1456

Last change on this file since 1456 was 1456, checked in by bnemhaus, 4 years ago

Added usage instructions to SplitSecret and GenerateSecret actions.

File size: 9.9 KB
Line 
1package org.expeditee.encryption;
2
3import java.security.InvalidKeyException;
4import java.security.NoSuchAlgorithmException;
5import java.security.SecureRandom;
6import java.util.Arrays;
7import java.util.Base64;
8import java.util.Collection;
9import java.util.HashMap;
10import java.util.List;
11import java.util.Map;
12import java.util.Random;
13
14import javax.crypto.BadPaddingException;
15import javax.crypto.Cipher;
16import javax.crypto.IllegalBlockSizeException;
17import javax.crypto.NoSuchPaddingException;
18import javax.crypto.SecretKey;
19import javax.crypto.spec.SecretKeySpec;
20
21import org.expeditee.auth.AuthenticatorBrowser;
22import org.expeditee.auth.account.Authenticate;
23import org.expeditee.core.Colour;
24import org.expeditee.gui.DisplayController;
25import org.expeditee.gui.Frame;
26import org.expeditee.gui.FrameIO;
27import org.expeditee.gui.FreeItems;
28import org.expeditee.gui.MessageBay;
29import org.expeditee.items.Item;
30import org.expeditee.items.Text;
31import org.expeditee.settings.UserSettings;
32
33import com.codahale.shamir.Scheme;
34
35public class Actions implements CryptographyConstants {
36
37 public static void SetSurrogateFor(Text surrogate, Text action) {
38 Frame frame = DisplayController.getCurrentFrame();
39 String[] split = action.getText().split(" ");
40
41 if (split.length >= 2) {
42 int primaryID = Integer.parseInt(split[1]);
43 Item itemWithID = frame.getItemWithID(primaryID);
44 if (itemWithID == null) {
45 MessageBay.displayMessage("No item with ID " + primaryID + " exists on this frame.");
46 return;
47 } else {
48 itemWithID.addToSurrogates(surrogate);
49 }
50 } else {
51 MessageBay.displayMessage("Usage: SetSurrogateFor Int, inject desired surrogate.");
52 }
53 }
54
55 public static Text GenerateSecret() {
56 return AuthGenerateSecretUsage();
57 }
58
59 public static Text GenerateSecret(String label) {
60 String nl = System.getProperty("line.separator");
61 String secretsFrame = UserSettings.UserName.get() + 11;
62 StringBuilder instructions = new StringBuilder("You have generated a encryption label with name " + label + "." + nl);
63 instructions.append("Place this generated label on your secrets frame (" + secretsFrame + ") before using it.");
64 MessageBay.displayMessage(instructions.toString()).setLink(secretsFrame);
65 return AuthGenerateSecret(label);
66 }
67
68 public static Text SplitSecret(Text key) {
69 return AuthSplitSecret(key);
70 }
71
72 public static Text JoinSecret(Text key) {
73 return AuthJoinSecret(key);
74 }
75
76 public static void Encrypt(Text labelWithKey) {
77 AuthEncrypt(labelWithKey);
78 }
79
80 public static void Decrypt(Text labelWithKey) {
81 AuthDecrypt(labelWithKey);
82 }
83
84 public static Text AuthGenerateSecret() {
85 return AuthGenerateSecretUsage();
86 }
87
88 public static Text AuthGenerateSecret(String label) {
89 // Generate AES Key
90 Random rand = new SecureRandom();
91 byte[] keyBytes = new byte[16];
92 rand.nextBytes(keyBytes);
93 String key = Base64.getEncoder().encodeToString(keyBytes);
94
95 Text text = new Text(label);
96 text.setData(key);
97 text.setPosition(DisplayController.getMousePosition());
98 return text;
99 }
100
101 public static Text AuthSplitSecret(Text key) {
102 if (!FreeItems.hasItemsAttachedToCursor()) {
103 return AuthSplitSecretUsage();
104 }
105
106 // Retrieve secret
107 String secret = key.getData().get(0);
108 byte[] secretBytes = Base64.getDecoder().decode(secret);
109
110 // Obtain parameters for shamir
111 String[] arguments = key.getText().split(" ");
112 int requiredShares = Integer.parseInt(arguments[1]);
113 int totalShares = arguments.length - 2;
114
115 // Create shares
116 Scheme scheme = new Scheme(new SecureRandom(), totalShares, requiredShares);
117 Map<Integer, byte[]> split = scheme.split(secretBytes);
118
119 // Add shares to key
120 List<String> data = key.getData();
121 for (Integer i: split.keySet()) {
122 data.add("{" + i + "}" + Base64.getEncoder().encodeToString(split.get(i)));
123 }
124 key.setData(data);
125 key.setText(arguments[0]);
126
127 return key;
128 }
129
130 public static Text AuthJoinSecret(Text key) {
131 Map<Integer, byte[]> contributingParts = new HashMap<Integer, byte[]>();
132
133 // Retrieve splits
134 List<String> data = key.getData();
135 for (String d: data) {
136 if (d.startsWith("{")) {
137 String[] split = d.split("}");
138 Integer k = Integer.parseInt(split[0].replace("{", ""));
139 byte[] v = Base64.getDecoder().decode(split[1]);
140 contributingParts.put(k, v);
141 }
142 }
143
144 // Obtain parameters for shamir
145 String[] arguments = key.getText().split(" ");
146 int totalShares = Integer.parseInt(arguments[2]);
147 int requiredShares = Integer.parseInt(arguments[1]);
148
149 // Perform join
150 Scheme scheme = new Scheme(new SecureRandom(), totalShares, requiredShares);
151 byte[] join = scheme.join(contributingParts);
152
153 data.clear();
154 data.add(Base64.getEncoder().encodeToString(join));
155
156 return key;
157 }
158
159 public static void AuthEncrypt(Text labelWithKey) {
160 // Obtain encryption key
161 String keyEncoded = labelWithKey.getData().get(0);
162 byte[] keyDecoded = Base64.getDecoder().decode(keyEncoded);
163 SecretKey key = new SecretKeySpec(keyDecoded, SymmetricAlgorithm);
164
165 // Perform encryption
166 Frame toEncrypt = FrameIO.LoadFrame(labelWithKey.getLink());
167 Collection<Text> textItems = toEncrypt.getTextItems();
168 for (Text t: textItems) {
169 byte[] encrypted = EncryptSymmetric(t.getText().getBytes(), key);
170 t.setText(Base64.getEncoder().encodeToString(encrypted));
171 }
172
173 // Save changes
174 FrameIO.SaveFrame(toEncrypt);
175 }
176
177 public static void AuthDecrypt(Text labelWithKey) {
178 // Obtain encryption key
179 String keyEncoded = labelWithKey.getData().get(0);
180 byte[] keyDecoded = Base64.getDecoder().decode(keyEncoded);
181 SecretKey key = new SecretKeySpec(keyDecoded, SymmetricAlgorithm);
182
183 // Perform decryption
184 Frame toDecrypt = FrameIO.LoadFrame(labelWithKey.getLink());
185 Collection<Text> textItems = toDecrypt.getTextItems();
186 for (Text t: textItems) {
187 byte[] decrypted = DecryptSymmetric(Base64.getDecoder().decode(t.getText().getBytes()), key);
188 t.setText(new String(decrypted));
189 }
190
191 // Save changes
192 FrameIO.SaveFrame(toDecrypt);
193 }
194
195 public static byte[] EncryptSymmetric(final byte[] toEncrypt, final SecretKey key) {
196 // toEncrypt = Base64.getDecoder().decode(toEncrypt);
197 try {
198 final Cipher cipher = Cipher.getInstance(SymmetricAlgorithm + SymmetricAlgorithmParameters);
199 cipher.init(Cipher.ENCRYPT_MODE, key);
200 //could use modulus
201 final int length = (int) ((Math.ceil(toEncrypt.length / 16f)) * 16);
202 final byte[] toEncryptSizeAdjusted = Arrays.copyOf(toEncrypt, length);
203 //System.err.println("(" + toEncryptSizeAdjusted.length + ")" + "Before Encryption Data: "
204 // + Arrays.toString(toEncryptSizeAdjusted));
205 final byte[] result = cipher.doFinal(toEncryptSizeAdjusted);
206 //System.err.println("(" + result.length + ")" + "Encrypted Data: " + Arrays.toString(result));
207 return result;
208 } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
209 | IllegalBlockSizeException | BadPaddingException e) {
210 e.printStackTrace();
211 return null;
212 }
213 }
214
215 public static byte[] DecryptSymmetric(final byte[] toDecrypt, final SecretKey key) {
216 try {
217 final Cipher cipher = Cipher.getInstance(SymmetricAlgorithm + SymmetricAlgorithmParameters);
218 cipher.init(Cipher.DECRYPT_MODE, key);
219 final byte[] decryptedBytes = cipher.doFinal(toDecrypt);
220 int indexOfZero = decryptedBytes.length - 1;
221 for (int i = decryptedBytes.length - 1; i >= 0; i--) {
222 if (decryptedBytes[i] != (byte) 0) {
223 indexOfZero = i + 1;
224 break;
225 }
226 }
227 return Arrays.copyOf(decryptedBytes, indexOfZero);
228 } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
229 | IllegalBlockSizeException | BadPaddingException e) {
230 e.printStackTrace();
231 return null;
232 }
233 }
234
235 public static void AuthAddSecretKey(String name, String data) {
236 Frame secretsFrame = FrameIO.LoadFrame(UserSettings.UserName.get() + AuthenticatorBrowser.SECRETS_FRAME);
237 secretsFrame.addText(500, 500, name, null).addToData(data);
238 }
239
240 private static Text AuthSplitSecretUsage() {
241 String nl = System.getProperty("line.separator");
242 String tab = " ";
243 StringBuilder message = new StringBuilder("Usage: " + nl);
244 message.append(tab + "With Text Item attached to cursor: " + nl);
245 message.append(tab + tab + "Content matches pattern \"<SecretName> <Amount of Coperation Required> <Individual Name 1> <Individual Name 2> ... <Individual Name N>\"" + nl);
246 message.append(tab + tab + "Context Example: \"SecretName 3 Sandra John Billy Sally Sam Tim\"" + nl);
247 message.append(tab + tab + "Data contains key data" + nl);
248 message.append(tab + "Middle click on this action." + nl);
249 message.append(tab + "Resulting Text Item will contain shares in data.");
250 return generateUsageText(message);
251 }
252
253 private static Text AuthGenerateSecretUsage() {
254 String nl = System.getProperty("line.separator");
255 String tab = " ";
256 StringBuilder message = new StringBuilder("Usage: " + nl);
257 message.append(tab + "With Text Item attached to cursor: " + nl);
258 message.append(tab + tab + "Content should be one word with no spaces." + nl);
259 message.append(tab + tab + "Content represents the desired label name for the generated secret." + nl);
260 message.append(tab + tab + "This action will overwrite any existing data." + nl);
261 message.append(tab + "Middle click on this action." + nl);
262 message.append(tab + "Text Item will now contain a full key in its data." + nl);
263 message.append(tab + "Resulting Text Item is now a Secret and can be placed on secrets frame.");
264 return generateUsageText(message);
265 }
266
267 private static Text generateUsageText(StringBuilder message) {
268 Text ret = new Text(message.toString());
269 ret.setPosition(DisplayController.getMousePosition());
270 ret.setSize(14);
271 ret.setBackgroundColor(Colour.LIGHT_GRAY);
272 ret.setBorderColor(Colour.DARK_GRAY);
273 return ret;
274 }
275}
Note: See TracBrowser for help on using the repository browser.