diff --git a/src/nodash/core/NoConfigBase.java b/src/nodash/core/NoConfigBase.java index cfc234f..c04d703 100644 --- a/src/nodash/core/NoConfigBase.java +++ b/src/nodash/core/NoConfigBase.java @@ -9,46 +9,46 @@ import javax.crypto.SecretKey; import nodash.exceptions.NoDashFatalException; public abstract class NoConfigBase implements NoConfigInterface { - protected boolean ready; - protected SecretKey secretKey; - protected boolean saveDatabase; - protected boolean saveByteSets; - - protected final void generateSecretKey() { - try { - KeyGenerator keyGenerator = KeyGenerator.getInstance(NoUtil.CIPHER_KEY_SPEC); - keyGenerator.init(NoUtil.AES_STRENGTH); - this.secretKey = keyGenerator.generateKey(); - } catch (NoSuchAlgorithmException e) { - throw new NoDashFatalException("Value for CIPHER_KEY_SPEC not valid.", e); - } - } + protected boolean ready; + protected SecretKey secretKey; + protected boolean saveDatabase; + protected boolean saveByteSets; - @Override - public void construct() { - this.generateSecretKey(); - this.ready = true; - } + protected final void generateSecretKey() { + try { + KeyGenerator keyGenerator = KeyGenerator.getInstance(NoUtil.CIPHER_KEY_SPEC); + keyGenerator.init(NoUtil.AES_STRENGTH); + this.secretKey = keyGenerator.generateKey(); + } catch (NoSuchAlgorithmException e) { + throw new NoDashFatalException("Value for CIPHER_KEY_SPEC not valid.", e); + } + } - @Override - public SecretKey getSecretKey() { - return this.secretKey; - } + @Override + public void construct() { + this.generateSecretKey(); + this.ready = true; + } - @Override - public boolean saveDatabase() { - return this.saveDatabase; - } + @Override + public SecretKey getSecretKey() { + return this.secretKey; + } - @Override - public boolean saveByteSets() { - return this.saveByteSets; - } + @Override + public boolean saveDatabase() { + return this.saveDatabase; + } - @Override - public abstract void saveNoConfig(); + @Override + public boolean saveByteSets() { + return this.saveByteSets; + } - @Override - public abstract NoConfigInterface loadNoConfig() throws IOException; + @Override + public abstract void saveNoConfig(); + + @Override + public abstract NoConfigInterface loadNoConfig() throws IOException; } diff --git a/src/nodash/core/NoConfigDefault.java b/src/nodash/core/NoConfigDefault.java index 09e8f52..f327861 100644 --- a/src/nodash/core/NoConfigDefault.java +++ b/src/nodash/core/NoConfigDefault.java @@ -1,20 +1,17 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * The NoConfig is a means to store the server secret key, database address - * and other configs. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * The NoConfig is a means to store the server secret key, database address and other configs. */ package nodash.core; @@ -32,59 +29,60 @@ import java.nio.file.StandardOpenOption; import nodash.exceptions.NoDashFatalException; public final class NoConfigDefault extends NoConfigBase implements Serializable { - private static final long serialVersionUID = -8498303909736017075L; + private static final long serialVersionUID = -8498303909736017075L; - private static final String CONFIG_FILENAME = "noconfig.cfg"; - - private String databaseFileName = "nodatabase.hash"; + private static final String CONFIG_FILENAME = "noconfig.cfg"; - @Override - public boolean saveDatabase() { - return saveDatabase; - } - - public String getDatabaseName() { - return databaseFileName; - } + private String databaseFileName = "nodatabase.hash"; - @Override - public boolean saveByteSets() { - return saveByteSets; - } + @Override + public boolean saveDatabase() { + return saveDatabase; + } - @Override - public void saveNoConfig() { - try { - File file = new File(NoConfigDefault.CONFIG_FILENAME); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(this); - byte[] data = baos.toByteArray(); - - Files.write(file.toPath(), data, StandardOpenOption.CREATE_NEW); - } catch (IOException e) { - throw new NoDashFatalException("Unable to save config, including generated secret key.", e); - } - } + public String getDatabaseName() { + return databaseFileName; + } - @Override - public NoConfigInterface loadNoConfig() throws IOException { - File file = new File(NoConfigDefault.CONFIG_FILENAME); - byte[] data = Files.readAllBytes(file.toPath()); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - ObjectInputStream ois = new ObjectInputStream(bais); - NoConfigInterface noConfig; - try { - noConfig = (NoConfigDefault) ois.readObject(); - } catch (ClassNotFoundException e) { - throw new NoDashFatalException("Given bytestream does not compile into a configuration object.", e); - } - this.ready = true; - return noConfig; - } + @Override + public boolean saveByteSets() { + return saveByteSets; + } - @Override - public boolean isReady() { - return this.ready; - } + @Override + public void saveNoConfig() { + try { + File file = new File(NoConfigDefault.CONFIG_FILENAME); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(this); + byte[] data = baos.toByteArray(); + + Files.write(file.toPath(), data, StandardOpenOption.CREATE_NEW); + } catch (IOException e) { + throw new NoDashFatalException("Unable to save config, including generated secret key.", e); + } + } + + @Override + public NoConfigInterface loadNoConfig() throws IOException { + File file = new File(NoConfigDefault.CONFIG_FILENAME); + byte[] data = Files.readAllBytes(file.toPath()); + ByteArrayInputStream bais = new ByteArrayInputStream(data); + ObjectInputStream ois = new ObjectInputStream(bais); + NoConfigInterface noConfig; + try { + noConfig = (NoConfigDefault) ois.readObject(); + } catch (ClassNotFoundException e) { + throw new NoDashFatalException( + "Given bytestream does not compile into a configuration object.", e); + } + this.ready = true; + return noConfig; + } + + @Override + public boolean isReady() { + return this.ready; + } } diff --git a/src/nodash/core/NoConfigInterface.java b/src/nodash/core/NoConfigInterface.java index c6aee6e..b8bd8ad 100644 --- a/src/nodash/core/NoConfigInterface.java +++ b/src/nodash/core/NoConfigInterface.java @@ -5,11 +5,17 @@ import java.io.IOException; import javax.crypto.SecretKey; public interface NoConfigInterface { - public void construct(); - public SecretKey getSecretKey(); - public boolean saveDatabase(); - public boolean saveByteSets(); - public void saveNoConfig(); - public NoConfigInterface loadNoConfig() throws IOException; - public boolean isReady(); + public void construct(); + + public SecretKey getSecretKey(); + + public boolean saveDatabase(); + + public boolean saveByteSets(); + + public void saveNoConfig(); + + public NoConfigInterface loadNoConfig() throws IOException; + + public boolean isReady(); } diff --git a/src/nodash/core/NoCore.java b/src/nodash/core/NoCore.java index 7c51b21..c9538d3 100644 --- a/src/nodash/core/NoCore.java +++ b/src/nodash/core/NoCore.java @@ -1,20 +1,18 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * The NoCore class is the interface between which the wrapper application - * (wrapplication?) accesses no- functionality. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * The NoCore class is the interface between which the wrapper application (wrapplication?) accesses + * no- functionality. */ package nodash.core; @@ -39,83 +37,94 @@ import nodash.models.NoUser; import nodash.models.NoSession.NoState; public final class NoCore { - public static NoConfigInterface config; - public static NoHashSphereInterface hashSphere; - - public static boolean isReady() { - return (config != null && config.isReady()) && - (hashSphere != null && hashSphere.isReady()); - } - - public static void setup(NoConfigInterface config, NoHashSphereInterface hashSphere) { - NoCore.setup(config); - NoCore.setup(hashSphere); - } - - public static void setup(NoConfigInterface config) { - NoCore.config = config; - } - - public static void setup(NoHashSphereInterface hashSphere) { - NoCore.hashSphere = hashSphere; - hashSphere.setup(); - } - - public static void setup() { - NoConfigInterface newConfig = new NoConfigDefault(); - try { - newConfig = newConfig.loadNoConfig(); - } catch (IOException e) { - newConfig.construct(); - } - NoCore.setup(newConfig); - NoCore.setup(new NoHashSphereDefault()); - } - - public static byte[] login(byte[] data, char[] password) throws NoUserNotValidException, NoUserAlreadyOnlineException, NoSessionExpiredException { - /* steps 1 through to pre-3 */ - return NoSessionSphere.login(data, password); - } - - public static NoRegister register(NoUser user, char[] password) { - /* Straight to step 4 */ - return NoSessionSphere.registerUser(user, password); - } - - public static NoUser getUser(byte[] cookie) throws NoSessionExpiredException, NoSessionConfirmedException, NoDashSessionBadUUIDException { - /* Facilitates step 3 - * allow website-side modifications to the NoUser or NoUser inheritant */ - return NoSessionSphere.getUser(cookie); - } - - public static NoState getSessionState(byte[] cookie) throws NoSessionExpiredException, NoSessionConfirmedException, NoDashSessionBadUUIDException { - /* Facilitates step 3 - * allow front-side to keep track of session state */ - return NoSessionSphere.getState(cookie); - } - - public static byte[] requestSave(byte[] cookie, char[] password) throws NoSessionExpiredException, NoSessionConfirmedException, NoSessionNotChangedException, NoSessionAlreadyAwaitingConfirmationException, NoDashSessionBadUUIDException { - /* Step 4. Provides a user with the new binary file */ - return NoSessionSphere.save(cookie, password); - } - - public static void confirm(byte[] cookie, char[] password, byte[] data) throws NoSessionExpiredException, NoSessionConfirmedException, NoSessionNotAwaitingConfirmationException, NoUserNotValidException, NoDashSessionBadUUIDException { - /* Step 5. Assumes the user has re-uploaded the file along with providing the same password. - * Further attempts of getUser or getSessionState will fail with a NoSessionExpiredException*/ - NoSessionSphere.confirm(cookie, password, data); - } + public static NoConfigInterface config; + public static NoHashSphereInterface hashSphere; - public static void addByteSet(NoByteSet byteSet, PublicKey publicKey) { - NoByteSetSphere.add(byteSet, publicKey); - } - - public static void shred(byte[] cookie) { - /* 3.2 Hot pull */ - NoSessionSphere.shred(cookie); - } - - public static void triggerPrune() { - NoSessionSphere.prune(); - } - -} \ No newline at end of file + public static boolean isReady() { + return (config != null && config.isReady()) && (hashSphere != null && hashSphere.isReady()); + } + + public static void setup(NoConfigInterface config, NoHashSphereInterface hashSphere) { + NoCore.setup(config); + NoCore.setup(hashSphere); + } + + public static void setup(NoConfigInterface config) { + NoCore.config = config; + } + + public static void setup(NoHashSphereInterface hashSphere) { + NoCore.hashSphere = hashSphere; + hashSphere.setup(); + } + + public static void setup() { + NoConfigInterface newConfig = new NoConfigDefault(); + try { + newConfig = newConfig.loadNoConfig(); + } catch (IOException e) { + newConfig.construct(); + } + NoCore.setup(newConfig); + NoCore.setup(new NoHashSphereDefault()); + } + + public static byte[] login(byte[] data, char[] password) throws NoUserNotValidException, + NoUserAlreadyOnlineException, NoSessionExpiredException { + /* steps 1 through to pre-3 */ + return NoSessionSphere.login(data, password); + } + + public static NoRegister register(NoUser user, char[] password) { + /* Straight to step 4 */ + return NoSessionSphere.registerUser(user, password); + } + + public static NoUser getUser(byte[] cookie) throws NoSessionExpiredException, + NoSessionConfirmedException, NoDashSessionBadUUIDException { + /* + * Facilitates step 3 allow website-side modifications to the NoUser or NoUser inheritant + */ + return NoSessionSphere.getUser(cookie); + } + + public static NoState getSessionState(byte[] cookie) throws NoSessionExpiredException, + NoSessionConfirmedException, NoDashSessionBadUUIDException { + /* + * Facilitates step 3 allow front-side to keep track of session state + */ + return NoSessionSphere.getState(cookie); + } + + public static byte[] requestSave(byte[] cookie, char[] password) + throws NoSessionExpiredException, NoSessionConfirmedException, NoSessionNotChangedException, + NoSessionAlreadyAwaitingConfirmationException, NoDashSessionBadUUIDException { + /* Step 4. Provides a user with the new binary file */ + return NoSessionSphere.save(cookie, password); + } + + public static void confirm(byte[] cookie, char[] password, byte[] data) + throws NoSessionExpiredException, NoSessionConfirmedException, + NoSessionNotAwaitingConfirmationException, NoUserNotValidException, + NoDashSessionBadUUIDException { + /* + * Step 5. Assumes the user has re-uploaded the file along with providing the same password. + * Further attempts of getUser or getSessionState will fail with a NoSessionExpiredException + */ + NoSessionSphere.confirm(cookie, password, data); + } + + public static void addByteSet(NoByteSet byteSet, PublicKey publicKey) { + NoByteSetSphere.add(byteSet, publicKey); + } + + public static void shred(byte[] cookie) { + /* 3.2 Hot pull */ + NoSessionSphere.shred(cookie); + } + + public static void triggerPrune() { + NoSessionSphere.prune(); + } + +} diff --git a/src/nodash/core/NoRegister.java b/src/nodash/core/NoRegister.java index c6b3f30..ef40d34 100644 --- a/src/nodash/core/NoRegister.java +++ b/src/nodash/core/NoRegister.java @@ -1,25 +1,23 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * The NoRegister class is a simple model used to return both cookies and - * download data upon user registration. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * The NoRegister class is a simple model used to return both cookies and download data upon user + * registration. */ package nodash.core; public final class NoRegister { - public byte[] cookie; - public byte[] data; -} \ No newline at end of file + public byte[] cookie; + public byte[] data; +} diff --git a/src/nodash/core/NoUtil.java b/src/nodash/core/NoUtil.java index 2b8e65a..a0d3f7c 100644 --- a/src/nodash/core/NoUtil.java +++ b/src/nodash/core/NoUtil.java @@ -1,20 +1,18 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * The NoUtil class encapsulates no- standard functions such as encryption/decryption - * and hashing algorithms. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * The NoUtil class encapsulates no- standard functions such as encryption/decryption and hashing + * algorithms. */ package nodash.core; @@ -38,172 +36,177 @@ import javax.crypto.spec.SecretKeySpec; import nodash.exceptions.NoDashFatalException; -public final class NoUtil { - public static final String CIPHER_TYPE = "AES/ECB/PKCS5PADDING"; - public static final String CIPHER_KEY_SPEC = "AES"; - public static final String DIGEST_TYPE = "SHA-512"; - public static final String PBE_TYPE = "PBKDF2WithHmacSHA1"; - public static final String CIPHER_RSA_TYPE = "RSA/ECB/PKCS1PADDING"; - public static final String KEYPAIR_ALGORITHM = "RSA"; - public static final String SECURERANDOM_ALGORITHM = "SHA1PRNG"; - public static final String SECURERANDOM_PROVIDER = "SUN"; - public static final int RSA_STRENGTH = 4096; - public static final int AES_STRENGTH = 256; - public static final byte BLANK_BYTE = 'A'; - - public static char[] bytesToChars(byte[] array) { - char[] result = new char[array.length]; - for (int x=0; x EMPTY_BYTESET_LIST = new ArrayList(0); - - private static ConcurrentHashMap> byteSets = new ConcurrentHashMap>(); - - public static void add(NoByteSet byteSet, PublicKey publicKey) { - if (!NoByteSetSphere.byteSets.containsKey(publicKey)) { - NoByteSetSphere.byteSets.put(publicKey, new ArrayList()); - } - NoByteSetSphere.byteSets.get(publicKey).add(byteSet); - } - - public static void addList(ArrayList byteSetList, PublicKey publicKey) { - if (!NoByteSetSphere.byteSets.containsKey(publicKey)) { - NoByteSetSphere.byteSets.put(publicKey, new ArrayList()); - } - NoByteSetSphere.byteSets.get(publicKey).addAll(byteSetList); - } - - public static ArrayList consume(NoUser user) { - if (NoByteSetSphere.byteSets.containsKey(user.getRSAPublicKey())) { - ArrayList result = NoByteSetSphere.byteSets.get(user.getRSAPublicKey()); - NoByteSetSphere.byteSets.remove(user.getRSAPublicKey()); - return result; - } else { - return NoByteSetSphere.EMPTY_BYTESET_LIST; - } - } + private static final ArrayList EMPTY_BYTESET_LIST = new ArrayList(0); + + private static ConcurrentHashMap> byteSets = + new ConcurrentHashMap>(); + + public static void add(NoByteSet byteSet, PublicKey publicKey) { + if (!NoByteSetSphere.byteSets.containsKey(publicKey)) { + NoByteSetSphere.byteSets.put(publicKey, new ArrayList()); + } + NoByteSetSphere.byteSets.get(publicKey).add(byteSet); + } + + public static void addList(ArrayList byteSetList, PublicKey publicKey) { + if (!NoByteSetSphere.byteSets.containsKey(publicKey)) { + NoByteSetSphere.byteSets.put(publicKey, new ArrayList()); + } + NoByteSetSphere.byteSets.get(publicKey).addAll(byteSetList); + } + + public static ArrayList consume(NoUser user) { + if (NoByteSetSphere.byteSets.containsKey(user.getRSAPublicKey())) { + ArrayList result = NoByteSetSphere.byteSets.get(user.getRSAPublicKey()); + NoByteSetSphere.byteSets.remove(user.getRSAPublicKey()); + return result; + } else { + return NoByteSetSphere.EMPTY_BYTESET_LIST; + } + } } diff --git a/src/nodash/core/spheres/NoHashSphereDefault.java b/src/nodash/core/spheres/NoHashSphereDefault.java index c36dd7c..e322fb3 100644 --- a/src/nodash/core/spheres/NoHashSphereDefault.java +++ b/src/nodash/core/spheres/NoHashSphereDefault.java @@ -1,17 +1,15 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * * The NoHashSpehre stores database hashes for user verification. * @@ -38,77 +36,78 @@ import nodash.exceptions.NoDashFatalException; import nodash.models.NoUser; public final class NoHashSphereDefault implements NoHashSphereInterface { - private Set database = Collections.newSetFromMap(new ConcurrentHashMap()); - private String fileName; - private boolean ready = false; - - public NoHashSphereDefault(String fileName) { - this.fileName = fileName; - } - - public NoHashSphereDefault() { - this.fileName = ( (NoConfigDefault) NoCore.config).getDatabaseName(); - } - - @SuppressWarnings("unchecked") - public void setup() { - if (NoCore.config.saveDatabase()) { - File file = new File(this.fileName); - if (file.exists()) { - try { - byte[] data = Files.readAllBytes(file.toPath()); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - ObjectInputStream ois = new ObjectInputStream(bais); - this.database = (Set) ois.readObject(); - ois.close(); - bais.close(); - } catch (IOException e){ - throw new NoDashFatalException("Unable to load up given database file.", e); - } catch (ClassNotFoundException e) { - throw new NoDashFatalException("Database file not in a verifiable format.", e); - } - } - } - this.ready = true; - } - - public synchronized void saveToFile() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(this.database); - byte[] data = baos.toByteArray(); - oos.close(); - baos.close(); - File file = new File( ( (NoConfigDefault) NoCore.config).getDatabaseName()); - Files.write(file.toPath(), data, StandardOpenOption.CREATE); - } - - public synchronized void addNewNoUser(NoUser user) throws IOException { - String hash = user.createHashString(); - this.database.add(hash); - this.saveToFile(); - } - - public synchronized void insertHash(String hash) throws IOException { - this.database.add(hash); - this.saveToFile(); - } - - public synchronized void removeHash(String hash) throws IOException { - this.database.remove(hash); - this.saveToFile(); - } - - public synchronized boolean checkHash(String hash) { - return this.database.contains(hash); - } + private Set database = Collections + .newSetFromMap(new ConcurrentHashMap()); + private String fileName; + private boolean ready = false; - public synchronized long size() { - return this.database.size(); - } + public NoHashSphereDefault(String fileName) { + this.fileName = fileName; + } - @Override - public boolean isReady() { - return this.ready; - } + public NoHashSphereDefault() { + this.fileName = ((NoConfigDefault) NoCore.config).getDatabaseName(); + } + + @SuppressWarnings("unchecked") + public void setup() { + if (NoCore.config.saveDatabase()) { + File file = new File(this.fileName); + if (file.exists()) { + try { + byte[] data = Files.readAllBytes(file.toPath()); + ByteArrayInputStream bais = new ByteArrayInputStream(data); + ObjectInputStream ois = new ObjectInputStream(bais); + this.database = (Set) ois.readObject(); + ois.close(); + bais.close(); + } catch (IOException e) { + throw new NoDashFatalException("Unable to load up given database file.", e); + } catch (ClassNotFoundException e) { + throw new NoDashFatalException("Database file not in a verifiable format.", e); + } + } + } + this.ready = true; + } + + public synchronized void saveToFile() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(this.database); + byte[] data = baos.toByteArray(); + oos.close(); + baos.close(); + File file = new File(((NoConfigDefault) NoCore.config).getDatabaseName()); + Files.write(file.toPath(), data, StandardOpenOption.CREATE); + } + + public synchronized void addNewNoUser(NoUser user) throws IOException { + String hash = user.createHashString(); + this.database.add(hash); + this.saveToFile(); + } + + public synchronized void insertHash(String hash) throws IOException { + this.database.add(hash); + this.saveToFile(); + } + + public synchronized void removeHash(String hash) throws IOException { + this.database.remove(hash); + this.saveToFile(); + } + + public synchronized boolean checkHash(String hash) { + return this.database.contains(hash); + } + + public synchronized long size() { + return this.database.size(); + } + + @Override + public boolean isReady() { + return this.ready; + } } diff --git a/src/nodash/core/spheres/NoHashSphereInterface.java b/src/nodash/core/spheres/NoHashSphereInterface.java index f2d1b46..c452d0e 100644 --- a/src/nodash/core/spheres/NoHashSphereInterface.java +++ b/src/nodash/core/spheres/NoHashSphereInterface.java @@ -5,12 +5,19 @@ import java.io.IOException; import nodash.models.NoUser; public interface NoHashSphereInterface { - public void setup(); - public void saveToFile() throws IOException; - public void addNewNoUser(NoUser user) throws IOException; - public void insertHash(String hash) throws IOException; - public void removeHash(String hash) throws IOException; - public boolean checkHash(String hash); - public long size(); - public boolean isReady(); + public void setup(); + + public void saveToFile() throws IOException; + + public void addNewNoUser(NoUser user) throws IOException; + + public void insertHash(String hash) throws IOException; + + public void removeHash(String hash) throws IOException; + + public boolean checkHash(String hash); + + public long size(); + + public boolean isReady(); } diff --git a/src/nodash/core/spheres/NoSessionSphere.java b/src/nodash/core/spheres/NoSessionSphere.java index bd10b0d..25ef007 100644 --- a/src/nodash/core/spheres/NoSessionSphere.java +++ b/src/nodash/core/spheres/NoSessionSphere.java @@ -1,20 +1,18 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * The NoSessionSphere stores user sessions and allows their access and - * manipulation with the use of their UUID. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * The NoSessionSphere stores user sessions and allows their access and manipulation with the use of + * their UUID. */ package nodash.core.spheres; @@ -43,148 +41,161 @@ import nodash.models.NoUser; import nodash.models.NoSession.NoState; public final class NoSessionSphere { - private static ConcurrentHashMap sessions = new ConcurrentHashMap(); - private static Set originalHashesOnline = Collections.newSetFromMap(new ConcurrentHashMap()); - - public static synchronized void prune() { - for (UUID uuid : NoSessionSphere.sessions.keySet()) { - pruneSingle(uuid); - } - } + private static ConcurrentHashMap sessions = + new ConcurrentHashMap(); + private static Set originalHashesOnline = Collections + .newSetFromMap(new ConcurrentHashMap()); - public static void shred(byte[] encryptedUUID) { - try { - UUID uuid = NoSession.decryptUUID(encryptedUUID); - if (NoSessionSphere.sessions.containsKey(uuid)) { - NoSession session = NoSessionSphere.sessions.get(uuid); - NoByteSetSphere.addList(session.incoming, session.current.getRSAPublicKey()); - NoSessionSphere.originalHashesOnline.remove(Base64.encodeBase64String(session.getOriginalHash())); - NoSessionSphere.sessions.remove(uuid); - session = null; - } - } catch (NoDashSessionBadUUIDException e) { - // Suppress, doesn't matter - } - } - - public static synchronized void pruneSingle(UUID uuid) { - NoSession session = NoSessionSphere.sessions.get(uuid); - try { - session.check(); - } catch (NoSessionExpiredException e) { - /* Resultant from 3.1 and 3.2 */ - NoByteSetSphere.addList(session.incoming, session.current.getRSAPublicKey()); - NoSessionSphere.originalHashesOnline.remove(session.getOriginalHash()); - NoSessionSphere.sessions.remove(uuid); - session = null; - } catch (NoSessionConfirmedException e) { - /* Should be cleaned up at 5.2 */ - } - } - - public static synchronized byte[] login(byte[] data, char[] password) throws NoUserNotValidException, NoUserAlreadyOnlineException, NoSessionExpiredException { - /* 1. Login with byte[] data and byte[] password */ - NoSession session = new NoSession(data, password); - /* 1.1. User currently has an online session, must wait for it to expire. */ - if (originalHashesOnline.contains(Base64.encodeBase64String(session.getOriginalHash()))) { - throw new NoUserAlreadyOnlineException(); - } - /* 1.2. User successfully logged in: set up session records. */ - NoSessionSphere.originalHashesOnline.add(Base64.encodeBase64String(session.getOriginalHash())); - NoSessionSphere.sessions.put(session.uuid, session); - - /* 2. Check NoByteSetSphere for incoming Influences */ - session.incoming = NoByteSetSphere.consume(session.current); - for (NoByteSet nbs : session.incoming) { - /* 2.1 Decrypt NoInfluence from NoByteSet, let the current user consume them */ - try { - session.consume(nbs); - } catch (NoByteSetBadDecryptionException e) { - throw new NoDashFatalException("Bad byte sets on consumption.", e); - } - } /* 2.2 Alternatively, no NoByteSets to consume */ - - try { - session.check(); - } catch (NoSessionConfirmedException e) { - /* Should be impossible to reach */ - throw new NoDashFatalException(e); - } - - /* Will set to 2.1[MODIFIED] or 2.2[IDLE] */ - - /* Precursor to 3.; allow website to associate user session with a cookie. */ - return session.getEncryptedUUID(); - } - - public static NoUser getUser(byte[] encryptedUUID) throws NoDashSessionBadUUIDException, NoSessionExpiredException, NoSessionConfirmedException { - UUID uuid = NoSession.decryptUUID(encryptedUUID); - if (NoSessionSphere.sessions.containsKey(uuid)) { - NoSessionSphere.pruneSingle(uuid); - try { - return NoSessionSphere.sessions.get(uuid).getNoUser(); - } catch (NullPointerException e) { - throw new NoSessionExpiredException(); - } - } - throw new NoSessionExpiredException(); - } - - public static NoState getState(byte[] encryptedUUID) throws NoDashSessionBadUUIDException, NoSessionExpiredException, NoSessionConfirmedException { - UUID uuid = NoSession.decryptUUID(encryptedUUID); - if (NoSessionSphere.sessions.containsKey(uuid)) { - NoSessionSphere.pruneSingle(uuid); - NoSession session = NoSessionSphere.sessions.get(uuid); - return session.getNoState(); - } - throw new NoSessionExpiredException(); - } - - public static synchronized byte[] save(byte[] encryptedUUID, char[] password) throws NoDashSessionBadUUIDException, NoSessionExpiredException, NoSessionConfirmedException, NoSessionNotChangedException, NoSessionAlreadyAwaitingConfirmationException { - UUID uuid = NoSession.decryptUUID(encryptedUUID); - if (NoSessionSphere.sessions.containsKey(uuid)) { - NoSessionSphere.pruneSingle(uuid); - NoSession session = NoSessionSphere.sessions.get(uuid); - - if (session.getNoState().equals(NoState.IDLE)) { - throw new NoSessionNotChangedException(); - } else if (session.getNoState().equals(NoState.AWAITING_CONFIRMATION)) { - throw new NoSessionAlreadyAwaitingConfirmationException(); - } - return session.initiateSaveAttempt(password); - } - throw new NoSessionExpiredException(); - } - - public static synchronized void confirm(byte[] encryptedUUID, char[] password, byte[] data) throws NoDashSessionBadUUIDException, NoSessionExpiredException, NoSessionConfirmedException, NoSessionNotAwaitingConfirmationException, NoUserNotValidException { - UUID uuid = NoSession.decryptUUID(encryptedUUID); - if (NoSessionSphere.sessions.containsKey(uuid)) { - NoSessionSphere.pruneSingle(uuid); - NoSession session = NoSessionSphere.sessions.get(uuid); - session.confirmSave(data, password); - return; - } - throw new NoSessionExpiredException(); - } + public static synchronized void prune() { + for (UUID uuid : NoSessionSphere.sessions.keySet()) { + pruneSingle(uuid); + } + } - public static synchronized NoRegister registerUser(NoUser user, char[] password) { - NoRegister result = new NoRegister(); - NoSession session = new NoSession(user); - NoSessionSphere.sessions.put(session.uuid, session); - result.cookie = session.getEncryptedUUID(); - try { - result.data = NoSessionSphere.save(result.cookie, password); - } catch (NoDashSessionBadUUIDException e) { - throw new NoDashFatalException("Immediately generated cookie throwing bad cookie error.", e); - } catch (NoSessionExpiredException e) { - throw new NoDashFatalException("Session expired before it was even returned to client.", e); - } catch (NoSessionConfirmedException e) { - throw new NoDashFatalException("Session is in confirmed state before it was returned to client.", e); - } catch (NoSessionNotChangedException e) { - throw new NoDashFatalException("Session claims to be unchanged but user is newly registered.", e); - } catch (NoSessionAlreadyAwaitingConfirmationException e) { - throw new NoDashFatalException("Session claims to be awaiting confirmation before returning data to the user.", e); - } - return result; - } -} \ No newline at end of file + public static void shred(byte[] encryptedUUID) { + try { + UUID uuid = NoSession.decryptUUID(encryptedUUID); + if (NoSessionSphere.sessions.containsKey(uuid)) { + NoSession session = NoSessionSphere.sessions.get(uuid); + NoByteSetSphere.addList(session.incoming, session.current.getRSAPublicKey()); + NoSessionSphere.originalHashesOnline.remove(Base64.encodeBase64String(session + .getOriginalHash())); + NoSessionSphere.sessions.remove(uuid); + session = null; + } + } catch (NoDashSessionBadUUIDException e) { + // Suppress, doesn't matter + } + } + + public static synchronized void pruneSingle(UUID uuid) { + NoSession session = NoSessionSphere.sessions.get(uuid); + try { + session.check(); + } catch (NoSessionExpiredException e) { + /* Resultant from 3.1 and 3.2 */ + NoByteSetSphere.addList(session.incoming, session.current.getRSAPublicKey()); + NoSessionSphere.originalHashesOnline.remove(session.getOriginalHash()); + NoSessionSphere.sessions.remove(uuid); + session = null; + } catch (NoSessionConfirmedException e) { + /* Should be cleaned up at 5.2 */ + } + } + + public static synchronized byte[] login(byte[] data, char[] password) + throws NoUserNotValidException, NoUserAlreadyOnlineException, NoSessionExpiredException { + /* 1. Login with byte[] data and byte[] password */ + NoSession session = new NoSession(data, password); + /* 1.1. User currently has an online session, must wait for it to expire. */ + if (originalHashesOnline.contains(Base64.encodeBase64String(session.getOriginalHash()))) { + throw new NoUserAlreadyOnlineException(); + } + /* 1.2. User successfully logged in: set up session records. */ + NoSessionSphere.originalHashesOnline.add(Base64.encodeBase64String(session.getOriginalHash())); + NoSessionSphere.sessions.put(session.uuid, session); + + /* 2. Check NoByteSetSphere for incoming Influences */ + session.incoming = NoByteSetSphere.consume(session.current); + for (NoByteSet nbs : session.incoming) { + /* 2.1 Decrypt NoInfluence from NoByteSet, let the current user consume them */ + try { + session.consume(nbs); + } catch (NoByteSetBadDecryptionException e) { + throw new NoDashFatalException("Bad byte sets on consumption.", e); + } + } /* 2.2 Alternatively, no NoByteSets to consume */ + + try { + session.check(); + } catch (NoSessionConfirmedException e) { + /* Should be impossible to reach */ + throw new NoDashFatalException(e); + } + + /* Will set to 2.1[MODIFIED] or 2.2[IDLE] */ + + /* Precursor to 3.; allow website to associate user session with a cookie. */ + return session.getEncryptedUUID(); + } + + public static NoUser getUser(byte[] encryptedUUID) throws NoDashSessionBadUUIDException, + NoSessionExpiredException, NoSessionConfirmedException { + UUID uuid = NoSession.decryptUUID(encryptedUUID); + if (NoSessionSphere.sessions.containsKey(uuid)) { + NoSessionSphere.pruneSingle(uuid); + try { + return NoSessionSphere.sessions.get(uuid).getNoUser(); + } catch (NullPointerException e) { + throw new NoSessionExpiredException(); + } + } + throw new NoSessionExpiredException(); + } + + public static NoState getState(byte[] encryptedUUID) throws NoDashSessionBadUUIDException, + NoSessionExpiredException, NoSessionConfirmedException { + UUID uuid = NoSession.decryptUUID(encryptedUUID); + if (NoSessionSphere.sessions.containsKey(uuid)) { + NoSessionSphere.pruneSingle(uuid); + NoSession session = NoSessionSphere.sessions.get(uuid); + return session.getNoState(); + } + throw new NoSessionExpiredException(); + } + + public static synchronized byte[] save(byte[] encryptedUUID, char[] password) + throws NoDashSessionBadUUIDException, NoSessionExpiredException, NoSessionConfirmedException, + NoSessionNotChangedException, NoSessionAlreadyAwaitingConfirmationException { + UUID uuid = NoSession.decryptUUID(encryptedUUID); + if (NoSessionSphere.sessions.containsKey(uuid)) { + NoSessionSphere.pruneSingle(uuid); + NoSession session = NoSessionSphere.sessions.get(uuid); + + if (session.getNoState().equals(NoState.IDLE)) { + throw new NoSessionNotChangedException(); + } else if (session.getNoState().equals(NoState.AWAITING_CONFIRMATION)) { + throw new NoSessionAlreadyAwaitingConfirmationException(); + } + return session.initiateSaveAttempt(password); + } + throw new NoSessionExpiredException(); + } + + public static synchronized void confirm(byte[] encryptedUUID, char[] password, byte[] data) + throws NoDashSessionBadUUIDException, NoSessionExpiredException, NoSessionConfirmedException, + NoSessionNotAwaitingConfirmationException, NoUserNotValidException { + UUID uuid = NoSession.decryptUUID(encryptedUUID); + if (NoSessionSphere.sessions.containsKey(uuid)) { + NoSessionSphere.pruneSingle(uuid); + NoSession session = NoSessionSphere.sessions.get(uuid); + session.confirmSave(data, password); + return; + } + throw new NoSessionExpiredException(); + } + + public static synchronized NoRegister registerUser(NoUser user, char[] password) { + NoRegister result = new NoRegister(); + NoSession session = new NoSession(user); + NoSessionSphere.sessions.put(session.uuid, session); + result.cookie = session.getEncryptedUUID(); + try { + result.data = NoSessionSphere.save(result.cookie, password); + } catch (NoDashSessionBadUUIDException e) { + throw new NoDashFatalException("Immediately generated cookie throwing bad cookie error.", e); + } catch (NoSessionExpiredException e) { + throw new NoDashFatalException("Session expired before it was even returned to client.", e); + } catch (NoSessionConfirmedException e) { + throw new NoDashFatalException( + "Session is in confirmed state before it was returned to client.", e); + } catch (NoSessionNotChangedException e) { + throw new NoDashFatalException( + "Session claims to be unchanged but user is newly registered.", e); + } catch (NoSessionAlreadyAwaitingConfirmationException e) { + throw new NoDashFatalException( + "Session claims to be awaiting confirmation before returning data to the user.", e); + } + return result; + } +} diff --git a/src/nodash/exceptions/NoByteSetBadDecryptionException.java b/src/nodash/exceptions/NoByteSetBadDecryptionException.java index 8b39ffe..98352de 100644 --- a/src/nodash/exceptions/NoByteSetBadDecryptionException.java +++ b/src/nodash/exceptions/NoByteSetBadDecryptionException.java @@ -1,29 +1,26 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoByteSetBadDecryptionException is triggered when no- is unable to - * decrypt a given byte stream. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoByteSetBadDecryptionException is triggered when no- is unable to decrypt a given byte stream. */ package nodash.exceptions; public class NoByteSetBadDecryptionException extends NoDashException { - private static final long serialVersionUID = -8579497499272656543L; - - public NoByteSetBadDecryptionException(Exception e) { - super(e); - } + private static final long serialVersionUID = -8579497499272656543L; + + public NoByteSetBadDecryptionException(Exception e) { + super(e); + } } diff --git a/src/nodash/exceptions/NoCannotGetInfluenceException.java b/src/nodash/exceptions/NoCannotGetInfluenceException.java index 084eab0..65f16bf 100644 --- a/src/nodash/exceptions/NoCannotGetInfluenceException.java +++ b/src/nodash/exceptions/NoCannotGetInfluenceException.java @@ -1,21 +1,19 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoCannotGetInfluenceException is returned when an action is unable to - * render a successful influence for the target, instead returning an - * influence to be returned to the sender if possible. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoCannotGetInfluenceException is returned when an action is unable to render a successful + * influence for the target, instead returning an influence to be returned to the sender if + * possible. */ package nodash.exceptions; @@ -23,16 +21,16 @@ package nodash.exceptions; import nodash.models.NoInfluence; public class NoCannotGetInfluenceException extends Exception { - private static final long serialVersionUID = 4581361079067540974L; - - private NoInfluence returnable; - - public NoCannotGetInfluenceException(NoInfluence returnable) { - super(); - this.returnable = returnable; - } - - public NoInfluence getResponseInfluence() { - return returnable; - } + private static final long serialVersionUID = 4581361079067540974L; + + private NoInfluence returnable; + + public NoCannotGetInfluenceException(NoInfluence returnable) { + super(); + this.returnable = returnable; + } + + public NoInfluence getResponseInfluence() { + return returnable; + } } diff --git a/src/nodash/exceptions/NoDashException.java b/src/nodash/exceptions/NoDashException.java index ccfd06e..861be9b 100644 --- a/src/nodash/exceptions/NoDashException.java +++ b/src/nodash/exceptions/NoDashException.java @@ -1,17 +1,15 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * * NoDashException is the base class for no- related exceptions. */ @@ -19,13 +17,13 @@ package nodash.exceptions; public class NoDashException extends Exception { - private static final long serialVersionUID = -8579497499272656543L; + private static final long serialVersionUID = -8579497499272656543L; - public NoDashException() { - super(); - } - - public NoDashException(Exception e) { - super(e); - } + public NoDashException() { + super(); + } + + public NoDashException(Exception e) { + super(e); + } } diff --git a/src/nodash/exceptions/NoDashFatalException.java b/src/nodash/exceptions/NoDashFatalException.java index 24674fa..f4772bb 100644 --- a/src/nodash/exceptions/NoDashFatalException.java +++ b/src/nodash/exceptions/NoDashFatalException.java @@ -1,35 +1,33 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. * * NoDashFatalException is the base exception for no- related runtime exceptions. */ package nodash.exceptions; -public class NoDashFatalException extends RuntimeException { - private static final long serialVersionUID = -8254102569327237811L; +public class NoDashFatalException extends RuntimeException { + private static final long serialVersionUID = -8254102569327237811L; - public NoDashFatalException(Exception e) { - super(e); - } + public NoDashFatalException(Exception e) { + super(e); + } - public NoDashFatalException(String string) { - super(string); - } - - public NoDashFatalException(String string, Exception e) { - super(string, e); - } + public NoDashFatalException(String string) { + super(string); + } + + public NoDashFatalException(String string, Exception e) { + super(string, e); + } } diff --git a/src/nodash/exceptions/NoDashSessionBadUUIDException.java b/src/nodash/exceptions/NoDashSessionBadUUIDException.java index 60ff766..773166e 100644 --- a/src/nodash/exceptions/NoDashSessionBadUUIDException.java +++ b/src/nodash/exceptions/NoDashSessionBadUUIDException.java @@ -1,32 +1,30 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoDashSessionBadUUIDException is triggered when the NoSessionSphere is - * unable to find a valid session for the provided UUID. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoDashSessionBadUUIDException is triggered when the NoSessionSphere is unable to find a valid + * session for the provided UUID. */ package nodash.exceptions; public class NoDashSessionBadUUIDException extends Exception { - private static final long serialVersionUID = -402131397575158344L; + private static final long serialVersionUID = -402131397575158344L; - public NoDashSessionBadUUIDException() { - super(); - } - - public NoDashSessionBadUUIDException(Exception e) { - super(e); - } + public NoDashSessionBadUUIDException() { + super(); + } + + public NoDashSessionBadUUIDException(Exception e) { + super(e); + } } diff --git a/src/nodash/exceptions/NoSessionAlreadyAwaitingConfirmationException.java b/src/nodash/exceptions/NoSessionAlreadyAwaitingConfirmationException.java index d884b3d..5f87ab9 100644 --- a/src/nodash/exceptions/NoSessionAlreadyAwaitingConfirmationException.java +++ b/src/nodash/exceptions/NoSessionAlreadyAwaitingConfirmationException.java @@ -1,25 +1,22 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoSessionAlreadyAWaitingConfirmationException is triggered when a - * save request is attempted for a session, but it is already awaiting - * a confirmation upload. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoSessionAlreadyAWaitingConfirmationException is triggered when a save request is attempted for a + * session, but it is already awaiting a confirmation upload. */ package nodash.exceptions; public class NoSessionAlreadyAwaitingConfirmationException extends NoDashException { - private static final long serialVersionUID = 6046203718016296554L; + private static final long serialVersionUID = 6046203718016296554L; } diff --git a/src/nodash/exceptions/NoSessionConfirmedException.java b/src/nodash/exceptions/NoSessionConfirmedException.java index cb5c671..8cce75a 100644 --- a/src/nodash/exceptions/NoSessionConfirmedException.java +++ b/src/nodash/exceptions/NoSessionConfirmedException.java @@ -1,24 +1,22 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoSessionConfirmedException is triggered when an interaction attempt is - * made on a session that has recently been confirmed and thus closed. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoSessionConfirmedException is triggered when an interaction attempt is made on a session that + * has recently been confirmed and thus closed. */ package nodash.exceptions; public class NoSessionConfirmedException extends NoDashException { - private static final long serialVersionUID = -8065331145629402524L; + private static final long serialVersionUID = -8065331145629402524L; } diff --git a/src/nodash/exceptions/NoSessionExpiredException.java b/src/nodash/exceptions/NoSessionExpiredException.java index 99b8998..d00c16f 100644 --- a/src/nodash/exceptions/NoSessionExpiredException.java +++ b/src/nodash/exceptions/NoSessionExpiredException.java @@ -1,24 +1,21 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoSessionExpiredException is thrown when an interaction is attempted with - * an expired session. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoSessionExpiredException is thrown when an interaction is attempted with an expired session. */ package nodash.exceptions; public class NoSessionExpiredException extends NoDashException { - private static final long serialVersionUID = -541733773743173644L; + private static final long serialVersionUID = -541733773743173644L; } diff --git a/src/nodash/exceptions/NoSessionNotAwaitingConfirmationException.java b/src/nodash/exceptions/NoSessionNotAwaitingConfirmationException.java index 1ebf540..6ecf9d5 100644 --- a/src/nodash/exceptions/NoSessionNotAwaitingConfirmationException.java +++ b/src/nodash/exceptions/NoSessionNotAwaitingConfirmationException.java @@ -1,25 +1,22 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoSessionNotAwaitingConfirmationException is thrown when an attempt is made - * to confirm a session with a password/byte[] combination, but the session is - * not currently awaiting a confirmation. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoSessionNotAwaitingConfirmationException is thrown when an attempt is made to confirm a session + * with a password/byte[] combination, but the session is not currently awaiting a confirmation. */ package nodash.exceptions; public class NoSessionNotAwaitingConfirmationException extends NoDashException { - private static final long serialVersionUID = -2563955621281305198L; + private static final long serialVersionUID = -2563955621281305198L; } diff --git a/src/nodash/exceptions/NoSessionNotChangedException.java b/src/nodash/exceptions/NoSessionNotChangedException.java index e67cc0e..d79a483 100644 --- a/src/nodash/exceptions/NoSessionNotChangedException.java +++ b/src/nodash/exceptions/NoSessionNotChangedException.java @@ -1,24 +1,22 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoSessionNotChangedException is thrown when a save is requested for a session - * whilst the user object remains unchanged. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoSessionNotChangedException is thrown when a save is requested for a session whilst the user + * object remains unchanged. */ package nodash.exceptions; public class NoSessionNotChangedException extends NoDashException { - private static final long serialVersionUID = 8049751796255114602L; + private static final long serialVersionUID = 8049751796255114602L; } diff --git a/src/nodash/exceptions/NoUserAlreadyOnlineException.java b/src/nodash/exceptions/NoUserAlreadyOnlineException.java index 75fb252..f0ac774 100644 --- a/src/nodash/exceptions/NoUserAlreadyOnlineException.java +++ b/src/nodash/exceptions/NoUserAlreadyOnlineException.java @@ -1,25 +1,23 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoUserAlreadyOnlineException is thrown when a login attempt is made for - * a user who is currently online. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoUserAlreadyOnlineException is thrown when a login attempt is made for a user who is currently + * online. */ package nodash.exceptions; public class NoUserAlreadyOnlineException extends NoDashException { - private static final long serialVersionUID = -2922060333175653034L; - + private static final long serialVersionUID = -2922060333175653034L; + } diff --git a/src/nodash/exceptions/NoUserNotValidException.java b/src/nodash/exceptions/NoUserNotValidException.java index dada547..ac555ba 100644 --- a/src/nodash/exceptions/NoUserNotValidException.java +++ b/src/nodash/exceptions/NoUserNotValidException.java @@ -1,24 +1,21 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoUserNotValidException is thrown when a user file does not hash to a known - * hash. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoUserNotValidException is thrown when a user file does not hash to a known hash. */ package nodash.exceptions; public class NoUserNotValidException extends NoDashException { - private static final long serialVersionUID = -6432604940919299965L; + private static final long serialVersionUID = -6432604940919299965L; } diff --git a/src/nodash/models/NoAction.java b/src/nodash/models/NoAction.java index 40558a7..30956fb 100644 --- a/src/nodash/models/NoAction.java +++ b/src/nodash/models/NoAction.java @@ -1,20 +1,18 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoAction is an abstract class to allow for the inheritance of actions which - * users can queue before confirmation (user-to-user and user-to-server). + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoAction is an abstract class to allow for the inheritance of actions which users can queue + * before confirmation (user-to-user and user-to-server). */ package nodash.models; @@ -22,8 +20,11 @@ package nodash.models; import java.io.Serializable; public abstract class NoAction implements Serializable { - private static final long serialVersionUID = -194752850197321803L; - public abstract void process(); - public abstract void execute(); - public abstract void purge(); + private static final long serialVersionUID = -194752850197321803L; + + public abstract void process(); + + public abstract void execute(); + + public abstract void purge(); } diff --git a/src/nodash/models/NoByteSet.java b/src/nodash/models/NoByteSet.java index ba5577c..23997ad 100644 --- a/src/nodash/models/NoByteSet.java +++ b/src/nodash/models/NoByteSet.java @@ -1,31 +1,29 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoByteSet stores an AES key which has been RSA-4096 encrypted and a data - * stream which has been encrypted by this key. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoByteSet stores an AES key which has been RSA-4096 encrypted and a data stream which has been + * encrypted by this key. */ package nodash.models; public final class NoByteSet { - public byte[] key; - public byte[] data; - - public NoByteSet(byte[] key, byte[] data) { - this.key = key; - this.data = data; - } - -} \ No newline at end of file + public byte[] key; + public byte[] data; + + public NoByteSet(byte[] key, byte[] data) { + this.key = key; + this.data = data; + } + +} diff --git a/src/nodash/models/NoInfluence.java b/src/nodash/models/NoInfluence.java index 542b930..00183ae 100644 --- a/src/nodash/models/NoInfluence.java +++ b/src/nodash/models/NoInfluence.java @@ -1,22 +1,20 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoInfluence is an abstract class allowing for the subclassing of user - * influences, generated by both actions and the server. Upon login, the user - * consumes NoByteSets (generated by .getByteSet()) into the primary NoInfluence, - * which is then applied to the user with .applyTo(NoUser). + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoInfluence is an abstract class allowing for the subclassing of user influences, generated by + * both actions and the server. Upon login, the user consumes NoByteSets (generated by + * .getByteSet()) into the primary NoInfluence, which is then applied to the user with + * .applyTo(NoUser). * * Examples include incoming messages, financial changes or charges or updates. */ @@ -40,53 +38,54 @@ import javax.crypto.SecretKey; import nodash.core.NoUtil; import nodash.exceptions.NoDashFatalException; -public abstract class NoInfluence implements Serializable { - private static final long serialVersionUID = -7509462039664862920L; +public abstract class NoInfluence implements Serializable { + private static final long serialVersionUID = -7509462039664862920L; + + public abstract void applyTo(NoUser user); + + public final NoByteSet getByteSet(PublicKey publicKey) { + KeyGenerator keyGen; + try { + keyGen = KeyGenerator.getInstance(NoUtil.CIPHER_KEY_SPEC); + } catch (NoSuchAlgorithmException e) { + throw new NoDashFatalException("Value for CIPHER_KEY_SPEC is not valid.", e); + } + keyGen.init(NoUtil.AES_STRENGTH); + SecretKey secretKey = keyGen.generateKey(); + byte[] key = secretKey.getEncoded(); + byte[] encryptedKey = NoUtil.encryptRSA(key, publicKey); + byte[] data = this.getEncrypted(key); + NoUtil.wipeBytes(key); + return new NoByteSet(encryptedKey, data); + } + + private final byte[] getEncrypted(byte[] key) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(this); + byte[] encrypted = NoUtil.encrypt(baos.toByteArray(), key); + oos.close(); + baos.close(); + return encrypted; + } catch (IOException e) { + throw new NoDashFatalException("Unable to write NoInfluence object to byte stream.", e); + } + } + + public static NoInfluence decrypt(byte[] data, byte[] key) throws IllegalBlockSizeException, + BadPaddingException, ClassNotFoundException { + byte[] decrypted = NoUtil.decrypt(data, key); + ByteArrayInputStream bais = new ByteArrayInputStream(decrypted); + try { + ObjectInputStream ois = new ObjectInputStream(bais); + NoInfluence noInfluence = (NoInfluence) ois.readObject(); + ois.close(); + bais.close(); + return noInfluence; + } catch (IOException e) { + throw new NoDashFatalException("Unable to read out provided data stream.", e); + } + } - public abstract void applyTo(NoUser user); - - public final NoByteSet getByteSet(PublicKey publicKey) { - KeyGenerator keyGen; - try { - keyGen = KeyGenerator.getInstance(NoUtil.CIPHER_KEY_SPEC); - } catch (NoSuchAlgorithmException e) { - throw new NoDashFatalException("Value for CIPHER_KEY_SPEC is not valid.", e); - } - keyGen.init(NoUtil.AES_STRENGTH); - SecretKey secretKey = keyGen.generateKey(); - byte[] key = secretKey.getEncoded(); - byte[] encryptedKey = NoUtil.encryptRSA(key, publicKey); - byte[] data = this.getEncrypted(key); - NoUtil.wipeBytes(key); - return new NoByteSet(encryptedKey, data); - } - - private final byte[] getEncrypted(byte[] key) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(this); - byte[] encrypted = NoUtil.encrypt(baos.toByteArray(), key); - oos.close(); - baos.close(); - return encrypted; - } catch (IOException e) { - throw new NoDashFatalException("Unable to write NoInfluence object to byte stream.", e); - } - } - - public static NoInfluence decrypt(byte[] data, byte[] key) throws IllegalBlockSizeException, BadPaddingException, ClassNotFoundException { - byte[] decrypted = NoUtil.decrypt(data, key); - ByteArrayInputStream bais = new ByteArrayInputStream(decrypted); - try { - ObjectInputStream ois = new ObjectInputStream(bais); - NoInfluence noInfluence = (NoInfluence) ois.readObject(); - ois.close(); - bais.close(); - return noInfluence; - } catch (IOException e) { - throw new NoDashFatalException("Unable to read out provided data stream.", e); - } - } - } diff --git a/src/nodash/models/NoSession.java b/src/nodash/models/NoSession.java index 3402781..df4e471 100644 --- a/src/nodash/models/NoSession.java +++ b/src/nodash/models/NoSession.java @@ -21,208 +21,212 @@ import nodash.exceptions.NoSessionNotAwaitingConfirmationException; import nodash.exceptions.NoUserNotValidException; public final class NoSession implements Serializable { - private static final long serialVersionUID = 1814807373427948931L; - - public static final long SESSION_DURATION = 1000 * 60 * 30; //30 minute sessions - public static enum NoState { - IDLE, MODIFIED, AWAITING_CONFIRMATION, CONFIRMED, CLOSED; - }; - - private NoUser original; - private NoState state; - private final long expiry; - private boolean newUserSession; - - public ArrayList incoming; - public NoUser current; - public UUID uuid; - - public NoSession() { - this.state = NoState.IDLE; - this.expiry = System.currentTimeMillis() + NoSession.SESSION_DURATION; - this.uuid = UUID.randomUUID(); - } - - public NoSession(NoUser newUser) { - this(); - this.state = NoState.MODIFIED; - this.original = null; - this.current = newUser; - this.newUserSession = true; - } - - public NoSession(byte[] data, char[] password) throws NoUserNotValidException { - this(); - this.newUserSession = false; - this.state = NoState.IDLE; - char[] passwordDupe = password.clone(); - try { - this.original = NoUser.createUserFromFile(data, password); - if (NoCore.hashSphere.checkHash(this.original.createHashString())) { - this.current = NoUser.createUserFromFile(data, passwordDupe); - this.uuid = UUID.randomUUID(); - NoUtil.wipeBytes(data); - } else { - throw new NoUserNotValidException(); - } - } catch (IOException e) { - throw new NoUserNotValidException(); - } catch (IllegalBlockSizeException e) { - throw new NoUserNotValidException(); - } catch (BadPaddingException e) { - throw new NoUserNotValidException(); - } catch (ClassNotFoundException e) { - throw new NoUserNotValidException(); - } - } - - public void check() throws NoSessionConfirmedException, NoSessionExpiredException { - if (this.state == NoState.CONFIRMED) { - throw new NoSessionConfirmedException(); - } else if (this.state == NoState.CLOSED || System.currentTimeMillis() > this.expiry) { - this.state = NoState.CLOSED; - throw new NoSessionExpiredException(); - } - } - - public NoState touchState() throws NoSessionConfirmedException, NoSessionExpiredException { - this.check(); - if (this.newUserSession) { - if (this.state != NoState.AWAITING_CONFIRMATION) { - this.state = NoState.MODIFIED; - } - } else { - String originalHash = this.original.createHashString(); - String currentHash = this.current.createHashString(); - if (originalHash.equals(currentHash)) { - this.state = NoState.IDLE; - } else if (this.state != NoState.AWAITING_CONFIRMATION) { - this.state = NoState.MODIFIED; - } - } - return this.state; - } - - public byte[] initiateSaveAttempt(char[] password) throws NoSessionConfirmedException, NoSessionExpiredException { - this.touchState(); - this.state = NoState.AWAITING_CONFIRMATION; - byte[] file = this.current.createFile(password); - NoUtil.wipeChars(password); - return file; - } - - public void confirmSave(byte[] confirmData, char[] password) throws NoSessionConfirmedException, NoSessionExpiredException, - NoSessionNotAwaitingConfirmationException, NoUserNotValidException { - this.check(); - if (this.state != NoState.AWAITING_CONFIRMATION) { - throw new NoSessionNotAwaitingConfirmationException(); - } - - NoUser confirmed; - try { - confirmed = NoUser.createUserFromFile(confirmData, password); - } catch (IOException e) { - throw new NoUserNotValidException(); - } catch (IllegalBlockSizeException e) { - throw new NoUserNotValidException(); - } catch (BadPaddingException e) { - throw new NoUserNotValidException(); - } catch (ClassNotFoundException e) { - throw new NoUserNotValidException(); - } - - NoUtil.wipeBytes(confirmData); - NoUtil.wipeChars(password); - if (confirmed.createHashString().equals(this.current.createHashString())) { - this.state = NoState.CONFIRMED; - /* 5.2: confirmed! */ - if (!this.newUserSession) { - /* 5.2.1: remove old hash from array */ - try { - NoCore.hashSphere.removeHash(this.original.createHashString()); - } catch (IOException e) { - throw new NoDashFatalException("Unable to remove hash on confirm.", e); - } - } - /* 5.2.2: add new hash to array */ - try { - NoCore.hashSphere.insertHash(this.current.createHashString()); - } catch (IOException e) { - throw new NoDashFatalException("Unable to remove hash on confirm.", e); - } - - /* 5.2.3: clear influences as they will not need to be re-applied */ - ArrayList actions = this.current.getNoActions(); - this.incoming = null; - this.original = null; - this.current = null; - /* 5.2.4: execute NoActions */ - for (NoAction action : actions) { - /* It is assumed that actions are not long-running tasks - * It is also assumed that actions have the information they need without the user objects */ - action.execute(); - action.purge(); - } - } else { - throw new NoUserNotValidException(); - } - } - - public NoState getNoState() throws NoSessionConfirmedException, NoSessionExpiredException { - this.touchState(); - return this.state; - } - - public NoUser getNoUser() throws NoSessionConfirmedException, NoSessionExpiredException { - this.check(); - return this.current; - } - - public UUID getUUID() { - return this.uuid; - } - - public String getUUIDAsString() { - return this.uuid.toString(); - } - - public byte[] getEncryptedUUID() { - return NoUtil.encrypt(Base64.encodeBase64(this.uuid.toString().getBytes())); - } - - public String getEncryptedUUIDAsString() { - return new String(this.getEncryptedUUID()); - } + private static final long serialVersionUID = 1814807373427948931L; - public byte[] getOriginalHash() { - if (this.original != null) { - return this.original.createHash(); - } else { - return null; - } - } - - public static UUID decryptUUID(byte[] data) throws NoDashSessionBadUUIDException { - if (data == null) { - throw new NoDashSessionBadUUIDException(); - } - - try { - return UUID.fromString(new String(Base64.decodeBase64(NoUtil.decrypt(data)))); - } catch (IllegalArgumentException e) { - throw new NoDashSessionBadUUIDException(); - }catch (IllegalBlockSizeException e) { - throw new NoDashSessionBadUUIDException(); - } catch (BadPaddingException e) { - throw new NoDashSessionBadUUIDException(); - } - } + public static final long SESSION_DURATION = 1000 * 60 * 30; // 30 minute sessions - public void consume(NoByteSet byteSet) throws NoByteSetBadDecryptionException { - this.current.consume(byteSet); - } - - public void close() { - this.state = NoState.CLOSED; - } + public static enum NoState { + IDLE, MODIFIED, AWAITING_CONFIRMATION, CONFIRMED, CLOSED; + }; + + private NoUser original; + private NoState state; + private final long expiry; + private boolean newUserSession; + + public ArrayList incoming; + public NoUser current; + public UUID uuid; + + public NoSession() { + this.state = NoState.IDLE; + this.expiry = System.currentTimeMillis() + NoSession.SESSION_DURATION; + this.uuid = UUID.randomUUID(); + } + + public NoSession(NoUser newUser) { + this(); + this.state = NoState.MODIFIED; + this.original = null; + this.current = newUser; + this.newUserSession = true; + } + + public NoSession(byte[] data, char[] password) throws NoUserNotValidException { + this(); + this.newUserSession = false; + this.state = NoState.IDLE; + char[] passwordDupe = password.clone(); + try { + this.original = NoUser.createUserFromFile(data, password); + if (NoCore.hashSphere.checkHash(this.original.createHashString())) { + this.current = NoUser.createUserFromFile(data, passwordDupe); + this.uuid = UUID.randomUUID(); + NoUtil.wipeBytes(data); + } else { + throw new NoUserNotValidException(); + } + } catch (IOException e) { + throw new NoUserNotValidException(); + } catch (IllegalBlockSizeException e) { + throw new NoUserNotValidException(); + } catch (BadPaddingException e) { + throw new NoUserNotValidException(); + } catch (ClassNotFoundException e) { + throw new NoUserNotValidException(); + } + } + + public void check() throws NoSessionConfirmedException, NoSessionExpiredException { + if (this.state == NoState.CONFIRMED) { + throw new NoSessionConfirmedException(); + } else if (this.state == NoState.CLOSED || System.currentTimeMillis() > this.expiry) { + this.state = NoState.CLOSED; + throw new NoSessionExpiredException(); + } + } + + public NoState touchState() throws NoSessionConfirmedException, NoSessionExpiredException { + this.check(); + if (this.newUserSession) { + if (this.state != NoState.AWAITING_CONFIRMATION) { + this.state = NoState.MODIFIED; + } + } else { + String originalHash = this.original.createHashString(); + String currentHash = this.current.createHashString(); + if (originalHash.equals(currentHash)) { + this.state = NoState.IDLE; + } else if (this.state != NoState.AWAITING_CONFIRMATION) { + this.state = NoState.MODIFIED; + } + } + return this.state; + } + + public byte[] initiateSaveAttempt(char[] password) throws NoSessionConfirmedException, + NoSessionExpiredException { + this.touchState(); + this.state = NoState.AWAITING_CONFIRMATION; + byte[] file = this.current.createFile(password); + NoUtil.wipeChars(password); + return file; + } + + public void confirmSave(byte[] confirmData, char[] password) throws NoSessionConfirmedException, + NoSessionExpiredException, NoSessionNotAwaitingConfirmationException, NoUserNotValidException { + this.check(); + if (this.state != NoState.AWAITING_CONFIRMATION) { + throw new NoSessionNotAwaitingConfirmationException(); + } + + NoUser confirmed; + try { + confirmed = NoUser.createUserFromFile(confirmData, password); + } catch (IOException e) { + throw new NoUserNotValidException(); + } catch (IllegalBlockSizeException e) { + throw new NoUserNotValidException(); + } catch (BadPaddingException e) { + throw new NoUserNotValidException(); + } catch (ClassNotFoundException e) { + throw new NoUserNotValidException(); + } + + NoUtil.wipeBytes(confirmData); + NoUtil.wipeChars(password); + if (confirmed.createHashString().equals(this.current.createHashString())) { + this.state = NoState.CONFIRMED; + /* 5.2: confirmed! */ + if (!this.newUserSession) { + /* 5.2.1: remove old hash from array */ + try { + NoCore.hashSphere.removeHash(this.original.createHashString()); + } catch (IOException e) { + throw new NoDashFatalException("Unable to remove hash on confirm.", e); + } + } + /* 5.2.2: add new hash to array */ + try { + NoCore.hashSphere.insertHash(this.current.createHashString()); + } catch (IOException e) { + throw new NoDashFatalException("Unable to remove hash on confirm.", e); + } + + /* 5.2.3: clear influences as they will not need to be re-applied */ + ArrayList actions = this.current.getNoActions(); + this.incoming = null; + this.original = null; + this.current = null; + /* 5.2.4: execute NoActions */ + for (NoAction action : actions) { + /* + * It is assumed that actions are not long-running tasks It is also assumed that actions + * have the information they need without the user objects + */ + action.execute(); + action.purge(); + } + } else { + throw new NoUserNotValidException(); + } + } + + public NoState getNoState() throws NoSessionConfirmedException, NoSessionExpiredException { + this.touchState(); + return this.state; + } + + public NoUser getNoUser() throws NoSessionConfirmedException, NoSessionExpiredException { + this.check(); + return this.current; + } + + public UUID getUUID() { + return this.uuid; + } + + public String getUUIDAsString() { + return this.uuid.toString(); + } + + public byte[] getEncryptedUUID() { + return NoUtil.encrypt(Base64.encodeBase64(this.uuid.toString().getBytes())); + } + + public String getEncryptedUUIDAsString() { + return new String(this.getEncryptedUUID()); + } + + public byte[] getOriginalHash() { + if (this.original != null) { + return this.original.createHash(); + } else { + return null; + } + } + + public static UUID decryptUUID(byte[] data) throws NoDashSessionBadUUIDException { + if (data == null) { + throw new NoDashSessionBadUUIDException(); + } + + try { + return UUID.fromString(new String(Base64.decodeBase64(NoUtil.decrypt(data)))); + } catch (IllegalArgumentException e) { + throw new NoDashSessionBadUUIDException(); + } catch (IllegalBlockSizeException e) { + throw new NoDashSessionBadUUIDException(); + } catch (BadPaddingException e) { + throw new NoDashSessionBadUUIDException(); + } + } + + public void consume(NoByteSet byteSet) throws NoByteSetBadDecryptionException { + this.current.consume(byteSet); + } + + public void close() { + this.state = NoState.CLOSED; + } } diff --git a/src/nodash/models/NoUser.java b/src/nodash/models/NoUser.java index ee9c4e3..dfbdd85 100644 --- a/src/nodash/models/NoUser.java +++ b/src/nodash/models/NoUser.java @@ -1,21 +1,19 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoUser allows the subclassing of custom user objects whilst keeping the - * core requirements of a NoUser: the public and private keys. It also supports - * the serialization, decryption and NoByteSet consumption. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoUser allows the subclassing of custom user objects whilst keeping the core requirements of a + * NoUser: the public and private keys. It also supports the serialization, decryption and NoByteSet + * consumption. */ package nodash.models; @@ -48,148 +46,152 @@ import nodash.exceptions.NoByteSetBadDecryptionException; import nodash.exceptions.NoDashFatalException; public class NoUser implements Serializable { - private static final long serialVersionUID = 7132405837081692211L; - private PublicKey publicKey; - private PrivateKey privateKey; - @SuppressWarnings("unused") - private String randomized; - - public int influences; - public int actions; - - private ArrayList outgoing = new ArrayList(); - - public NoUser() { - KeyPairGenerator kpg; - try { - kpg = KeyPairGenerator.getInstance(NoUtil.KEYPAIR_ALGORITHM); - } catch (NoSuchAlgorithmException e) { - throw new NoDashFatalException("Value for KEYPAIR_ALGORITHM is not valid.", e); - } + private static final long serialVersionUID = 7132405837081692211L; + private PublicKey publicKey; + private PrivateKey privateKey; + @SuppressWarnings("unused") + private String randomized; - try { - kpg.initialize(NoUtil.RSA_STRENGTH, SecureRandom.getInstance(NoUtil.SECURERANDOM_ALGORITHM, NoUtil.SECURERANDOM_PROVIDER)); - } catch (NoSuchAlgorithmException e) { - throw new NoDashFatalException("Value for SECURERANDOM_ALGORITHM not valid.", e); - } catch (NoSuchProviderException e) { - throw new NoDashFatalException("Value for SECURERANDOM_PROVIDER not valid.", e); - } - - KeyPair keyPair = kpg.generateKeyPair(); - this.publicKey = keyPair.getPublic(); - this.privateKey = keyPair.getPrivate(); - this.influences = 0; - this.actions = 0; - this.touchRandomizer(); - } - - private void touchRandomizer() { - byte[] randomBytes = new byte[64]; - try { - SecureRandom.getInstance(NoUtil.SECURERANDOM_ALGORITHM).nextBytes(randomBytes); - } catch (NoSuchAlgorithmException e) { - throw new NoDashFatalException("Value for SECURERANDOM_ALGORITHM not valid.", e); - } - this.randomized = new String(randomBytes); - } + public int influences; + public int actions; - public final byte[] createFile(char[] password) { - ArrayList temp = this.outgoing; - try { - this.touchRandomizer(); - this.outgoing = new ArrayList(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(this); - byte[] encrypted = NoUtil.encrypt(baos.toByteArray(), password); - oos.close(); - baos.close(); - return encrypted; - } catch (IOException e) { - throw new NoDashFatalException("IO Exception encountered while generating encrypted user file byte stream.", e); - } finally { - this.outgoing = temp; - } - } - - public final byte[] createHash() { - ArrayList temp = this.outgoing; - try { - this.outgoing = new ArrayList(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(this); - byte[] userBytes = baos.toByteArray(); - return NoUtil.getHashFromByteArray(userBytes); - } catch (IOException e) { - throw new NoDashFatalException("IO Exception encountered while generating user hash.", e); - } finally { - this.outgoing = temp; - } - } - - public final String createHashString() { - return new String(this.createHash()); - } + private ArrayList outgoing = new ArrayList(); - public final void consume(NoByteSet byteSet) throws NoByteSetBadDecryptionException { - try { - SecretKey secretKey = new SecretKeySpec(decryptRSA(byteSet.key), NoUtil.CIPHER_KEY_SPEC); - byte[] key = secretKey.getEncoded(); - secretKey = null; - NoInfluence influence = NoInfluence.decrypt(byteSet.data, key); - NoUtil.wipeBytes(key); - - influence.applyTo(this); - this.influences++; - } catch (BadPaddingException e) { - throw new NoByteSetBadDecryptionException(e); - } catch (IllegalBlockSizeException e) { - throw new NoByteSetBadDecryptionException(e); - } catch (ClassNotFoundException e) { - throw new NoByteSetBadDecryptionException(e); - } catch (InvalidKeyException e) { - throw new NoByteSetBadDecryptionException(e); - } - } - - public final void addAction(NoAction action) { - this.outgoing.add(action); - this.actions++; - } + public NoUser() { + KeyPairGenerator kpg; + try { + kpg = KeyPairGenerator.getInstance(NoUtil.KEYPAIR_ALGORITHM); + } catch (NoSuchAlgorithmException e) { + throw new NoDashFatalException("Value for KEYPAIR_ALGORITHM is not valid.", e); + } - public final ArrayList getNoActions() { - return this.outgoing; - } - - public final BigInteger getPublicExponent() { - return ((RSAPublicKeyImpl) publicKey).getPublicExponent(); - } - - public final BigInteger getModulus() { - return ((RSAPublicKeyImpl) publicKey).getModulus(); - } - - public final PublicKey getRSAPublicKey() { - try { - return new RSAPublicKeyImpl(this.getModulus(), this.getPublicExponent()); - } catch (InvalidKeyException e) { - throw new NoDashFatalException("Invalid key while re-generating a RSAPublicKey.", e); - } - } - - private final byte[] decryptRSA(byte[] data) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - return NoUtil.decryptRSA(data, this.privateKey); - } - - public static NoUser createUserFromFile(byte[] data, char[] password) throws IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException { - byte[] decrypted = NoUtil.decrypt(data, password); - ByteArrayInputStream bais = new ByteArrayInputStream(decrypted); - ObjectInputStream ois = new ObjectInputStream(bais); - NoUser noUser = (NoUser) ois.readObject(); - ois.close(); - bais.close(); - return noUser; - } - -} \ No newline at end of file + try { + kpg.initialize(NoUtil.RSA_STRENGTH, + SecureRandom.getInstance(NoUtil.SECURERANDOM_ALGORITHM, NoUtil.SECURERANDOM_PROVIDER)); + } catch (NoSuchAlgorithmException e) { + throw new NoDashFatalException("Value for SECURERANDOM_ALGORITHM not valid.", e); + } catch (NoSuchProviderException e) { + throw new NoDashFatalException("Value for SECURERANDOM_PROVIDER not valid.", e); + } + + KeyPair keyPair = kpg.generateKeyPair(); + this.publicKey = keyPair.getPublic(); + this.privateKey = keyPair.getPrivate(); + this.influences = 0; + this.actions = 0; + this.touchRandomizer(); + } + + private void touchRandomizer() { + byte[] randomBytes = new byte[64]; + try { + SecureRandom.getInstance(NoUtil.SECURERANDOM_ALGORITHM).nextBytes(randomBytes); + } catch (NoSuchAlgorithmException e) { + throw new NoDashFatalException("Value for SECURERANDOM_ALGORITHM not valid.", e); + } + this.randomized = new String(randomBytes); + } + + public final byte[] createFile(char[] password) { + ArrayList temp = this.outgoing; + try { + this.touchRandomizer(); + this.outgoing = new ArrayList(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(this); + byte[] encrypted = NoUtil.encrypt(baos.toByteArray(), password); + oos.close(); + baos.close(); + return encrypted; + } catch (IOException e) { + throw new NoDashFatalException( + "IO Exception encountered while generating encrypted user file byte stream.", e); + } finally { + this.outgoing = temp; + } + } + + public final byte[] createHash() { + ArrayList temp = this.outgoing; + try { + this.outgoing = new ArrayList(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(this); + byte[] userBytes = baos.toByteArray(); + return NoUtil.getHashFromByteArray(userBytes); + } catch (IOException e) { + throw new NoDashFatalException("IO Exception encountered while generating user hash.", e); + } finally { + this.outgoing = temp; + } + } + + public final String createHashString() { + return new String(this.createHash()); + } + + public final void consume(NoByteSet byteSet) throws NoByteSetBadDecryptionException { + try { + SecretKey secretKey = new SecretKeySpec(decryptRSA(byteSet.key), NoUtil.CIPHER_KEY_SPEC); + byte[] key = secretKey.getEncoded(); + secretKey = null; + NoInfluence influence = NoInfluence.decrypt(byteSet.data, key); + NoUtil.wipeBytes(key); + + influence.applyTo(this); + this.influences++; + } catch (BadPaddingException e) { + throw new NoByteSetBadDecryptionException(e); + } catch (IllegalBlockSizeException e) { + throw new NoByteSetBadDecryptionException(e); + } catch (ClassNotFoundException e) { + throw new NoByteSetBadDecryptionException(e); + } catch (InvalidKeyException e) { + throw new NoByteSetBadDecryptionException(e); + } + } + + public final void addAction(NoAction action) { + this.outgoing.add(action); + this.actions++; + } + + public final ArrayList getNoActions() { + return this.outgoing; + } + + public final BigInteger getPublicExponent() { + return ((RSAPublicKeyImpl) publicKey).getPublicExponent(); + } + + public final BigInteger getModulus() { + return ((RSAPublicKeyImpl) publicKey).getModulus(); + } + + public final PublicKey getRSAPublicKey() { + try { + return new RSAPublicKeyImpl(this.getModulus(), this.getPublicExponent()); + } catch (InvalidKeyException e) { + throw new NoDashFatalException("Invalid key while re-generating a RSAPublicKey.", e); + } + } + + private final byte[] decryptRSA(byte[] data) throws InvalidKeyException, + IllegalBlockSizeException, BadPaddingException { + return NoUtil.decryptRSA(data, this.privateKey); + } + + public static NoUser createUserFromFile(byte[] data, char[] password) + throws IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException { + byte[] decrypted = NoUtil.decrypt(data, password); + ByteArrayInputStream bais = new ByteArrayInputStream(decrypted); + ObjectInputStream ois = new ObjectInputStream(bais); + NoUser noUser = (NoUser) ois.readObject(); + ois.close(); + bais.close(); + return noUser; + } + +} diff --git a/src/nodash/models/noactiontypes/NoErrorableAction.java b/src/nodash/models/noactiontypes/NoErrorableAction.java index 5bd3319..5db40c1 100644 --- a/src/nodash/models/noactiontypes/NoErrorableAction.java +++ b/src/nodash/models/noactiontypes/NoErrorableAction.java @@ -1,25 +1,22 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoErrorableAction is a subclassing of NoTargetedAction for user-server - * interactions that require an error to be returned if a - * NoCannotGetInfluenceException is thrown. The target is not a destination user, - * but is instead treated as the source. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * As with all sourced actions it is advised to avoid their use unless the logic - * demands it, as it establishes a connection between a server action and a user address. + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoErrorableAction is a subclassing of NoTargetedAction for user-server interactions that require + * an error to be returned if a NoCannotGetInfluenceException is thrown. The target is not a + * destination user, but is instead treated as the source. + * + * As with all sourced actions it is advised to avoid their use unless the logic demands it, as it + * establishes a connection between a server action and a user address. */ package nodash.models.noactiontypes; @@ -32,27 +29,27 @@ import nodash.models.NoByteSet; import nodash.models.NoInfluence; public abstract class NoErrorableAction extends NoTargetedAction { - private static final long serialVersionUID = -6077150774349400823L; + private static final long serialVersionUID = -6077150774349400823L; - public NoErrorableAction(PublicKey source) { - // Note that - super(source); - } + public NoErrorableAction(PublicKey source) { + // Note that + super(source); + } - public void execute() { - this.process(); - try { - NoInfluence influence = this.generateTargetInfluence(); - if (influence != null) { - NoByteSet byteSet = influence.getByteSet(this.target); - NoCore.addByteSet(byteSet, this.target); - } - } catch (NoCannotGetInfluenceException e) { - NoInfluence errorInfluence = e.getResponseInfluence(); - if (errorInfluence != null) { - NoByteSet byteSet = errorInfluence.getByteSet(this.target); - NoCore.addByteSet(byteSet, this.target); - } - } - } + public void execute() { + this.process(); + try { + NoInfluence influence = this.generateTargetInfluence(); + if (influence != null) { + NoByteSet byteSet = influence.getByteSet(this.target); + NoCore.addByteSet(byteSet, this.target); + } + } catch (NoCannotGetInfluenceException e) { + NoInfluence errorInfluence = e.getResponseInfluence(); + if (errorInfluence != null) { + NoByteSet byteSet = errorInfluence.getByteSet(this.target); + NoCore.addByteSet(byteSet, this.target); + } + } + } } diff --git a/src/nodash/models/noactiontypes/NoHandshakeAction.java b/src/nodash/models/noactiontypes/NoHandshakeAction.java index 84dc23c..ac8fe76 100644 --- a/src/nodash/models/noactiontypes/NoHandshakeAction.java +++ b/src/nodash/models/noactiontypes/NoHandshakeAction.java @@ -1,25 +1,22 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoHandshakeAction is a subclass of the NoSourcedAction with logic to - * generate an applying influence as well as a returned influence, whilst - * also being capable of returned an error influence if the - * NoCannotGetInfluenceException is thrown. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * As with all two-way or sourced actions, their use should be sparing as - * it establishes a connection between two user addresses. + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoHandshakeAction is a subclass of the NoSourcedAction with logic to generate an applying + * influence as well as a returned influence, whilst also being capable of returned an error + * influence if the NoCannotGetInfluenceException is thrown. + * + * As with all two-way or sourced actions, their use should be sparing as it establishes a + * connection between two user addresses. */ package nodash.models.noactiontypes; @@ -31,39 +28,39 @@ import nodash.exceptions.NoCannotGetInfluenceException; import nodash.models.NoByteSet; import nodash.models.NoInfluence; -public abstract class NoHandshakeAction extends NoSourcedAction { - private static final long serialVersionUID = 3195466136587475680L; +public abstract class NoHandshakeAction extends NoSourcedAction { + private static final long serialVersionUID = 3195466136587475680L; - protected abstract NoInfluence generateReturnedInfluence(); - - public NoHandshakeAction(PublicKey target, PublicKey source) { - super(target, source); - } - - public void execute() { - this.process(); - try { - NoInfluence influence = this.generateTargetInfluence(); - if (influence != null) { - NoByteSet byteSet = influence.getByteSet(this.target); - NoCore.addByteSet(byteSet, this.target); - } - - NoInfluence result = this.generateReturnedInfluence(); - if (result != null) { - NoByteSet byteSet = result.getByteSet(this.source); - NoCore.addByteSet(byteSet, this.source); - } - } catch (NoCannotGetInfluenceException e) { - NoInfluence errorInfluence = e.getResponseInfluence(); - if (errorInfluence != null) { - NoByteSet byteSet = errorInfluence.getByteSet(this.source); - NoCore.addByteSet(byteSet, this.source); - } - } - } - - public void purge() { - super.purge(); - } + protected abstract NoInfluence generateReturnedInfluence(); + + public NoHandshakeAction(PublicKey target, PublicKey source) { + super(target, source); + } + + public void execute() { + this.process(); + try { + NoInfluence influence = this.generateTargetInfluence(); + if (influence != null) { + NoByteSet byteSet = influence.getByteSet(this.target); + NoCore.addByteSet(byteSet, this.target); + } + + NoInfluence result = this.generateReturnedInfluence(); + if (result != null) { + NoByteSet byteSet = result.getByteSet(this.source); + NoCore.addByteSet(byteSet, this.source); + } + } catch (NoCannotGetInfluenceException e) { + NoInfluence errorInfluence = e.getResponseInfluence(); + if (errorInfluence != null) { + NoByteSet byteSet = errorInfluence.getByteSet(this.source); + NoCore.addByteSet(byteSet, this.source); + } + } + } + + public void purge() { + super.purge(); + } } diff --git a/src/nodash/models/noactiontypes/NoSourcedAction.java b/src/nodash/models/noactiontypes/NoSourcedAction.java index 91c6b2c..7bc8794 100644 --- a/src/nodash/models/noactiontypes/NoSourcedAction.java +++ b/src/nodash/models/noactiontypes/NoSourcedAction.java @@ -1,24 +1,21 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoSourcedAction is a subclassing of NoTargetedAction which additionally - * has a source, allowing for errors to be returned if a NoCannotGetInfluenceException - * is thrown. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at * - * It is not advised to make a habit of using these for all user-user interactions - * as they provide a clear link between two users. + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoSourcedAction is a subclassing of NoTargetedAction which additionally has a source, allowing + * for errors to be returned if a NoCannotGetInfluenceException is thrown. + * + * It is not advised to make a habit of using these for all user-user interactions as they provide a + * clear link between two users. */ package nodash.models.noactiontypes; @@ -30,35 +27,36 @@ import nodash.exceptions.NoCannotGetInfluenceException; import nodash.models.NoByteSet; import nodash.models.NoInfluence; -public abstract class NoSourcedAction extends NoTargetedAction { - private static final long serialVersionUID = -2996690472537380062L; - protected PublicKey source; - protected abstract NoInfluence generateTargetInfluence() throws NoCannotGetInfluenceException; - - public NoSourcedAction(PublicKey target, PublicKey source) { - super(target); - this.source = source; - } - - public void execute() { - this.process(); - try { - NoInfluence influence = this.generateTargetInfluence(); - if (influence != null) { - NoByteSet byteSet = influence.getByteSet(this.target); - NoCore.addByteSet(byteSet, this.target); - } - } catch (NoCannotGetInfluenceException e) { - NoInfluence errorInfluence = e.getResponseInfluence(); - if (errorInfluence != null) { - NoByteSet byteSet = errorInfluence.getByteSet(this.source); - NoCore.addByteSet(byteSet, this.source); - } - } - } - - public void purge() { - super.purge(); - this.source = null; - } +public abstract class NoSourcedAction extends NoTargetedAction { + private static final long serialVersionUID = -2996690472537380062L; + protected PublicKey source; + + protected abstract NoInfluence generateTargetInfluence() throws NoCannotGetInfluenceException; + + public NoSourcedAction(PublicKey target, PublicKey source) { + super(target); + this.source = source; + } + + public void execute() { + this.process(); + try { + NoInfluence influence = this.generateTargetInfluence(); + if (influence != null) { + NoByteSet byteSet = influence.getByteSet(this.target); + NoCore.addByteSet(byteSet, this.target); + } + } catch (NoCannotGetInfluenceException e) { + NoInfluence errorInfluence = e.getResponseInfluence(); + if (errorInfluence != null) { + NoByteSet byteSet = errorInfluence.getByteSet(this.source); + NoCore.addByteSet(byteSet, this.source); + } + } + } + + public void purge() { + super.purge(); + this.source = null; + } } diff --git a/src/nodash/models/noactiontypes/NoTargetedAction.java b/src/nodash/models/noactiontypes/NoTargetedAction.java index e6dfb1f..cd98659 100644 --- a/src/nodash/models/noactiontypes/NoTargetedAction.java +++ b/src/nodash/models/noactiontypes/NoTargetedAction.java @@ -1,20 +1,18 @@ /* * Copyright 2014 David Horscroft - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. * - * NoTargetedAction is an abstract subclassing of NoAction aimed at providing the - * basis for an action that has a user target in mind. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + * + * NoTargetedAction is an abstract subclassing of NoAction aimed at providing the basis for an + * action that has a user target in mind. */ package nodash.models.noactiontypes; @@ -29,31 +27,32 @@ import nodash.models.NoByteSet; import nodash.models.NoInfluence; public abstract class NoTargetedAction extends NoAction { - private static final long serialVersionUID = -8893381130155149646L; - protected PublicKey target; - - protected abstract NoInfluence generateTargetInfluence() throws NoCannotGetInfluenceException; - - public NoTargetedAction(PublicKey target) { - this.target = target; - } - - public void execute() { - this.process(); - try { - NoInfluence influence = this.generateTargetInfluence(); - if (influence != null) { - NoByteSet byteSet = influence.getByteSet(this.target); - NoCore.addByteSet(byteSet, this.target); - } - } catch (NoCannotGetInfluenceException e) { - if (e.getResponseInfluence() != null) { - throw new NoDashFatalException("Unsourced action has generated an error with an undeliverable influence.", e); - } - } - } - - public void purge() { - this.target = null; - } + private static final long serialVersionUID = -8893381130155149646L; + protected PublicKey target; + + protected abstract NoInfluence generateTargetInfluence() throws NoCannotGetInfluenceException; + + public NoTargetedAction(PublicKey target) { + this.target = target; + } + + public void execute() { + this.process(); + try { + NoInfluence influence = this.generateTargetInfluence(); + if (influence != null) { + NoByteSet byteSet = influence.getByteSet(this.target); + NoCore.addByteSet(byteSet, this.target); + } + } catch (NoCannotGetInfluenceException e) { + if (e.getResponseInfluence() != null) { + throw new NoDashFatalException( + "Unsourced action has generated an error with an undeliverable influence.", e); + } + } + } + + public void purge() { + this.target = null; + } } diff --git a/src/nodash/test/NoActionTest.java b/src/nodash/test/NoActionTest.java index e8c4c0d..70916e3 100644 --- a/src/nodash/test/NoActionTest.java +++ b/src/nodash/test/NoActionTest.java @@ -7,26 +7,26 @@ import nodash.models.NoInfluence; import nodash.models.noactiontypes.NoTargetedAction; public class NoActionTest extends NoTargetedAction { - /** + /** * */ - private static final long serialVersionUID = 1L; - - private String newName; - - public NoActionTest(PublicKey target, String newName) { - super(target); - this.newName = newName; - } + private static final long serialVersionUID = 1L; - @Override - protected NoInfluence generateTargetInfluence() throws NoCannotGetInfluenceException { - return new NoInfluenceTest(newName); - } + private String newName; - @Override - public void process() { - // Nothing; - } + public NoActionTest(PublicKey target, String newName) { + super(target); + this.newName = newName; + } + + @Override + protected NoInfluence generateTargetInfluence() throws NoCannotGetInfluenceException { + return new NoInfluenceTest(newName); + } + + @Override + public void process() { + // Nothing; + } } diff --git a/src/nodash/test/NoCoreTest.java b/src/nodash/test/NoCoreTest.java index 40aa19e..aecef31 100644 --- a/src/nodash/test/NoCoreTest.java +++ b/src/nodash/test/NoCoreTest.java @@ -16,776 +16,801 @@ import nodash.exceptions.NoUserNotValidException; import nodash.models.NoSession.NoState; public class NoCoreTest { - private static final String[] CHANGE = new String[] { - "first-string", - "second-string", - "third-string", - "forth-string", - "fifth-string", - "sixth-string", - "seventh-string", - "eighth-string", - "ninth-string", - "tenth-string" - }; - private static Iterator CHANGES = Arrays.asList(CHANGE).iterator(); - - private static final String PASSWORD = "password"; - private static final String BAD_PASSWORD = "bad-password"; - private static final Logger logger = Logger.getLogger("NoCoreTest"); - - private static boolean silent = false; - private static boolean printStackTraces = false; - - private static Object passoverData; + private static final String[] CHANGE = new String[] {"first-string", "second-string", + "third-string", "forth-string", "fifth-string", "sixth-string", "seventh-string", + "eighth-string", "ninth-string", "tenth-string"}; + private static Iterator CHANGES = Arrays.asList(CHANGE).iterator(); - public static void setPrintStackTraces(boolean toggle) { - printStackTraces = toggle; - } - - public static void setSilence(boolean toggle) { - silent = toggle; - } - - private static class TestTicker { - private int run; - private int passed; - - public void test(boolean result) { - run++; - if (result) { - passed++; - } - } - - public boolean passed() { - return run == passed; - } - - public int getRun() { - return run; - } - - public int getPassed() { - return passed; - } - - public String getResultMessage() { - return "Passed " + getPassed() + " out of " + getRun() + " tests."; - } - - public void logResultMessage() { - if (passed()) { - printIf(getResultMessage()); - } else { - logger.severe(getResultMessage()); - } - } - } - - private static void printIf(Exception e) { - if (printStackTraces) { - e.printStackTrace(); - } - } - - private static void printIf(String s) { - if (!silent) { - logger.info(s); - } - } - - private static void checkSetup() { - if (!NoCore.isReady()) { - throw new NoTestNotReadyException("NoCore is not ready to test."); - } - } - - private static byte[] modifyByteArray(byte[] array) { - if (array.length > 0) { - if (array[0] == 'A') { - array[0] = 'B'; - } else { - array[0] = 'A'; - } - } - return array; - } - - private static byte[] copy(byte[] array) { - return Arrays.copyOf(array, array.length); - } - - /* - * BEGIN Registration Methods - */ - public static boolean testRegistrationFailureBadCookie() { - printIf("Testing registration failure with a bad cookie."); - checkSetup(); - NoUserTest user = new NoUserTest(CHANGE[0]); - NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); - byte[] cookie = modifyByteArray(register.cookie); - try { - NoCore.confirm(cookie, PASSWORD.toCharArray(), register.data); - logger.severe("Registration with bad cookie throws no errors."); - } catch (NoDashSessionBadUUIDException e) { - printIf("NoDashSessionBadUUIDException thrown, passed."); - return true; - } catch (Exception e) { - logger.severe("Wrong error thrown, should have been NoDashSessionBadUUIDException, was " + e.getClass().getSimpleName()); - printIf(e); - } - return false; - } - - public static boolean testRegistrationFailureBadData() { - printIf("Testing registration failure with a bad data stream."); - checkSetup(); - NoUserTest user = new NoUserTest(CHANGE[0]); - NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); - byte[] data = modifyByteArray(register.data); - try { - NoCore.confirm(register.cookie, PASSWORD.toCharArray(), data); - logger.severe("Registration with bad d throws no errors."); - } catch (NoUserNotValidException e) { - printIf("NoUserNotValidException thrown, passed."); - return true; - } catch (Exception e) { - logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName()); - printIf(e); - } - return false; - } - - public static boolean testRegistrationFailureBadPassword() { - printIf("Testing registration failure with a bad password."); - checkSetup(); - NoUserTest user = new NoUserTest(CHANGE[0]); - NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); - try { - NoCore.confirm(register.cookie, BAD_PASSWORD.toCharArray(), register.data); - logger.severe("Registration with bad d throws no errors."); - } catch (NoUserNotValidException e) { - printIf("NoUserNotValidException thrown, passed."); - return true; - } catch (Exception e) { - logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName()); - printIf(e); - } - return false; - } - - public static boolean testRegistrationFailure() { - printIf("Testing registration failure."); - checkSetup(); - - TestTicker ticker = new TestTicker(); - - ticker.test(testRegistrationFailureBadCookie()); - ticker.test(testRegistrationFailureBadData()); - ticker.test(testRegistrationFailureBadPassword()); - - ticker.logResultMessage(); - return ticker.passed(); - } - - public static boolean testRegistrationSuccess() { - printIf("Testing successful registration."); - checkSetup(); + private static final String PASSWORD = "password"; + private static final String BAD_PASSWORD = "bad-password"; + private static final Logger logger = Logger.getLogger("NoCoreTest"); - NoUserTest user = new NoUserTest(CHANGE[0]); - NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); - try { - NoCore.confirm(register.cookie, PASSWORD.toCharArray(), copy(register.data)); - } catch (Exception e) { - logger.severe("Error thrown on confirm, of type " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - printIf("Registration completed without errors. Attempting login to confirm."); - byte[] cookie; - try { - cookie = NoCore.login(register.data, PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown on login, of type " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - NoUserTest accessed; - try { - accessed = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown on getUser, of type " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - if (!accessed.getPublicExponent().equals(user.getPublicExponent())) { - logger.severe("Received user object from getUser has a different Public Exponent to the registered user."); - return false; - } - - printIf("Successfully registered, logged in and retrieved user information."); - return true; - } - - public static boolean testRegistration() { - printIf("Testing registration paths."); - checkSetup(); - - TestTicker ticker = new TestTicker(); - - ticker.test(testRegistrationFailure()); - ticker.test(testRegistrationSuccess()); - - ticker.logResultMessage(); - return ticker.passed(); - } - - /* - * END Registration Methods - * - * BEGIN Login methods - */ - - private static byte[] registerAndGetBytes() { - printIf("Registering..."); + private static boolean silent = false; + private static boolean printStackTraces = false; - NoUserTest user = new NoUserTest(CHANGES.next()); - printIf("Generated user, changeableString: " + user.getChangableString()); - NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); - byte[] userFile = copy(register.data); - try { - NoCore.confirm(register.cookie, PASSWORD.toCharArray(), register.data); - } catch (Exception e) { - logger.severe("Error encountered while trying to register, of type " + e.getClass().getSimpleName()); - printIf(e); - throw new NoTestNotReadyException("Failed to set up user file."); - } - return userFile; - } - - public static boolean testLoginFailBadPassword(byte[] data) { - printIf("Testing login with bad password."); - checkSetup(); - - byte[] cookie = null; - try { - cookie = NoCore.login(copy(data), BAD_PASSWORD.toCharArray()); - logger.severe("Cookie (" + Base64.encodeBase64(cookie) + ") returned, even with bad password."); - } catch (NoUserNotValidException e) { - printIf("NoUserNotValidException thrown, passed."); - return true; - } catch (Exception e) { - logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName()); - printIf(e); - } finally { - NoCore.shred(cookie); - } - - return false; - } - - public static boolean testLoginFailBadData(byte[] data) { - printIf("Testing login with bad data."); - checkSetup(); - - byte[] dataCopy = copy(data); - dataCopy = modifyByteArray(dataCopy); - byte[] cookie = null; - try { - cookie = NoCore.login(dataCopy, PASSWORD.toCharArray()); - logger.severe("Cookie (" + Base64.encodeBase64(cookie) + ") returned, even with bad data."); - } catch (NoUserNotValidException e) { - printIf("NoUserNotValidException thrown, passed."); - return true; - } catch (Exception e) { - logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + e.getClass().getSimpleName()); - printIf(e); - } finally { - NoCore.shred(cookie); - } - - return false; - } - - public static boolean testLoginFailMultipleSessions(byte[] data) { - printIf("Testing that multiple sessions throw an error."); - checkSetup(); - - byte[] cookie; - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - printIf("Received cookie (" + new String(cookie) + ")"); - } catch (Exception e) { - logger.severe("Error thrown, should have logged in, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - byte[] secondCookie = null; - try { - secondCookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - logger.severe("Cookie (" + new String(secondCookie) + ") returned, even with concurrent session."); - } catch (NoUserAlreadyOnlineException e) { - printIf("NoUserAlreadyOnlineException thrown, passed."); - return true; - } catch (Exception e) { - logger.severe("Wrong error thrown, should have been NoUserAlreadyOnlineException, was " + e.getClass().getSimpleName()); - printIf(e); - } finally { - NoCore.shred(secondCookie); - NoCore.shred(cookie); - } - - return false; - } - - public static boolean testLoginFail() { - return testLoginFail(registerAndGetBytes()); - } - - public static boolean testLoginFail(byte[] data) { - printIf("Testing login failure methods."); - checkSetup(); - - TestTicker ticker = new TestTicker(); - ticker.test(testLoginFailBadPassword(data)); - ticker.test(testLoginFailBadData(data)); - ticker.test(testLoginFailMultipleSessions(data)); - - ticker.logResultMessage(); - return ticker.passed(); - } - - public static boolean testLoginSuccess(byte[] data) { - printIf("Testing successful login and user/state retrieval."); - checkSetup(); - - byte[] cookie = null; - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown, should have logged in, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - try { - NoState state = NoCore.getSessionState(cookie); - if (state != NoState.IDLE) { - logger.severe("Returned state is not IDLE, instead '" + state.toString() + "'"); - return false; - } - } catch (Exception e) { - logger.severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - NoUserTest user = null; - try { - user = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } + private static Object passoverData; - printIf("User login successful, changableString: " + user.getChangableString()); - NoCore.shred(cookie); - return true; - } - - public static boolean testLogin() { - return testLogin(registerAndGetBytes()); - } - - public static boolean testLogin(byte[] data) { - printIf("Testing all login methods."); - checkSetup(); - - TestTicker ticker = new TestTicker(); - ticker.test(testLoginFail(data)); - ticker.test(testLoginSuccess(data)); - - ticker.logResultMessage(); - return ticker.passed(); - } - - /* - * END Login methods - * BEGIN Login-Logout methods - */ - - public static boolean testLoginModifyLogout(byte[] data) { - printIf("Testing login, change changableString, save-logout."); - checkSetup(); - - byte[] cookie = null; - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown, should have returned cookie, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - printIf("Cookie recieved."); - - NoUserTest user; - try { - user = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - printIf("User object received."); - String original = user.getChangableString(); - user.setChangableString(CHANGES.next()); - - NoState stateModified; - try { - stateModified = NoCore.getSessionState(cookie); - } catch (Exception e) { - logger.severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - if (stateModified != NoState.MODIFIED) { - logger.severe("State not MODIFIED."); - NoCore.shred(cookie); - return false; - } - printIf("State is MODIFIED."); - - byte[] newData; - try { - newData = NoCore.requestSave(cookie, PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown, should have returned new byte array, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - printIf("New data stream received."); - - NoState stateAwaiting; - try { - stateAwaiting = NoCore.getSessionState(cookie); - } catch (Exception e) { - logger.severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - if (stateAwaiting != NoState.AWAITING_CONFIRMATION) { - logger.severe("State not AWAITING_CONFIRMATION."); - NoCore.shred(cookie); - return false; - } - printIf("State is AWAITING_CONFIRMATION."); - - try { - NoCore.confirm(cookie, PASSWORD.toCharArray(), copy(newData)); - } catch (Exception e) { - logger.severe("Error thrown, should have confirmed, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - printIf("Confirm raised no errors."); - passoverData = copy(newData); - data = copy(newData); - - try { - NoCore.getSessionState(cookie); - logger.severe("Get session state threw no errors after confirmation."); - return false; - } catch (NoSessionConfirmedException e) { - printIf("NoSessionConfirmed exception thrown."); - } catch (Exception e) { - logger.severe("Error thrown, should have been NoSessionConfirmedException, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } finally { - user = null; - } - - // Log in again to check changes - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown, should have returned cookie, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - printIf("Cookie recieved for second login."); + public static void setPrintStackTraces(boolean toggle) { + printStackTraces = toggle; + } - try { - user = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown on second login, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - printIf("User object received on second login."); - - if (!user.getChangableString().equals(original)) { - printIf("Changable string has changed and saved."); - NoCore.shred(cookie); - return true; - } else { - logger.severe("Changable string has not changed."); - NoCore.shred(cookie); - return false; - } - } - - public static boolean testActionInfluenceLifecycle(byte[] data) { - printIf("Testing an action-influence cycle between two users."); - checkSetup(); - - // First, log in, get the user Public Address and save the current name, log out - PublicKey address; - String currentString; - byte[] cookie = null; - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - NoUserTest user = (NoUserTest) NoCore.getUser(cookie); - address = user.getRSAPublicKey(); - currentString = user.getChangableString(); - } catch (Exception e) { - logger.severe("Error thrown on address-getting login, gotten address and string, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } finally { - NoCore.shred(cookie); - } - printIf("Got public address."); - - // Create a second user - byte[] secondUserData = registerAndGetBytes(); - byte[] secondUserCookie; - try { - secondUserCookie = NoCore.login(copy(secondUserData), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown on second user login, should have returned cookie, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - NoUserTest user; - try { - user = (NoUserTest) NoCore.getUser(secondUserCookie); - } catch (Exception e) { - logger.severe("Error thrown on second user login, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - // Create outgoing action - NoActionTest action = new NoActionTest(address, CHANGES.next()); - user.addAction(action); - printIf("Action added to second user."); - - // Save-confirm user - try { - secondUserData = NoCore.requestSave(secondUserCookie, PASSWORD.toCharArray()); - NoCore.confirm(secondUserCookie, PASSWORD.toCharArray(), copy(secondUserData)); - } catch (Exception e) { - logger.severe("Error thrown on second user confirm, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(secondUserCookie); - return false; - } - printIf("Logged out of second user."); - - // Log in as first user, should get changes - printIf("Logging into first user again."); - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown on first user, second login, should have returned cookie, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - NoState state; - try { - state = NoCore.getSessionState(cookie); - } catch (Exception e) { - logger.severe("Error thrown on first user, second login, should have returned state, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - if (state != NoState.MODIFIED) { - logger.severe("Was expecting state to be MODIFIED, instead was " + state.toString()); - return false; - } - - try { - user = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown on first user, second login, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - - if (user.getChangableString().equals(currentString)) { - logger.severe("User information has not changed (still " + user.getChangableString() + ")."); - return false; - } - printIf("User string changed on first return login, (" + currentString + " to " + user.getChangableString() + ")!"); - - // Test that the influence resets accordingly on hotpull - NoCore.shred(cookie); - - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown on first user, third login, should have returned cookie, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } + public static void setSilence(boolean toggle) { + silent = toggle; + } - try { - state = NoCore.getSessionState(cookie); - } catch (Exception e) { - logger.severe("Error thrown on first user, third login, should have returned state, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - if (state != NoState.MODIFIED) { - logger.severe("Was expecting state to be MODIFIED, instead was " + state.toString()); - return false; - } - - try { - user = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown on first user, third login, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - - if (user.getChangableString().equals(currentString)) { - logger.severe("User information has not changed (still " + user.getChangableString() + ")."); - return false; - } - printIf("User string changed on second return login, (" + currentString + " to " + user.getChangableString() + ")!"); - - // Save-confirm - try { - data = NoCore.requestSave(cookie, PASSWORD.toCharArray()); - NoCore.confirm(cookie, PASSWORD.toCharArray(), copy(data)); - passoverData = copy(data); - } catch (Exception e) { - logger.severe("Error thrown on first user, save-confirm, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } - - // Final login, check that data has changed AND state is IDLE + private static class TestTicker { + private int run; + private int passed; - try { - cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); - } catch (Exception e) { - logger.severe("Error thrown on first user, final login, should have returned cookie, was " + e.getClass().getSimpleName()); - printIf(e); - return false; - } + public void test(boolean result) { + run++; + if (result) { + passed++; + } + } - try { - state = NoCore.getSessionState(cookie); - } catch (Exception e) { - logger.severe("Error thrown on first user, final login, should have returned state, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - if (state != NoState.IDLE) { - logger.severe("Was expecting state to be IDLE, instead was " + state.toString()); - return false; - } - - try { - user = (NoUserTest) NoCore.getUser(cookie); - } catch (Exception e) { - logger.severe("Error thrown on first user, final login, should have returned user, was " + e.getClass().getSimpleName()); - printIf(e); - NoCore.shred(cookie); - return false; - } - - if (user.getChangableString().equals(currentString)) { - logger.severe("User information has not changed (still " + user.getChangableString() + ")."); - return false; - } - printIf("User string changed on final login (" + currentString + " to " + user.getChangableString() + "), while IDLE!"); - return true; - } - - public static boolean testLifecycle(byte[] data) { - printIf("Running life-cycle tests."); - checkSetup(); - - TestTicker ticker = new TestTicker(); - ticker.test(testLoginModifyLogout(data)); - if (passoverData != null && passoverData.getClass().equals(byte[].class)) { - data = copy((byte[])passoverData); - passoverData = null; - } - ticker.test(testActionInfluenceLifecycle(data)); - if (passoverData != null && passoverData.getClass().equals(byte[].class)) { - data = copy((byte[])passoverData); - passoverData = null; - } - - ticker.logResultMessage(); - return ticker.passed(); - } - - /* - * END Login-Logout methods - */ - - public static boolean testAll() { - logger.info("Running all tests."); - checkSetup(); - - TestTicker ticker = new TestTicker(); - ticker.test(testRegistration()); - - final byte[] data = registerAndGetBytes(); - ticker.test(testLogin(data)); - - ticker.test(testLifecycle(data)); - - ticker.logResultMessage(); - return ticker.passed(); - } - - public static void run() { - if (testAll()) { - logger.info("All tests passed."); - } - } - - public static void main(String[] args) { - setSilence(false); - setPrintStackTraces(true); - if (!NoCore.isReady()) { - NoCore.setup(); - } - - run(); - } + public boolean passed() { + return run == passed; + } + + public int getRun() { + return run; + } + + public int getPassed() { + return passed; + } + + public String getResultMessage() { + return "Passed " + getPassed() + " out of " + getRun() + " tests."; + } + + public void logResultMessage() { + if (passed()) { + printIf(getResultMessage()); + } else { + logger.severe(getResultMessage()); + } + } + } + + private static void printIf(Exception e) { + if (printStackTraces) { + e.printStackTrace(); + } + } + + private static void printIf(String s) { + if (!silent) { + logger.info(s); + } + } + + private static void checkSetup() { + if (!NoCore.isReady()) { + throw new NoTestNotReadyException("NoCore is not ready to test."); + } + } + + private static byte[] modifyByteArray(byte[] array) { + if (array.length > 0) { + if (array[0] == 'A') { + array[0] = 'B'; + } else { + array[0] = 'A'; + } + } + return array; + } + + private static byte[] copy(byte[] array) { + return Arrays.copyOf(array, array.length); + } + + /* + * BEGIN Registration Methods + */ + public static boolean testRegistrationFailureBadCookie() { + printIf("Testing registration failure with a bad cookie."); + checkSetup(); + NoUserTest user = new NoUserTest(CHANGE[0]); + NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); + byte[] cookie = modifyByteArray(register.cookie); + try { + NoCore.confirm(cookie, PASSWORD.toCharArray(), register.data); + logger.severe("Registration with bad cookie throws no errors."); + } catch (NoDashSessionBadUUIDException e) { + printIf("NoDashSessionBadUUIDException thrown, passed."); + return true; + } catch (Exception e) { + logger.severe("Wrong error thrown, should have been NoDashSessionBadUUIDException, was " + + e.getClass().getSimpleName()); + printIf(e); + } + return false; + } + + public static boolean testRegistrationFailureBadData() { + printIf("Testing registration failure with a bad data stream."); + checkSetup(); + NoUserTest user = new NoUserTest(CHANGE[0]); + NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); + byte[] data = modifyByteArray(register.data); + try { + NoCore.confirm(register.cookie, PASSWORD.toCharArray(), data); + logger.severe("Registration with bad d throws no errors."); + } catch (NoUserNotValidException e) { + printIf("NoUserNotValidException thrown, passed."); + return true; + } catch (Exception e) { + logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + + e.getClass().getSimpleName()); + printIf(e); + } + return false; + } + + public static boolean testRegistrationFailureBadPassword() { + printIf("Testing registration failure with a bad password."); + checkSetup(); + NoUserTest user = new NoUserTest(CHANGE[0]); + NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); + try { + NoCore.confirm(register.cookie, BAD_PASSWORD.toCharArray(), register.data); + logger.severe("Registration with bad d throws no errors."); + } catch (NoUserNotValidException e) { + printIf("NoUserNotValidException thrown, passed."); + return true; + } catch (Exception e) { + logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + + e.getClass().getSimpleName()); + printIf(e); + } + return false; + } + + public static boolean testRegistrationFailure() { + printIf("Testing registration failure."); + checkSetup(); + + TestTicker ticker = new TestTicker(); + + ticker.test(testRegistrationFailureBadCookie()); + ticker.test(testRegistrationFailureBadData()); + ticker.test(testRegistrationFailureBadPassword()); + + ticker.logResultMessage(); + return ticker.passed(); + } + + public static boolean testRegistrationSuccess() { + printIf("Testing successful registration."); + checkSetup(); + + NoUserTest user = new NoUserTest(CHANGE[0]); + NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); + try { + NoCore.confirm(register.cookie, PASSWORD.toCharArray(), copy(register.data)); + } catch (Exception e) { + logger.severe("Error thrown on confirm, of type " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + printIf("Registration completed without errors. Attempting login to confirm."); + byte[] cookie; + try { + cookie = NoCore.login(register.data, PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown on login, of type " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + NoUserTest accessed; + try { + accessed = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown on getUser, of type " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + if (!accessed.getPublicExponent().equals(user.getPublicExponent())) { + logger + .severe("Received user object from getUser has a different Public Exponent to the registered user."); + return false; + } + + printIf("Successfully registered, logged in and retrieved user information."); + return true; + } + + public static boolean testRegistration() { + printIf("Testing registration paths."); + checkSetup(); + + TestTicker ticker = new TestTicker(); + + ticker.test(testRegistrationFailure()); + ticker.test(testRegistrationSuccess()); + + ticker.logResultMessage(); + return ticker.passed(); + } + + /* + * END Registration Methods + * + * BEGIN Login methods + */ + + private static byte[] registerAndGetBytes() { + printIf("Registering..."); + + NoUserTest user = new NoUserTest(CHANGES.next()); + printIf("Generated user, changeableString: " + user.getChangableString()); + NoRegister register = NoCore.register(user, PASSWORD.toCharArray()); + byte[] userFile = copy(register.data); + try { + NoCore.confirm(register.cookie, PASSWORD.toCharArray(), register.data); + } catch (Exception e) { + logger.severe("Error encountered while trying to register, of type " + + e.getClass().getSimpleName()); + printIf(e); + throw new NoTestNotReadyException("Failed to set up user file."); + } + return userFile; + } + + public static boolean testLoginFailBadPassword(byte[] data) { + printIf("Testing login with bad password."); + checkSetup(); + + byte[] cookie = null; + try { + cookie = NoCore.login(copy(data), BAD_PASSWORD.toCharArray()); + logger.severe("Cookie (" + Base64.encodeBase64(cookie) + + ") returned, even with bad password."); + } catch (NoUserNotValidException e) { + printIf("NoUserNotValidException thrown, passed."); + return true; + } catch (Exception e) { + logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + + e.getClass().getSimpleName()); + printIf(e); + } finally { + NoCore.shred(cookie); + } + + return false; + } + + public static boolean testLoginFailBadData(byte[] data) { + printIf("Testing login with bad data."); + checkSetup(); + + byte[] dataCopy = copy(data); + dataCopy = modifyByteArray(dataCopy); + byte[] cookie = null; + try { + cookie = NoCore.login(dataCopy, PASSWORD.toCharArray()); + logger.severe("Cookie (" + Base64.encodeBase64(cookie) + ") returned, even with bad data."); + } catch (NoUserNotValidException e) { + printIf("NoUserNotValidException thrown, passed."); + return true; + } catch (Exception e) { + logger.severe("Wrong error thrown, should have been NoUserNotValidException, was " + + e.getClass().getSimpleName()); + printIf(e); + } finally { + NoCore.shred(cookie); + } + + return false; + } + + public static boolean testLoginFailMultipleSessions(byte[] data) { + printIf("Testing that multiple sessions throw an error."); + checkSetup(); + + byte[] cookie; + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + printIf("Received cookie (" + new String(cookie) + ")"); + } catch (Exception e) { + logger.severe("Error thrown, should have logged in, was " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + byte[] secondCookie = null; + try { + secondCookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + logger.severe("Cookie (" + new String(secondCookie) + + ") returned, even with concurrent session."); + } catch (NoUserAlreadyOnlineException e) { + printIf("NoUserAlreadyOnlineException thrown, passed."); + return true; + } catch (Exception e) { + logger.severe("Wrong error thrown, should have been NoUserAlreadyOnlineException, was " + + e.getClass().getSimpleName()); + printIf(e); + } finally { + NoCore.shred(secondCookie); + NoCore.shred(cookie); + } + + return false; + } + + public static boolean testLoginFail() { + return testLoginFail(registerAndGetBytes()); + } + + public static boolean testLoginFail(byte[] data) { + printIf("Testing login failure methods."); + checkSetup(); + + TestTicker ticker = new TestTicker(); + ticker.test(testLoginFailBadPassword(data)); + ticker.test(testLoginFailBadData(data)); + ticker.test(testLoginFailMultipleSessions(data)); + + ticker.logResultMessage(); + return ticker.passed(); + } + + public static boolean testLoginSuccess(byte[] data) { + printIf("Testing successful login and user/state retrieval."); + checkSetup(); + + byte[] cookie = null; + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown, should have logged in, was " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + try { + NoState state = NoCore.getSessionState(cookie); + if (state != NoState.IDLE) { + logger.severe("Returned state is not IDLE, instead '" + state.toString() + "'"); + return false; + } + } catch (Exception e) { + logger + .severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + NoUserTest user = null; + try { + user = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown, should have returned user, was " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + printIf("User login successful, changableString: " + user.getChangableString()); + NoCore.shred(cookie); + return true; + } + + public static boolean testLogin() { + return testLogin(registerAndGetBytes()); + } + + public static boolean testLogin(byte[] data) { + printIf("Testing all login methods."); + checkSetup(); + + TestTicker ticker = new TestTicker(); + ticker.test(testLoginFail(data)); + ticker.test(testLoginSuccess(data)); + + ticker.logResultMessage(); + return ticker.passed(); + } + + /* + * END Login methods BEGIN Login-Logout methods + */ + + public static boolean testLoginModifyLogout(byte[] data) { + printIf("Testing login, change changableString, save-logout."); + checkSetup(); + + byte[] cookie = null; + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown, should have returned cookie, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + printIf("Cookie recieved."); + + NoUserTest user; + try { + user = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown, should have returned user, was " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + printIf("User object received."); + String original = user.getChangableString(); + user.setChangableString(CHANGES.next()); + + NoState stateModified; + try { + stateModified = NoCore.getSessionState(cookie); + } catch (Exception e) { + logger + .severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + if (stateModified != NoState.MODIFIED) { + logger.severe("State not MODIFIED."); + NoCore.shred(cookie); + return false; + } + printIf("State is MODIFIED."); + + byte[] newData; + try { + newData = NoCore.requestSave(cookie, PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown, should have returned new byte array, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + printIf("New data stream received."); + + NoState stateAwaiting; + try { + stateAwaiting = NoCore.getSessionState(cookie); + } catch (Exception e) { + logger + .severe("Error thrown, should have returned state, was " + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + if (stateAwaiting != NoState.AWAITING_CONFIRMATION) { + logger.severe("State not AWAITING_CONFIRMATION."); + NoCore.shred(cookie); + return false; + } + printIf("State is AWAITING_CONFIRMATION."); + + try { + NoCore.confirm(cookie, PASSWORD.toCharArray(), copy(newData)); + } catch (Exception e) { + logger.severe("Error thrown, should have confirmed, was " + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + printIf("Confirm raised no errors."); + passoverData = copy(newData); + data = copy(newData); + + try { + NoCore.getSessionState(cookie); + logger.severe("Get session state threw no errors after confirmation."); + return false; + } catch (NoSessionConfirmedException e) { + printIf("NoSessionConfirmed exception thrown."); + } catch (Exception e) { + logger.severe("Error thrown, should have been NoSessionConfirmedException, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } finally { + user = null; + } + + // Log in again to check changes + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown, should have returned cookie, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + printIf("Cookie recieved for second login."); + + try { + user = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown on second login, should have returned user, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + printIf("User object received on second login."); + + if (!user.getChangableString().equals(original)) { + printIf("Changable string has changed and saved."); + NoCore.shred(cookie); + return true; + } else { + logger.severe("Changable string has not changed."); + NoCore.shred(cookie); + return false; + } + } + + public static boolean testActionInfluenceLifecycle(byte[] data) { + printIf("Testing an action-influence cycle between two users."); + checkSetup(); + + // First, log in, get the user Public Address and save the current name, log out + PublicKey address; + String currentString; + byte[] cookie = null; + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + NoUserTest user = (NoUserTest) NoCore.getUser(cookie); + address = user.getRSAPublicKey(); + currentString = user.getChangableString(); + } catch (Exception e) { + logger.severe("Error thrown on address-getting login, gotten address and string, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } finally { + NoCore.shred(cookie); + } + printIf("Got public address."); + + // Create a second user + byte[] secondUserData = registerAndGetBytes(); + byte[] secondUserCookie; + try { + secondUserCookie = NoCore.login(copy(secondUserData), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown on second user login, should have returned cookie, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + NoUserTest user; + try { + user = (NoUserTest) NoCore.getUser(secondUserCookie); + } catch (Exception e) { + logger.severe("Error thrown on second user login, should have returned user, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + // Create outgoing action + NoActionTest action = new NoActionTest(address, CHANGES.next()); + user.addAction(action); + printIf("Action added to second user."); + + // Save-confirm user + try { + secondUserData = NoCore.requestSave(secondUserCookie, PASSWORD.toCharArray()); + NoCore.confirm(secondUserCookie, PASSWORD.toCharArray(), copy(secondUserData)); + } catch (Exception e) { + logger.severe("Error thrown on second user confirm, should have returned user, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(secondUserCookie); + return false; + } + printIf("Logged out of second user."); + + // Log in as first user, should get changes + printIf("Logging into first user again."); + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown on first user, second login, should have returned cookie, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + NoState state; + try { + state = NoCore.getSessionState(cookie); + } catch (Exception e) { + logger.severe("Error thrown on first user, second login, should have returned state, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + if (state != NoState.MODIFIED) { + logger.severe("Was expecting state to be MODIFIED, instead was " + state.toString()); + return false; + } + + try { + user = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown on first user, second login, should have returned user, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + + if (user.getChangableString().equals(currentString)) { + logger.severe("User information has not changed (still " + user.getChangableString() + ")."); + return false; + } + printIf("User string changed on first return login, (" + currentString + " to " + + user.getChangableString() + ")!"); + + // Test that the influence resets accordingly on hotpull + NoCore.shred(cookie); + + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown on first user, third login, should have returned cookie, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + try { + state = NoCore.getSessionState(cookie); + } catch (Exception e) { + logger.severe("Error thrown on first user, third login, should have returned state, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + if (state != NoState.MODIFIED) { + logger.severe("Was expecting state to be MODIFIED, instead was " + state.toString()); + return false; + } + + try { + user = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown on first user, third login, should have returned user, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + + if (user.getChangableString().equals(currentString)) { + logger.severe("User information has not changed (still " + user.getChangableString() + ")."); + return false; + } + printIf("User string changed on second return login, (" + currentString + " to " + + user.getChangableString() + ")!"); + + // Save-confirm + try { + data = NoCore.requestSave(cookie, PASSWORD.toCharArray()); + NoCore.confirm(cookie, PASSWORD.toCharArray(), copy(data)); + passoverData = copy(data); + } catch (Exception e) { + logger + .severe("Error thrown on first user, save-confirm, was " + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + // Final login, check that data has changed AND state is IDLE + + try { + cookie = NoCore.login(copy(data), PASSWORD.toCharArray()); + } catch (Exception e) { + logger.severe("Error thrown on first user, final login, should have returned cookie, was " + + e.getClass().getSimpleName()); + printIf(e); + return false; + } + + try { + state = NoCore.getSessionState(cookie); + } catch (Exception e) { + logger.severe("Error thrown on first user, final login, should have returned state, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + if (state != NoState.IDLE) { + logger.severe("Was expecting state to be IDLE, instead was " + state.toString()); + return false; + } + + try { + user = (NoUserTest) NoCore.getUser(cookie); + } catch (Exception e) { + logger.severe("Error thrown on first user, final login, should have returned user, was " + + e.getClass().getSimpleName()); + printIf(e); + NoCore.shred(cookie); + return false; + } + + if (user.getChangableString().equals(currentString)) { + logger.severe("User information has not changed (still " + user.getChangableString() + ")."); + return false; + } + printIf("User string changed on final login (" + currentString + " to " + + user.getChangableString() + "), while IDLE!"); + return true; + } + + public static boolean testLifecycle(byte[] data) { + printIf("Running life-cycle tests."); + checkSetup(); + + TestTicker ticker = new TestTicker(); + ticker.test(testLoginModifyLogout(data)); + if (passoverData != null && passoverData.getClass().equals(byte[].class)) { + data = copy((byte[]) passoverData); + passoverData = null; + } + ticker.test(testActionInfluenceLifecycle(data)); + if (passoverData != null && passoverData.getClass().equals(byte[].class)) { + data = copy((byte[]) passoverData); + passoverData = null; + } + + ticker.logResultMessage(); + return ticker.passed(); + } + + /* + * END Login-Logout methods + */ + + public static boolean testAll() { + logger.info("Running all tests."); + checkSetup(); + + TestTicker ticker = new TestTicker(); + ticker.test(testRegistration()); + + final byte[] data = registerAndGetBytes(); + ticker.test(testLogin(data)); + + ticker.test(testLifecycle(data)); + + ticker.logResultMessage(); + return ticker.passed(); + } + + public static void run() { + if (testAll()) { + logger.info("All tests passed."); + } + } + + public static void main(String[] args) { + setSilence(false); + setPrintStackTraces(true); + if (!NoCore.isReady()) { + NoCore.setup(); + } + + run(); + } } diff --git a/src/nodash/test/NoInfluenceTest.java b/src/nodash/test/NoInfluenceTest.java index b8f9d15..14cefda 100644 --- a/src/nodash/test/NoInfluenceTest.java +++ b/src/nodash/test/NoInfluenceTest.java @@ -4,20 +4,20 @@ import nodash.models.NoInfluence; import nodash.models.NoUser; public class NoInfluenceTest extends NoInfluence { - /** + /** * */ - private static final long serialVersionUID = 5710677031891178814L; - private String newName; - - public NoInfluenceTest(String newName) { - super(); - this.newName = newName; - } + private static final long serialVersionUID = 5710677031891178814L; + private String newName; - @Override - public void applyTo(NoUser user) { - ((NoUserTest) user).setChangableString(this.newName); - } + public NoInfluenceTest(String newName) { + super(); + this.newName = newName; + } + + @Override + public void applyTo(NoUser user) { + ((NoUserTest) user).setChangableString(this.newName); + } } diff --git a/src/nodash/test/NoTestNotReadyException.java b/src/nodash/test/NoTestNotReadyException.java index 1c2e3ad..456c03b 100644 --- a/src/nodash/test/NoTestNotReadyException.java +++ b/src/nodash/test/NoTestNotReadyException.java @@ -3,13 +3,13 @@ package nodash.test; import nodash.exceptions.NoDashFatalException; public class NoTestNotReadyException extends NoDashFatalException { - /** + /** * */ - private static final long serialVersionUID = -8955061212302042899L; + private static final long serialVersionUID = -8955061212302042899L; - public NoTestNotReadyException(String string) { - super(string); - } + public NoTestNotReadyException(String string) { + super(string); + } } diff --git a/src/nodash/test/NoUserTest.java b/src/nodash/test/NoUserTest.java index 83e406c..0b4df90 100644 --- a/src/nodash/test/NoUserTest.java +++ b/src/nodash/test/NoUserTest.java @@ -4,23 +4,23 @@ import nodash.models.NoUser; public class NoUserTest extends NoUser { - /** + /** * */ - private static final long serialVersionUID = 7791713515804652613L; + private static final long serialVersionUID = 7791713515804652613L; - private String changableString; - - public NoUserTest(String changableString) { - super(); - setChangableString(changableString); - } - - public String getChangableString() { - return changableString; - } - - public void setChangableString(String changableString) { - this.changableString = changableString; - } + private String changableString; + + public NoUserTest(String changableString) { + super(); + setChangableString(changableString); + } + + public String getChangableString() { + return changableString; + } + + public void setChangableString(String changableString) { + this.changableString = changableString; + } }