Ignore:
Timestamp:
06/25/19 13:57:37 (5 years ago)
Author:
bln4
Message:

Changed surrogates to work the way discussed with David. EncryptedExpReader/Writer updated to work with this.

Location:
trunk/src/org/expeditee/encryption
Files:
1 deleted
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/expeditee/encryption/io/EncryptedExpReader.java

    r1409 r1413  
    2626import org.expeditee.encryption.items.surrogates.EncryptionDetail;
    2727import org.expeditee.encryption.items.surrogates.Label;
    28 import org.expeditee.encryption.items.surrogates.Surrogate;
    2928import org.expeditee.encryption.items.surrogates.Label.LabelResult;
    3029import org.expeditee.gui.Frame;
     
    3736
    3837public class EncryptedExpReader extends ExpReader implements CryptographyConstants {
     38       
    3939        private static final String ENCRYPTED_EXP_FLAG = "EncryptedExp";
    4040        private static final String labelProfile = "Profile";
     
    4343        private boolean accessDenied = false;
    4444
    45         public EncryptedExpReader(String frameName) {
    46                 super(frameName);
    47         }
    48 
    4945        public static boolean isEncryptedExpediteeFile(final String path) throws IOException {
    5046                final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
     
    5248                in.close();
    5349                return firstLine.startsWith(ENCRYPTED_EXP_FLAG);
     50        }
     51       
     52        public EncryptedExpReader(String frameName) {
     53                super(frameName);
    5454        }
    5555       
     
    132132                                continue;
    133133                        }
     134                       
    134135                        String tag = getTagEnc(next);
    135                         if (tag.equals("S")) {
     136                        if (next.startsWith("S ")) {
    136137                                currentItem = newItem(next);
    137138                                _linePoints.put(currentItem.getID(), currentItem);
    138139                                newFrame.addItem(currentItem);
    139140                                currentItem.setEncryptionDetailForTag(tag + "", EncryptionDetail.UnencryptedOnSave);
     141                        } else if (next.startsWith("SurrogateFor")) {
     142                                int parentID = Integer.parseInt(next.split(" ")[1]);
     143                                newFrame.getItemWithID(parentID).addToSurrogates(currentItem);
    140144                        } else if (currentItem != null && actionShouldBeDelayed(tag.charAt(0))) {
    141145                                delayedActions.add(new DelayedAction(currentItem, next));
     
    147151                }
    148152               
    149                 if (next.equals("Z...")) {
    150                         next = readTheSurrogateItems(newFrame, delayedActions);
     153                if (next.equals(EncryptedExpWriter.SURROGATE_TERMINATOR)) {
     154                        next = readTheItems(newFrame, delayedActions);
    151155                }
    152156               
     
    159163                String tag = getTagEnc(line);
    160164                String value = getValue(line);
     165               
     166                if (item.isSurrogate() && item.isTagInherited(tag)) {
     167                        return;
     168                }
    161169               
    162170                // Attempt to decrypt the line if necessary.
     
    192200                }
    193201        }
    194                
    195         private String readTheSurrogateItems(Frame newFrame, List<DelayedAction> delayedActions) throws IOException {
    196                 String next = null;
    197                 Item currentItem = null;
    198                
    199                 Predicate<String> endOfSection = s -> s.equals("Z") || s.equals("Z...");
    200                 while (_reader.ready() && !endOfSection.test(next = _reader.readLine())) {
    201                         if (!isValidLine(next)) {
    202                                 continue;
    203                         }
    204                        
    205                         String tag = getTagEnc(next);
    206                         if (tag.equals("S") && !next.startsWith("SurrogateFor")) {
    207                                 currentItem = newItem(next);
    208                                 currentItem.setEncryptionDetailForTag(tag + "", EncryptionDetail.UnencryptedOnSave);
    209                         } else if (next.startsWith("SurrogateFor")) {
    210                                 String id = next.split(" ")[1];
    211                                 Item classic = newFrame.getItemWithID(Integer.parseInt(id));
    212                                 if (id == null) {
    213                                         System.err.println("WARNING: Attempted to create surrogate for classic ID " +
    214                                                         id + " but was no item on frame " + newFrame.getName() + " exists.");
    215                                         continue;
    216                                 }
    217                                 currentItem.setAsSurrogateFor(classic);
    218                                 classic.addToSurrogates(new Surrogate(currentItem));
    219                         } else if (currentItem != null && actionShouldBeDelayed(getTag(next))) {
    220                                 delayedActions.add(new DelayedAction(currentItem, next));
    221                         } else if (currentItem != null) {
    222                                 processBodyLine(currentItem, next);
    223                         } else {
    224                                 System.err.println("Error while reading in frame (ExpReader): Found body line but no current item to apply it to.");
    225                         }
    226                 }
    227 
    228                 return next;
    229         }
    230        
    231         protected static String getTagEnc(String line) {
    232                 char charAtZero = line.charAt(0);
    233                 if (charAtZero == '_') {
    234                         return line.split(" ")[0];
    235                 } else {
    236                         return charAtZero + "";
    237                 }
    238         }
    239202       
    240203        protected static String getValue(String line) {
     
    247210        }
    248211       
    249         protected static boolean isEncryptedLine(String line) {
     212        private static String getTagEnc(String line) {
     213                char charAtZero = line.charAt(0);
     214                if (charAtZero == '_') {
     215                        return line.split(" ")[0];
     216                } else {
     217                        return charAtZero + "";
     218                }
     219        }
     220               
     221        private static boolean isEncryptedLine(String line) {
    250222                if (line.startsWith("S") || line.startsWith("_el")) {
    251223                        return false;
     
    278250                }
    279251        }
    280        
     252
    281253        private class EncryptedLineReader extends BufferedReader {
    282254                private boolean noneMode = false;
  • trunk/src/org/expeditee/encryption/io/EncryptedExpWriter.java

    r1410 r1413  
    66import java.security.InvalidKeyException;
    77import java.security.NoSuchAlgorithmException;
    8 import java.util.ArrayList;
    98import java.util.Arrays;
    109import java.util.Base64;
    1110import java.util.LinkedHashMap;
    1211import java.util.List;
    13 import java.util.Set;
    14 import java.util.function.Consumer;
     12import java.util.function.BinaryOperator;
     13import java.util.function.Function;
     14import java.util.stream.Collectors;
    1515
    1616import javax.crypto.BadPaddingException;
     
    2424import org.expeditee.encryption.items.surrogates.EncryptionDetail;
    2525import org.expeditee.encryption.items.surrogates.Label;
    26 import org.expeditee.encryption.items.surrogates.Surrogate;
    2726import org.expeditee.encryption.items.surrogates.Label.LabelResult;
    2827import org.expeditee.gui.Frame;
     
    7675       
    7776        @Override
    78         public void outputFrame(Frame frame) throws IOException {
    79                 if (_writer == null) { return; }
    80                
    81                 preOutputFrame();
    82                 writeHeader(frame);
    83                
    84                 // write item
    85                 writeItemData(frame);
    86                 writeTerminator();
    87                
    88                 // write lines and constraints
    89                 writeLineData();
    90                 writeTerminator();
    91                 writeConstraintData();
    92                 writeTerminator();
    93                
    94                 writeLine(SessionStats.getFrameEventList(frame));
    95         }
    96        
    97         @Override
    9877        protected void preOutputFrame() {
    9978                try {
     
    10786       
    10887        @Override
     88        public void outputFrame(Frame frame) throws IOException {
     89                if (_writer == null) { return; }
     90               
     91                preOutputFrame();
     92                writeHeader(frame);
     93               
     94                // write item
     95                writeItemData(frame);
     96                writeTerminator();
     97               
     98                // write lines and constraints
     99                writeLineData();
     100                writeTerminator();
     101                writeConstraintData();
     102                writeTerminator();
     103               
     104                writeLine(SessionStats.getFrameEventList(frame));
     105        }
     106       
     107        @Override
    109108        protected void writeLine(String line) throws IOException {
    110109                // do not write empty lines
     
    125124        }
    126125       
    127         @Override
    128         protected void writeLineData() throws IOException {
    129                 super.writeLineData();
    130                
    131                 writeSurrogateLineData();
    132         }
    133        
    134         @Override
    135126        protected void writeClass(Item toWrite) throws IOException {
    136127                LinkedHashMap<Character,Method> itemTags = new LinkedHashMap<Character, Method>(getItemTags());
    137128                LinkedHashMap<String,Method> itemTagsExt = new LinkedHashMap<String, Method>(getItemTagsExt());
    138129               
    139                 // Perform final update on surrogates to ensure inheritance works.
    140                 Set<Surrogate> surrogates = toWrite.getSurrogates();
    141                 for (Surrogate s: surrogates) {
    142                         s.toString();
    143                 }
    144                
    145130                writeTag(toWrite, new Object[] {}, itemTags, 'S');
    146131                writeTag(toWrite, new Object[] {}, itemTagsExt, "_el");
    147132               
     133                if (toWrite.isSurrogate()) {
     134                        writeLine("SurrogateFor " + toWrite.getClassic().getID());
     135                }
     136               
    148137                itemTags.remove('S');
    149138                itemTagsExt.remove("_el");
    150                
     139                               
    151140                writeTags(toWrite, new Object[] {}, itemTags);
    152141                writeTags(toWrite, new Object[] {}, itemTagsExt);
     
    155144        @Override
    156145        protected <T> void writeTag(Item toWrite, Object[] param, LinkedHashMap<T, Method> tags, T tag) {
     146                if (toWrite.isSurrogate() && toWrite.isTagInherited(tag + "")) {
     147                        return;
     148                }
    157149                EncryptionDetail encryptionDetail = toWrite.getEncryptionDetailForTag(tag + "");
    158                 switch (encryptionDetail) {
     150                               
     151                switch(encryptionDetail) {
    159152                case UnencryptedOnSave:
    160                         super.writeTag(toWrite, param, tags, tag);
     153                        writeTagUnencryptedOnSave(toWrite, param, tags, tag);
     154                        break;
     155                case InheritanceCheckOnSave:
     156                        writeTagInheritanceCheckOnSave(toWrite, tags, tag);
    161157                        break;
    162158                case ReencryptOnSave:
    163                         Method toRun = tags.get(tag);
    164                         Class<?> declarer = toRun.getDeclaringClass();
    165                         LabelResult res = Label.resolveKey(toWrite.getEncryptionLabel());
    166                         if (declarer.isAssignableFrom(toWrite.getClass()) && res == LabelResult.SuccessResolveLabelToKey) {
    167                                 SecretKey key = new SecretKeySpec(res.key, SymmetricAlgorithm);
    168                                 try {
    169                                         Object o = toRun.invoke(toWrite, new Object[] {});
    170                                         o = Conversion.ConvertToExpeditee(toRun, o);
    171                                         if (o != null) {
    172                                                 if (o instanceof List) {
    173                                                         for (Object line: (List<?>)o) {
    174                                                                 byte[] encryptedBytes = EncryptSymmetric(line.toString().getBytes(), key);
    175                                                                 writeLine(tag + "E", Base64.getEncoder().encodeToString(encryptedBytes));
    176                                                         }
    177                                                 } else {
    178                                                         byte[] encryptedBytes = EncryptSymmetric(o.toString().getBytes(), key);
    179                                                         writeLine(tag + "E", Base64.getEncoder().encodeToString(encryptedBytes));
    180                                                 }
    181                                         }
    182                                 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    183                                         e.printStackTrace();
    184                                 } catch (IOException e) {
    185                                         e.printStackTrace();
    186                                 }
    187                         }
     159                        writeTagReencryptOnSave(toWrite, tags, tag);
    188160                        break;
    189161                case UseUndecipheredValueOnSave:
    190                         try {
    191                                 writeLine(tag + "E", encryptionDetail.getUndecipheredValue());
    192                         } catch (IOException e) {
    193                                 e.printStackTrace();
    194                         }
     162                        writeTagUseUndecipheredValueOnSave(toWrite, tags, tag);
    195163                        break;
    196164                }
     
    204172                }
    205173               
    206                 for (final Item i: frame.getBodyItemsWithInsufficientPermissions()) {
     174                for (Item i: frame.getBodyItemsWithInsufficientPermissions()) {
    207175                        assert (!(i instanceof Line));
    208176                        writeItem(i);
    209177                }
    210178               
    211                 writeSurrogateItemsData(frame);
    212         }
    213        
    214         private void writeSurrogateItemsData(Frame frame) throws IOException {
    215                 List<Surrogate> surrogates = new ArrayList<Surrogate>();
    216                
    217                 Consumer<? super Item> store = item -> surrogates.addAll(item.getSurrogates());
    218                 frame.getItemsToSave().forEach(store);
    219                 frame.getBodyItemsWithInsufficientPermissions().forEach(store);
    220                
     179                List<Item> surrogates = frame.getSurrogateItemsToSave();
    221180                if (!surrogates.isEmpty()) {
    222                         // If there is some surrogates, write the surrogate
    223                         // terminator, then write out the surrogates.
    224181                        writeSurrogateTerminator();
    225                        
    226                         for (Surrogate surrogate: surrogates) {
    227                                 String output = surrogate.toString();
    228                                 writeLine(output);
    229                         }
    230                 }
    231         }
    232 
    233         private void writeSurrogateLineData() throws IOException {
    234                 List<Surrogate> surrogateLines = new ArrayList<Surrogate>();
    235                
    236                 for(Item lineEnd: _lineEnds) {
    237                         List<Line> lines = lineEnd.getLines();
    238                         for (Line line: lines) {
    239                                 surrogateLines.addAll(line.getSurrogates());
    240                         }
    241                 }
    242                
    243                 if (!surrogateLines.isEmpty()) {
    244                         // If there is some surrogates, write the surrogate
    245                         // terminator, then write out the surrogates.
    246                         writeSurrogateTerminator();
    247                        
    248                         for (Surrogate surrogate: surrogateLines) {
    249                                 String output = surrogate.toString();
    250                                 writeLine(output);
    251                         }
    252                 }
     182                        for (Item i: surrogates) {
     183                                assert (!(i instanceof Line));
     184                                writeItem(i);
     185                        }
     186                }
     187        }
     188       
     189        private <T> void writeTagInheritanceCheckOnSave(Item toWrite, LinkedHashMap<T, Method> tags, T tag) {   
     190                List<Item> surrogateItems = toWrite.getSurrogates().stream().collect(Collectors.toList());
     191                Function<Item, Boolean> isTagInherited = surrogate -> surrogate.isTagInherited(tag + "");
     192                BinaryOperator<Boolean> trueExists = (a, b) -> a || b;
     193                boolean surrogatesInherit = surrogateItems.stream().map(isTagInherited).collect(Collectors.reducing(trueExists)).get();
     194                if (surrogatesInherit &&
     195                                Label.resolveKey(toWrite.getEncryptionLabel()) == LabelResult.SuccessResolveLabelToKey) {
     196                        toWrite.setEncryptionDetailForTag(tag + "", EncryptionDetail.UnencryptedOnSave);
     197                        writeTagUnencryptedOnSave(toWrite, new Object[] {}, tags, tag);
     198                } else {
     199                        toWrite.setEncryptionDetailForTag(tag + "", EncryptionDetail.ReencryptOnSave);
     200                        writeTagReencryptOnSave(toWrite, tags, tag);
     201                }
     202        }
     203       
     204        private <T> void writeTagReencryptOnSave(Item toWrite, LinkedHashMap<T, Method> tags, T tag) {
     205                Method toRun = tags.get(tag);
     206                Class<?> declarer = toRun.getDeclaringClass();
     207                LabelResult res = Label.resolveKey(toWrite.getEncryptionLabel());
     208                if (declarer.isAssignableFrom(toWrite.getClass()) && res == LabelResult.SuccessResolveLabelToKey) {
     209                        try {
     210                                Object o = toRun.invoke(toWrite, new Object[] {});
     211                                o = Conversion.ConvertToExpeditee(toRun, o);
     212                                if (o == null) {
     213                                        return;
     214                                }
     215                                if (o instanceof List) {
     216                                        for (Object line: (List<?>) o) {
     217                                                writeLineEnc(tag, line, res.key);
     218                                        }
     219                                } else {
     220                                        writeLineEnc(tag, o, res.key);
     221                                }
     222                        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
     223                                e.printStackTrace();
     224                        } catch (IOException e) {
     225                                e.printStackTrace();
     226                        }
     227                }
     228        }
     229       
     230        private <T> void writeTagUseUndecipheredValueOnSave(Item toWrite, LinkedHashMap<T, Method> tags, T tag) {
     231                EncryptionDetail encryptionDetail = toWrite.getEncryptionDetailForTag(tag + "");
     232                try {
     233                        writeLine(tag + "E", encryptionDetail.getUndecipheredValue());
     234                } catch (IOException e) {
     235                        e.printStackTrace();
     236                }
     237        }
     238       
     239        private <T> void writeTagUnencryptedOnSave(Item toWrite, Object[] param, LinkedHashMap<T, Method> tags, T tag) {
     240                super.writeTag(toWrite, param, tags, tag);
    253241        }
    254242       
    255243        private void writeSurrogateTerminator() throws IOException {
    256244                writeLine(SURROGATE_TERMINATOR + nl);
     245        }
     246       
     247        private <T> void writeLineEnc(T tag, Object line, byte[] keyBytes) throws IOException {
     248                SecretKey key = new SecretKeySpec(keyBytes, SymmetricAlgorithm);
     249                byte[] lineEncryptedBytes = EncryptSymmetric(line.toString().getBytes(), key);
     250                line = Base64.getEncoder().encodeToString(lineEncryptedBytes);
     251                writeLine(tag + "E", line.toString());
    257252        }
    258253       
     
    271266                        return null;
    272267                }
    273         }       
     268        }
    274269}
  • trunk/src/org/expeditee/encryption/items/surrogates/EncryptionDetail.java

    r1408 r1413  
    22
    33public enum EncryptionDetail {
    4         UnencryptedOnSave, ReencryptOnSave, UseUndecipheredValueOnSave;
     4        // If the property needs to be unencrypted due to inheritance then do not try to encrypt it.
     5        UnencryptedOnSave,
     6       
     7        // If the property is not inherited by any surrogates then we can try to encrypt it. 
     8        // If we do not have key then default to UnencryptedOnSave.
     9        ReencryptOnSave,
     10       
     11        // If the property is no longer inherited by at least one surrogate then this value is present. 
     12        // If it turns out there is no longer any surrogates who inherit the value then this value can be replaced with ReencryptOnSave.
     13        // Otherwise, this value must be replaced with UnencryptedOnSave.
     14        InheritanceCheckOnSave,
     15       
     16        // If we could not decrypt the value on load then EncryptionDetail.getUndecipheredValue() can be used to get the value for saving.
     17        UseUndecipheredValueOnSave;
    518       
    619        private String undecipheredValue = null;
  • trunk/src/org/expeditee/encryption/items/surrogates/Label.java

    r1409 r1413  
    11package org.expeditee.encryption.items.surrogates;
    22
     3import java.util.ArrayList;
    34import java.util.Base64;
    45import java.util.Collection;
     6import java.util.List;
     7import java.util.Set;
     8import java.util.stream.Collectors;
    59
    610import org.expeditee.auth.AuthenticatorBrowser;
     11import org.expeditee.gui.DisplayController;
    712import org.expeditee.gui.Frame;
    813import org.expeditee.gui.FrameIO;
     14import org.expeditee.gui.MessageBay;
     15import org.expeditee.items.Item;
    916import org.expeditee.items.Text;
    1017import org.expeditee.settings.UserSettings;
     
    1219public class Label {
    1320       
     21        private static List<LabelResult> labelCache = new ArrayList<LabelResult>();
     22        private static List<String> forbiddenLabels = new ArrayList<String>();
     23       
    1424        public static LabelResult resolveKey(String label) {
     25               
     26                if (forbiddenLabels.contains(label)) {
     27                        return LabelResult.ErrorUnableToFindLabel;
     28                }
     29               
     30                LabelResult fromCache = getFromCache(label);
     31                if (fromCache != null) {
     32                        return fromCache;
     33                }
     34
     35               
    1536                String credentialsFrameName = UserSettings.ProfileName.get() +
    1637                                AuthenticatorBrowser.CREDENTIALS_FRAME;
     
    4465                                LabelResult res = LabelResult.SuccessResolveLabelToKey;
    4566                                res.key = Base64.getDecoder().decode(data);
     67                                res.name = label;
     68                                labelCache.add(res);
    4669                                return res;
    4770                        } catch (IllegalArgumentException e) {
     
    5073                }
    5174        }
     75       
     76        public static void progressSurrogateMode() {
     77                Collection<Item> allItems = DisplayController.getCurrentFrame().getAllItems();
     78                allItems.removeIf(item -> item.getEncryptionLabel() == null);
     79                MessageBay.displayMessage("Encryption labels found on items on current frame: ");
     80                Set<String> allLabels = allItems.stream().map(i -> i.getEncryptionLabel()).collect(Collectors.toSet());
     81                StringBuilder sb = new StringBuilder();
     82                for (String label: allLabels) {
     83                        sb.append(label + ",");
     84                }
     85                MessageBay.displayMessage(sb.deleteCharAt(sb.length() - 1).toString());
     86        }
     87       
     88        public static void resetSurrogateMode() {
     89                // TODO Auto-generated method stub
     90               
     91        }
     92       
     93        private static LabelResult getFromCache(String label) {
     94                List<LabelResult> cacheCanditates = labelCache.stream().filter(labelResult -> labelResult.name.equals(label)).collect(Collectors.toList());
     95                if (!cacheCanditates.isEmpty()) {
     96                        return cacheCanditates.get(0);
     97                } else {
     98                        return null;
     99                }
     100        }
     101       
     102//      private static List<List<String>> permutation(List<String> strings, List<List<String>> acc) {
     103//              for (int i = 0; i < strings.size(); i++) {
     104//                     
     105//              }
     106//      }
    52107       
    53108        public enum LabelResult {
     
    58113               
    59114                public byte[] key;
     115                public String name;
    60116               
    61117                @Override
Note: See TracChangeset for help on using the changeset viewer.