[1399] | 1 | package org.expeditee.encryption.io;
|
---|
[1200] | 2 |
|
---|
| 3 | import java.io.IOException;
|
---|
[1408] | 4 | import java.lang.reflect.InvocationTargetException;
|
---|
| 5 | import java.lang.reflect.Method;
|
---|
[1200] | 6 | import java.security.InvalidKeyException;
|
---|
| 7 | import java.security.NoSuchAlgorithmException;
|
---|
| 8 | import java.util.Arrays;
|
---|
| 9 | import java.util.Base64;
|
---|
[1408] | 10 | import java.util.LinkedHashMap;
|
---|
[1243] | 11 | import java.util.List;
|
---|
[1413] | 12 | import java.util.function.BinaryOperator;
|
---|
| 13 | import java.util.function.Function;
|
---|
| 14 | import java.util.stream.Collectors;
|
---|
[1200] | 15 |
|
---|
| 16 | import javax.crypto.BadPaddingException;
|
---|
| 17 | import javax.crypto.Cipher;
|
---|
| 18 | import javax.crypto.IllegalBlockSizeException;
|
---|
| 19 | import javax.crypto.NoSuchPaddingException;
|
---|
| 20 | import javax.crypto.SecretKey;
|
---|
| 21 | import javax.crypto.spec.SecretKeySpec;
|
---|
| 22 |
|
---|
[1389] | 23 | import org.expeditee.encryption.CryptographyConstants;
|
---|
[1408] | 24 | import org.expeditee.encryption.items.surrogates.EncryptionDetail;
|
---|
[1415] | 25 | import org.expeditee.encryption.items.surrogates.EncryptionDetail.Type;
|
---|
[1431] | 26 | import org.expeditee.encryption.items.surrogates.Label.LabelResult;
|
---|
[1409] | 27 | import org.expeditee.encryption.items.surrogates.Label;
|
---|
[1431] | 28 | import org.expeditee.encryption.items.surrogates.Label.LabelInfo;
|
---|
[1323] | 29 | import org.expeditee.gui.Frame;
|
---|
[1415] | 30 | import org.expeditee.gui.Frame.BodyType;
|
---|
[1323] | 31 | import org.expeditee.gui.MessageBay;
|
---|
[1408] | 32 | import org.expeditee.io.Conversion;
|
---|
[1200] | 33 | import org.expeditee.io.ExpWriter;
|
---|
[1400] | 34 | import org.expeditee.items.Item;
|
---|
[1408] | 35 | import org.expeditee.items.Line;
|
---|
[1202] | 36 | import org.expeditee.items.Text;
|
---|
[1243] | 37 | import org.expeditee.settings.identity.secrets.KeyList;
|
---|
[1408] | 38 | import org.expeditee.stats.SessionStats;
|
---|
[1200] | 39 |
|
---|
[1227] | 40 | public class EncryptedExpWriter extends ExpWriter implements CryptographyConstants {
|
---|
| 41 | private SecretKey key;
|
---|
[1408] | 42 |
|
---|
| 43 | private final String label;
|
---|
| 44 |
|
---|
| 45 | private static final String ENCRYPTED_EXP_FLAG = "EncryptedExp";
|
---|
[1200] | 46 | private static final String nl = "\n";
|
---|
[1408] | 47 | private static final String labelProfile = "Profile";
|
---|
| 48 | private static final String labelNone = "None";
|
---|
[1414] | 49 | protected static final char TERMINATOR = 'Z';
|
---|
| 50 | protected static final String TERMINATOR_WITH_CONTINUATION = TERMINATOR + "...";
|
---|
[1408] | 51 |
|
---|
| 52 | public EncryptedExpWriter(String encryptionLabel) {
|
---|
| 53 | label = encryptionLabel;
|
---|
[1506] | 54 | if (label.equals(getLabelNone())) {
|
---|
[1408] | 55 | return;
|
---|
| 56 | }
|
---|
| 57 |
|
---|
| 58 | if (label.equals(labelProfile)) {
|
---|
[1227] | 59 | // obtain personal key
|
---|
| 60 | Text text = KeyList.PersonalKey.get();
|
---|
[1243] | 61 | List<String> data = text.getData();
|
---|
| 62 | if (data != null && !data.isEmpty()) {
|
---|
| 63 | byte[] keyBytes = Base64.getDecoder().decode(data.get(0));
|
---|
| 64 | key = new SecretKeySpec(keyBytes, SymmetricAlgorithm);
|
---|
| 65 | }
|
---|
[1227] | 66 | } else {
|
---|
[1431] | 67 | LabelInfo res = Label.getLabel(label);
|
---|
| 68 | if (res.is(LabelResult.SuccessResolveLabelToKey)) {
|
---|
[1401] | 69 | byte[] keyBytes = res.key;
|
---|
| 70 | key = new SecretKeySpec(keyBytes, SymmetricAlgorithm);
|
---|
[1431] | 71 | } else if (res.is(LabelResult.ErrorUnableToFindLabel)) {
|
---|
[1401] | 72 | MessageBay.errorMessage(res.toString() + encryptionLabel);
|
---|
[1408] | 73 | key = null;
|
---|
[1401] | 74 | } else {
|
---|
| 75 | MessageBay.errorMessage(res.toString());
|
---|
| 76 | }
|
---|
[1227] | 77 | }
|
---|
[1200] | 78 | }
|
---|
[1408] | 79 |
|
---|
[1200] | 80 | @Override
|
---|
[1413] | 81 | protected void preOutputFrame() {
|
---|
| 82 | try {
|
---|
| 83 | String line = ENCRYPTED_EXP_FLAG + label + nl;
|
---|
| 84 | _writer.write(line);
|
---|
| 85 | _stringWriter.append(line);
|
---|
| 86 | } catch (final IOException e) {
|
---|
| 87 | e.printStackTrace();
|
---|
| 88 | }
|
---|
| 89 | }
|
---|
| 90 |
|
---|
| 91 | @Override
|
---|
[1408] | 92 | public void outputFrame(Frame frame) throws IOException {
|
---|
| 93 | if (_writer == null) { return; }
|
---|
| 94 |
|
---|
| 95 | preOutputFrame();
|
---|
| 96 | writeHeader(frame);
|
---|
| 97 |
|
---|
| 98 | // write item
|
---|
[1415] | 99 | writeItemData(frame, true);
|
---|
[1408] | 100 | writeTerminator();
|
---|
| 101 | // write lines and constraints
|
---|
| 102 | writeLineData();
|
---|
| 103 | writeTerminator();
|
---|
| 104 | writeConstraintData();
|
---|
| 105 |
|
---|
[1415] | 106 | // write surrogate items
|
---|
| 107 | if (frame.hasSurrogates()) {
|
---|
| 108 | writeSurrogateTerminator();
|
---|
| 109 | writeItemData(frame, false);
|
---|
| 110 | writeTerminator();
|
---|
| 111 | } else {
|
---|
| 112 | writeTerminator();
|
---|
| 113 | }
|
---|
| 114 |
|
---|
[1408] | 115 | writeLine(SessionStats.getFrameEventList(frame));
|
---|
| 116 | }
|
---|
| 117 |
|
---|
| 118 | @Override
|
---|
[1200] | 119 | protected void writeLine(String line) throws IOException {
|
---|
| 120 | // do not write empty lines
|
---|
| 121 | if (line == null) { return; }
|
---|
| 122 |
|
---|
[1408] | 123 | String toWrite;
|
---|
[1506] | 124 | if (key == null && label.equals(getLabelNone())) {
|
---|
[1408] | 125 | toWrite = line + nl;
|
---|
| 126 | } else {
|
---|
| 127 | // prepare line to write out
|
---|
| 128 | byte[] encrypted = EncryptSymmetric(line.getBytes(), key);
|
---|
| 129 | toWrite = Base64.getEncoder().encodeToString(encrypted) + nl;
|
---|
| 130 | }
|
---|
| 131 |
|
---|
[1200] | 132 | // output
|
---|
| 133 | _writer.write(toWrite);
|
---|
| 134 | _stringWriter.append(toWrite);
|
---|
| 135 | }
|
---|
| 136 |
|
---|
[1408] | 137 | protected void writeClass(Item toWrite) throws IOException {
|
---|
[1418] | 138 | LinkedHashMap<Character,Method> itemTags = new LinkedHashMap<Character, Method>(getItemCharTags());
|
---|
| 139 | LinkedHashMap<String,Method> itemTagsExt = new LinkedHashMap<String, Method>(getItemStrTags());
|
---|
[1408] | 140 |
|
---|
| 141 | writeTag(toWrite, new Object[] {}, itemTags, 'S');
|
---|
| 142 | writeTag(toWrite, new Object[] {}, itemTagsExt, "_el");
|
---|
| 143 |
|
---|
[1413] | 144 | if (toWrite.isSurrogate()) {
|
---|
[1414] | 145 | writeLine("SurrogateFor " + toWrite.getPrimary().getID());
|
---|
[1413] | 146 | }
|
---|
| 147 |
|
---|
[1408] | 148 | itemTags.remove('S');
|
---|
| 149 | itemTagsExt.remove("_el");
|
---|
[1413] | 150 |
|
---|
[1408] | 151 | writeTags(toWrite, new Object[] {}, itemTags);
|
---|
| 152 | writeTags(toWrite, new Object[] {}, itemTagsExt);
|
---|
| 153 | }
|
---|
| 154 |
|
---|
| 155 | @Override
|
---|
| 156 | protected <T> void writeTag(Item toWrite, Object[] param, LinkedHashMap<T, Method> tags, T tag) {
|
---|
[1413] | 157 | if (toWrite.isSurrogate() && toWrite.isTagInherited(tag + "")) {
|
---|
| 158 | return;
|
---|
| 159 | }
|
---|
[1408] | 160 | EncryptionDetail encryptionDetail = toWrite.getEncryptionDetailForTag(tag + "");
|
---|
[1415] | 161 | Type encryptionDetailType = encryptionDetail.getEncryptionDetailType();
|
---|
[1413] | 162 |
|
---|
[1415] | 163 | switch(encryptionDetailType) {
|
---|
[1408] | 164 | case UnencryptedOnSave:
|
---|
[1413] | 165 | writeTagUnencryptedOnSave(toWrite, param, tags, tag);
|
---|
[1408] | 166 | break;
|
---|
[1413] | 167 | case InheritanceCheckOnSave:
|
---|
| 168 | writeTagInheritanceCheckOnSave(toWrite, tags, tag);
|
---|
| 169 | break;
|
---|
[1408] | 170 | case ReencryptOnSave:
|
---|
[1413] | 171 | writeTagReencryptOnSave(toWrite, tags, tag);
|
---|
[1408] | 172 | break;
|
---|
| 173 | case UseUndecipheredValueOnSave:
|
---|
[1413] | 174 | writeTagUseUndecipheredValueOnSave(toWrite, tags, tag);
|
---|
[1408] | 175 | break;
|
---|
[1323] | 176 | }
|
---|
[1227] | 177 | }
|
---|
| 178 |
|
---|
[1415] | 179 | private void writeItemData(Frame frame, boolean primaryItems) throws IOException {
|
---|
[1408] | 180 | // write each item in the frame
|
---|
[1415] | 181 | BodyType bodyType = primaryItems ? BodyType.PrimaryBody : BodyType.SurrogateBody;
|
---|
| 182 | for (Item i : frame.getItemsToSave(bodyType)) {
|
---|
[1408] | 183 | assert (!(i instanceof Line));
|
---|
| 184 | writeItem(i);
|
---|
| 185 | }
|
---|
| 186 |
|
---|
[1413] | 187 | for (Item i: frame.getBodyItemsWithInsufficientPermissions()) {
|
---|
[1408] | 188 | assert (!(i instanceof Line));
|
---|
| 189 | writeItem(i);
|
---|
| 190 | }
|
---|
| 191 | }
|
---|
[1413] | 192 |
|
---|
| 193 | private <T> void writeTagInheritanceCheckOnSave(Item toWrite, LinkedHashMap<T, Method> tags, T tag) {
|
---|
| 194 | List<Item> surrogateItems = toWrite.getSurrogates().stream().collect(Collectors.toList());
|
---|
| 195 | Function<Item, Boolean> isTagInherited = surrogate -> surrogate.isTagInherited(tag + "");
|
---|
| 196 | BinaryOperator<Boolean> trueExists = (a, b) -> a || b;
|
---|
[1430] | 197 | boolean surrogatesInherit = surrogateItems.stream().map(isTagInherited).collect(Collectors.reducing(trueExists)).orElseGet(() -> false);
|
---|
[1431] | 198 | boolean userHasKey = Label.getLabel(toWrite.getEncryptionLabel()).is(LabelResult.SuccessResolveLabelToKey);
|
---|
[1415] | 199 |
|
---|
[1430] | 200 | // If we have no surrogates that inherit this property from us, and we have the label required to encrypt it, then we should encrypt it.
|
---|
[1415] | 201 | if (!surrogatesInherit && userHasKey) {
|
---|
| 202 | EncryptionDetail reencryptOnSave = new EncryptionDetail(EncryptionDetail.Type.ReencryptOnSave);
|
---|
| 203 | toWrite.setEncryptionDetailForTag(tag + "", reencryptOnSave);
|
---|
| 204 | writeTagReencryptOnSave(toWrite, tags, tag);
|
---|
| 205 | } else {
|
---|
[1416] | 206 | // If one or more surrogates still inherit from us, or we do not have the label, then we write it out unencrypted.
|
---|
[1415] | 207 | EncryptionDetail unencryptedOnSave = new EncryptionDetail(EncryptionDetail.Type.UnencryptedOnSave);
|
---|
| 208 | toWrite.setEncryptionDetailForTag(tag + "", unencryptedOnSave);
|
---|
[1413] | 209 | writeTagUnencryptedOnSave(toWrite, new Object[] {}, tags, tag);
|
---|
[1408] | 210 | }
|
---|
[1413] | 211 | }
|
---|
| 212 |
|
---|
| 213 | private <T> void writeTagReencryptOnSave(Item toWrite, LinkedHashMap<T, Method> tags, T tag) {
|
---|
| 214 | Method toRun = tags.get(tag);
|
---|
| 215 | Class<?> declarer = toRun.getDeclaringClass();
|
---|
[1431] | 216 | LabelInfo res = Label.getLabel(toWrite.getEncryptionLabel());
|
---|
| 217 | if (declarer.isAssignableFrom(toWrite.getClass()) && res.is(LabelResult.SuccessResolveLabelToKey)) {
|
---|
[1413] | 218 | try {
|
---|
| 219 | Object o = toRun.invoke(toWrite, new Object[] {});
|
---|
| 220 | o = Conversion.ConvertToExpeditee(toRun, o);
|
---|
| 221 | if (o == null) {
|
---|
| 222 | return;
|
---|
| 223 | }
|
---|
| 224 | if (o instanceof List) {
|
---|
| 225 | for (Object line: (List<?>) o) {
|
---|
| 226 | writeLineEnc(tag, line, res.key);
|
---|
| 227 | }
|
---|
| 228 | } else {
|
---|
| 229 | writeLineEnc(tag, o, res.key);
|
---|
| 230 | }
|
---|
| 231 | } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
---|
| 232 | e.printStackTrace();
|
---|
| 233 | } catch (IOException e) {
|
---|
| 234 | e.printStackTrace();
|
---|
[1408] | 235 | }
|
---|
| 236 | }
|
---|
| 237 | }
|
---|
| 238 |
|
---|
[1413] | 239 | private <T> void writeTagUseUndecipheredValueOnSave(Item toWrite, LinkedHashMap<T, Method> tags, T tag) {
|
---|
| 240 | EncryptionDetail encryptionDetail = toWrite.getEncryptionDetailForTag(tag + "");
|
---|
| 241 | try {
|
---|
| 242 | writeLine(tag + "E", encryptionDetail.getUndecipheredValue());
|
---|
| 243 | } catch (IOException e) {
|
---|
| 244 | e.printStackTrace();
|
---|
| 245 | }
|
---|
| 246 | }
|
---|
| 247 |
|
---|
| 248 | private <T> void writeTagUnencryptedOnSave(Item toWrite, Object[] param, LinkedHashMap<T, Method> tags, T tag) {
|
---|
| 249 | super.writeTag(toWrite, param, tags, tag);
|
---|
| 250 | }
|
---|
| 251 |
|
---|
[1408] | 252 | private void writeSurrogateTerminator() throws IOException {
|
---|
[1414] | 253 | writeLine(TERMINATOR_WITH_CONTINUATION + nl);
|
---|
[1408] | 254 | }
|
---|
| 255 |
|
---|
[1413] | 256 | private <T> void writeLineEnc(T tag, Object line, byte[] keyBytes) throws IOException {
|
---|
| 257 | SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm);
|
---|
| 258 | byte[] lineEncryptedBytes = EncryptSymmetric(line.toString().getBytes(), key);
|
---|
| 259 | line = Base64.getEncoder().encodeToString(lineEncryptedBytes);
|
---|
| 260 | writeLine(tag + "E", line.toString());
|
---|
| 261 | }
|
---|
| 262 |
|
---|
[1227] | 263 | private static byte[] EncryptSymmetric(byte[] toEncrypt, SecretKey key) {
|
---|
[1200] | 264 | try {
|
---|
[1227] | 265 | Cipher cipher = Cipher.getInstance(SymmetricAlgorithm + SymmetricAlgorithmParameters);
|
---|
[1200] | 266 | cipher.init(Cipher.ENCRYPT_MODE, key);
|
---|
| 267 | //could use modulus
|
---|
[1227] | 268 | int length = (int) ((Math.ceil(toEncrypt.length / 16f)) * 16);
|
---|
| 269 | byte[] toEncryptSizeAdjusted = Arrays.copyOf(toEncrypt, length);
|
---|
| 270 | byte[] result = cipher.doFinal(toEncryptSizeAdjusted);
|
---|
[1200] | 271 | return result;
|
---|
| 272 | } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
|
---|
| 273 | | IllegalBlockSizeException | BadPaddingException e) {
|
---|
| 274 | e.printStackTrace();
|
---|
| 275 | return null;
|
---|
| 276 | }
|
---|
[1413] | 277 | }
|
---|
[1506] | 278 |
|
---|
| 279 | /**
|
---|
| 280 | * @return the labelnone
|
---|
| 281 | */
|
---|
| 282 | public static String getLabelNone() {
|
---|
| 283 | return labelNone;
|
---|
| 284 | }
|
---|
[1200] | 285 | }
|
---|